graphql-client 1.0.0 → 1.1.0
raw patch · 8 files changed
+50830/−50484 lines, 8 filesdep ~aeson-schemasdep ~optparse-applicativePVP ok
version bump matches the API change (PVP)
Dependency ranges changed: aeson-schemas, optparse-applicative
API changes (from Hackage documentation)
+ Data.GraphQL.TestUtils: data AnyResultMock
+ Data.GraphQL.TestUtils: instance Control.Monad.Trans.Class.MonadTrans Data.GraphQL.TestUtils.MockQueryT
+ Data.GraphQL.TestUtils: instance GHC.Show.Show Data.GraphQL.TestUtils.AnyResultMock
- Data.GraphQL.Query: class IsSchemaObject (ResultSchema query) => GraphQLQuery query where {
+ Data.GraphQL.Query: class IsSchema (ResultSchema query) => GraphQLQuery query where {
- Data.GraphQL.Query: type family ResultSchema query :: SchemaType;
+ Data.GraphQL.Query: type family ResultSchema query :: Schema;
- Data.GraphQL.TestUtils: mocked :: GraphQLQuery query => ResultMock query -> AnyResultMock
+ Data.GraphQL.TestUtils: mocked :: (Show query, GraphQLQuery query) => ResultMock query -> AnyResultMock
Files
- CHANGELOG.md +16/−0
- README.md +2/−3
- graphql-client.cabal +5/−5
- js/graphql-codegen-haskell.js +50794/−50467
- src/Data/GraphQL/Query.hs +4/−3
- src/Data/GraphQL/TestUtils.hs +8/−3
- test/Data/GraphQL/Test/Monad/Class.hs +0/−3
- test/Data/GraphQL/Test/TestQuery.hs +1/−0
CHANGELOG.md view
@@ -1,5 +1,21 @@ ## Upcoming +## 1.1.0++Breaking changes:++* Require `aeson-schemas-1.3.0`+ * `TypeApplications` is no longer needed for `get` quasiquoters+ * See `aeson-schemas` CHANGELOG for more details+* Scalars now also need a `ToJSON` instance++Miscellaneous changes:++* Improved test-utils UX:+ * Export `AnyResultMock`+ * Add `Show` instance for `AnyResultMock`+ * Add `MonadTrans` instance for `MockQueryT`+ ## 1.0.0 Initial release:
README.md view
@@ -87,7 +87,6 @@ ```haskell {-# LANGUAGE DataKinds #-} {-# LANGUAGE QuasiQuotes #-}-{-# LANGUAGE TypeApplications #-} import Control.Monad.IO.Class (MonadIO(..)) import Data.GraphQL@@ -160,8 +159,8 @@ * `scalarsModule`: The module where custom GraphQL scalars should be exported. You may define the scalars in other modules, but you must re-export them in this module. If you're not using any custom scalars in your queries, this- module can be empty (but must still exist). All GraphQL scalars must have a- `FromJSON` instance.+ module can be empty (but must still exist). All GraphQL scalars must have+ `FromJSON` and `ToJSON` instances. ## Testing
graphql-client.cabal view
@@ -4,10 +4,10 @@ -- -- see: https://github.com/sol/hpack ----- hash: 716a43cf62d62ae97eb2545311b0b432e3b029b2de2d80055a25f22c32c49930+-- hash: 1e5cbd0fa96a9b044b801baafda6953cf3b51d16e5030235bd6bad5d908f07af name: graphql-client-version: 1.0.0+version: 1.1.0 synopsis: A client for Haskell programs to query a GraphQL API description: A client for Haskell programs to query a GraphQL API. category: Graphql@@ -47,7 +47,7 @@ ghc-options: -Wall build-depends: aeson >=1.2.4.0 && <1.6- , aeson-schemas >=1.2 && <1.3+ , aeson-schemas >=1.3 && <1.4 , base >=4.9 && <5 , http-client >=0.5.13.1 && <0.8 , http-client-tls >=0.3.5.3 && <0.4@@ -70,7 +70,7 @@ ghc-options: -Wall build-depends: aeson >=1.2.4.0 && <1.6- , aeson-schemas >=1.2 && <1.3+ , aeson-schemas >=1.3 && <1.4 , base >=4.9 && <5 , bytestring >=0.10.8.2 && <0.11 , file-embed >=0.0.10.1 && <0.0.14@@ -106,7 +106,7 @@ ghc-options: -Wall build-depends: aeson >=1.2.4.0 && <1.6- , aeson-schemas >=1.2 && <1.3+ , aeson-schemas >=1.3 && <1.4 , base >=4.9 && <5 , graphql-client , http-client >=0.5.13.1 && <0.8
js/graphql-codegen-haskell.js view
@@ -2,50473 +2,50800 @@ Object.defineProperty(exports, '__esModule', { value: true }); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }--function _interopNamespace(e) {- if (e && e.__esModule) { return e; } else {- var n = {};- if (e) {- Object.keys(e).forEach(function (k) {- var d = Object.getOwnPropertyDescriptor(e, k);- Object.defineProperty(n, k, d.get ? d : {- enumerable: true,- get: function () {- return e[k];- }- });- });- }- n['default'] = e;- return n;- }-}--var path = require('path');-var path__default = _interopDefault(path);-var fs$2 = require('fs');-var fs$2__default = _interopDefault(fs$2);-var constants$4 = _interopDefault(require('constants'));-var Stream$2 = _interopDefault(require('stream'));-var util = _interopDefault(require('util'));-var assert = _interopDefault(require('assert'));-var process$1 = require('process');-var Module = _interopDefault(require('module'));-var require$$1 = _interopDefault(require('os'));-var EventEmitter = _interopDefault(require('events'));-var http = _interopDefault(require('http'));-var Url = _interopDefault(require('url'));-var https = _interopDefault(require('https'));-var zlib = _interopDefault(require('zlib'));-var crypto = _interopDefault(require('crypto'));-var net = _interopDefault(require('net'));-var tls = _interopDefault(require('tls'));-var websocket$1 = require('websocket');--/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -var __assign = function() { - __assign = Object.assign || function __assign(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); -}; - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}--/**- * Note: This file is autogenerated using "resources/gen-version.js" script and- * automatically updated by "npm version" command.- */--/**- * A string containing the version of the GraphQL.js library- */-var version = '15.3.0';-/**- * An object containing the components of the GraphQL.js version string- */--var versionInfo = Object.freeze({- major: 15,- minor: 3,- patch: 0,- preReleaseTag: null-});--/**- * Returns true if the value acts like a Promise, i.e. has a "then" function,- * otherwise returns false.- */-// eslint-disable-next-line no-redeclare-function isPromise(value) {- return typeof (value === null || value === void 0 ? void 0 : value.then) === 'function';-}--// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')-var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;--function _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); }-var MAX_ARRAY_LENGTH = 10;-var MAX_RECURSIVE_DEPTH = 2;-/**- * Used to print values in error messages.- */--function inspect(value) {- return formatValue(value, []);-}--function formatValue(value, seenValues) {- switch (_typeof(value)) {- case 'string':- return JSON.stringify(value);-- case 'function':- return value.name ? "[function ".concat(value.name, "]") : '[function]';-- case 'object':- if (value === null) {- return 'null';- }-- return formatObjectValue(value, seenValues);-- default:- return String(value);- }-}--function formatObjectValue(value, previouslySeenValues) {- if (previouslySeenValues.indexOf(value) !== -1) {- return '[Circular]';- }-- var seenValues = [].concat(previouslySeenValues, [value]);- var customInspectFn = getCustomFn(value);-- if (customInspectFn !== undefined) {- // $FlowFixMe(>=0.90.0)- var customValue = customInspectFn.call(value); // check for infinite recursion-- if (customValue !== value) {- return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);- }- } else if (Array.isArray(value)) {- return formatArray(value, seenValues);- }-- return formatObject(value, seenValues);-}--function formatObject(object, seenValues) {- var keys = Object.keys(object);-- if (keys.length === 0) {- return '{}';- }-- if (seenValues.length > MAX_RECURSIVE_DEPTH) {- return '[' + getObjectTag(object) + ']';- }-- var properties = keys.map(function (key) {- var value = formatValue(object[key], seenValues);- return key + ': ' + value;- });- return '{ ' + properties.join(', ') + ' }';-}--function formatArray(array, seenValues) {- if (array.length === 0) {- return '[]';- }-- if (seenValues.length > MAX_RECURSIVE_DEPTH) {- return '[Array]';- }-- var len = Math.min(MAX_ARRAY_LENGTH, array.length);- var remaining = array.length - len;- var items = [];-- for (var i = 0; i < len; ++i) {- items.push(formatValue(array[i], seenValues));- }-- if (remaining === 1) {- items.push('... 1 more item');- } else if (remaining > 1) {- items.push("... ".concat(remaining, " more items"));- }-- return '[' + items.join(', ') + ']';-}--function getCustomFn(object) {- var customInspectFn = object[String(nodejsCustomInspectSymbol)];-- if (typeof customInspectFn === 'function') {- return customInspectFn;- }-- if (typeof object.inspect === 'function') {- return object.inspect;- }-}--function getObjectTag(object) {- var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, '');-- if (tag === 'Object' && typeof object.constructor === 'function') {- var name = object.constructor.name;-- if (typeof name === 'string' && name !== '') {- return name;- }- }-- return tag;-}--function devAssert(condition, message) {- var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')-- if (!booleanCondition) {- throw new Error(message);- }-}--function _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); }--/**- * Return true if `value` is object-like. A value is object-like if it's not- * `null` and has a `typeof` result of "object".- */-function isObjectLike(value) {- return _typeof$1(value) == 'object' && value !== null;-}--// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator-// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')-var SYMBOL_ITERATOR = typeof Symbol === 'function' ? Symbol.iterator : '@@iterator'; // In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator-// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')--var SYMBOL_ASYNC_ITERATOR = // $FlowFixMe Flow doesn't define `Symbol.asyncIterator` yet-typeof Symbol === 'function' ? Symbol.asyncIterator : '@@asyncIterator'; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')--var SYMBOL_TO_STRING_TAG = // $FlowFixMe Flow doesn't define `Symbol.toStringTag` yet-typeof Symbol === 'function' ? Symbol.toStringTag : '@@toStringTag';--/**- * Represents a location in a Source.- */--/**- * Takes a Source and a UTF-8 character offset, and returns the corresponding- * line and column as a SourceLocation.- */-function getLocation(source, position) {- var lineRegexp = /\r\n|[\n\r]/g;- var line = 1;- var column = position + 1;- var match;-- while ((match = lineRegexp.exec(source.body)) && match.index < position) {- line += 1;- column = position + 1 - (match.index + match[0].length);- }-- return {- line: line,- column: column- };-}--/**- * Render a helpful description of the location in the GraphQL Source document.- */--function printLocation(location) {- return printSourceLocation(location.source, getLocation(location.source, location.start));-}-/**- * Render a helpful description of the location in the GraphQL Source document.- */--function printSourceLocation(source, sourceLocation) {- var firstLineColumnOffset = source.locationOffset.column - 1;- var body = whitespace(firstLineColumnOffset) + source.body;- var lineIndex = sourceLocation.line - 1;- var lineOffset = source.locationOffset.line - 1;- var lineNum = sourceLocation.line + lineOffset;- var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;- var columnNum = sourceLocation.column + columnOffset;- var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");- var lines = body.split(/\r\n|[\n\r]/g);- var locationLine = lines[lineIndex]; // Special case for minified documents-- if (locationLine.length > 120) {- var subLineIndex = Math.floor(columnNum / 80);- var subLineColumnNum = columnNum % 80;- var subLines = [];-- for (var i = 0; i < locationLine.length; i += 80) {- subLines.push(locationLine.slice(i, i + 80));- }-- return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {- return ['', subLine];- }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));- }-- return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"],- ["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]);-}--function printPrefixedLines(lines) {- var existingLines = lines.filter(function (_ref) {- var _ = _ref[0],- line = _ref[1];- return line !== undefined;- });- var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {- var prefix = _ref2[0];- return prefix.length;- }));- return existingLines.map(function (_ref3) {- var prefix = _ref3[0],- line = _ref3[1];- return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');- }).join('\n');-}--function whitespace(len) {- return Array(len + 1).join(' ');-}--function leftPad(len, str) {- return whitespace(len - str.length) + str;-}--function _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); }--function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }--function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }--function _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); }--function _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); }; }--function _possibleConstructorReturn(self, call) { if (call && (_typeof$2(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }--function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }--function _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); }--function _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); }--function _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; } }--function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }--function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }--function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }-/**- * A GraphQLError describes an Error found during the parse, validate, or- * execute phases of performing a GraphQL operation. In addition to a message- * and stack trace, it also includes information about the locations in a- * GraphQL document and/or execution result that correspond to the Error.- */--var GraphQLError = /*#__PURE__*/function (_Error) {- _inherits(GraphQLError, _Error);-- var _super = _createSuper(GraphQLError);-- /**- * A message describing the Error for debugging purposes.- *- * Enumerable, and appears in the result of JSON.stringify().- *- * Note: should be treated as readonly, despite invariant usage.- */-- /**- * An array of { line, column } locations within the source GraphQL document- * which correspond to this error.- *- * Errors during validation often contain multiple locations, for example to- * point out two things with the same name. Errors during execution include a- * single location, the field which produced the error.- *- * Enumerable, and appears in the result of JSON.stringify().- */-- /**- * An array describing the JSON-path into the execution response which- * corresponds to this error. Only included for errors during execution.- *- * Enumerable, and appears in the result of JSON.stringify().- */-- /**- * An array of GraphQL AST Nodes corresponding to this error.- */-- /**- * The source GraphQL document for the first location of this error.- *- * Note that if this Error represents more than one node, the source may not- * represent nodes after the first node.- */-- /**- * An array of character offsets within the source GraphQL document- * which correspond to this error.- */-- /**- * The original error thrown from a field resolver during execution.- */-- /**- * Extension fields to add to the formatted error.- */- function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {- var _locations2, _source2, _positions2, _extensions2;-- var _this;-- _classCallCheck(this, GraphQLError);-- _this = _super.call(this, message); // Compute list of blame nodes.-- var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.--- var _source = source;-- if (!_source && _nodes) {- var _nodes$0$loc;-- _source = (_nodes$0$loc = _nodes[0].loc) === null || _nodes$0$loc === void 0 ? void 0 : _nodes$0$loc.source;- }-- var _positions = positions;-- if (!_positions && _nodes) {- _positions = _nodes.reduce(function (list, node) {- if (node.loc) {- list.push(node.loc.start);- }-- return list;- }, []);- }-- if (_positions && _positions.length === 0) {- _positions = undefined;- }-- var _locations;-- if (positions && source) {- _locations = positions.map(function (pos) {- return getLocation(source, pos);- });- } else if (_nodes) {- _locations = _nodes.reduce(function (list, node) {- if (node.loc) {- list.push(getLocation(node.loc.source, node.loc.start));- }-- return list;- }, []);- }-- var _extensions = extensions;-- if (_extensions == null && originalError != null) {- var originalExtensions = originalError.extensions;-- if (isObjectLike(originalExtensions)) {- _extensions = originalExtensions;- }- }-- Object.defineProperties(_assertThisInitialized(_this), {- name: {- value: 'GraphQLError'- },- message: {- value: message,- // By being enumerable, JSON.stringify will include `message` in the- // resulting output. This ensures that the simplest possible GraphQL- // service adheres to the spec.- enumerable: true,- writable: true- },- locations: {- // Coercing falsy values to undefined ensures they will not be included- // in JSON.stringify() when not provided.- value: (_locations2 = _locations) !== null && _locations2 !== void 0 ? _locations2 : undefined,- // By being enumerable, JSON.stringify will include `locations` in the- // resulting output. This ensures that the simplest possible GraphQL- // service adheres to the spec.- enumerable: _locations != null- },- path: {- // Coercing falsy values to undefined ensures they will not be included- // in JSON.stringify() when not provided.- value: path !== null && path !== void 0 ? path : undefined,- // By being enumerable, JSON.stringify will include `path` in the- // resulting output. This ensures that the simplest possible GraphQL- // service adheres to the spec.- enumerable: path != null- },- nodes: {- value: _nodes !== null && _nodes !== void 0 ? _nodes : undefined- },- source: {- value: (_source2 = _source) !== null && _source2 !== void 0 ? _source2 : undefined- },- positions: {- value: (_positions2 = _positions) !== null && _positions2 !== void 0 ? _positions2 : undefined- },- originalError: {- value: originalError- },- extensions: {- // Coercing falsy values to undefined ensures they will not be included- // in JSON.stringify() when not provided.- value: (_extensions2 = _extensions) !== null && _extensions2 !== void 0 ? _extensions2 : undefined,- // By being enumerable, JSON.stringify will include `path` in the- // resulting output. This ensures that the simplest possible GraphQL- // service adheres to the spec.- enumerable: _extensions != null- }- }); // Include (non-enumerable) stack trace.-- if (originalError === null || originalError === void 0 ? void 0 : originalError.stack) {- Object.defineProperty(_assertThisInitialized(_this), 'stack', {- value: originalError.stack,- writable: true,- configurable: true- });- return _possibleConstructorReturn(_this);- } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')--- if (Error.captureStackTrace) {- Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);- } else {- Object.defineProperty(_assertThisInitialized(_this), 'stack', {- value: Error().stack,- writable: true,- configurable: true- });- }-- return _this;- }-- _createClass(GraphQLError, [{- key: "toString",- value: function toString() {- return printError(this);- } // FIXME: workaround to not break chai comparisons, should be remove in v16- // $FlowFixMe Flow doesn't support computed properties yet-- }, {- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'Object';- }- }]);-- return GraphQLError;-}( /*#__PURE__*/_wrapNativeSuper(Error));-/**- * Prints a GraphQLError to a string, representing useful location information- * about the error's position in the source.- */--function printError(error) {- var output = error.message;-- if (error.nodes) {- for (var _i2 = 0, _error$nodes2 = error.nodes; _i2 < _error$nodes2.length; _i2++) {- var node = _error$nodes2[_i2];-- if (node.loc) {- output += '\n\n' + printLocation(node.loc);- }- }- } else if (error.source && error.locations) {- for (var _i4 = 0, _error$locations2 = error.locations; _i4 < _error$locations2.length; _i4++) {- var location = _error$locations2[_i4];- output += '\n\n' + printSourceLocation(error.source, location);- }- }-- return output;-}--/**- * Produces a GraphQLError representing a syntax error, containing useful- * descriptive information about the syntax error's position in the source.- */--function syntaxError(source, position, description) {- return new GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);-}--/**- * The set of allowed kind values for AST nodes.- */-var Kind = Object.freeze({- // Name- NAME: 'Name',- // Document- DOCUMENT: 'Document',- OPERATION_DEFINITION: 'OperationDefinition',- VARIABLE_DEFINITION: 'VariableDefinition',- SELECTION_SET: 'SelectionSet',- FIELD: 'Field',- ARGUMENT: 'Argument',- // Fragments- FRAGMENT_SPREAD: 'FragmentSpread',- INLINE_FRAGMENT: 'InlineFragment',- FRAGMENT_DEFINITION: 'FragmentDefinition',- // Values- VARIABLE: 'Variable',- INT: 'IntValue',- FLOAT: 'FloatValue',- STRING: 'StringValue',- BOOLEAN: 'BooleanValue',- NULL: 'NullValue',- ENUM: 'EnumValue',- LIST: 'ListValue',- OBJECT: 'ObjectValue',- OBJECT_FIELD: 'ObjectField',- // Directives- DIRECTIVE: 'Directive',- // Types- NAMED_TYPE: 'NamedType',- LIST_TYPE: 'ListType',- NON_NULL_TYPE: 'NonNullType',- // Type System Definitions- SCHEMA_DEFINITION: 'SchemaDefinition',- OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',- // Type Definitions- SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',- OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',- FIELD_DEFINITION: 'FieldDefinition',- INPUT_VALUE_DEFINITION: 'InputValueDefinition',- INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',- UNION_TYPE_DEFINITION: 'UnionTypeDefinition',- ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',- ENUM_VALUE_DEFINITION: 'EnumValueDefinition',- INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',- // Directive Definitions- DIRECTIVE_DEFINITION: 'DirectiveDefinition',- // Type System Extensions- SCHEMA_EXTENSION: 'SchemaExtension',- // Type Extensions- SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',- OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',- INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',- UNION_TYPE_EXTENSION: 'UnionTypeExtension',- ENUM_TYPE_EXTENSION: 'EnumTypeExtension',- INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'-});-/**- * The enum type representing the possible kind values of AST nodes.- */--function invariant(condition, message) {- var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')-- if (!booleanCondition) {- throw new Error(message != null ? message : 'Unexpected invariant triggered.');- }-}--/**- * The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON`- */--function defineInspect(classObject) {- var fn = classObject.prototype.toJSON;- typeof fn === 'function' || invariant(0);- classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317')-- if (nodejsCustomInspectSymbol) {- classObject.prototype[nodejsCustomInspectSymbol] = fn;- }-}--/**- * Contains a range of UTF-8 character offsets and token references that- * identify the region of the source from which the AST derived.- */-var Location = /*#__PURE__*/function () {- /**- * The character offset at which this Node begins.- */-- /**- * The character offset at which this Node ends.- */-- /**- * The Token at which this Node begins.- */-- /**- * The Token at which this Node ends.- */-- /**- * The Source document the AST represents.- */- function Location(startToken, endToken, source) {- this.start = startToken.start;- this.end = endToken.end;- this.startToken = startToken;- this.endToken = endToken;- this.source = source;- }-- var _proto = Location.prototype;-- _proto.toJSON = function toJSON() {- return {- start: this.start,- end: this.end- };- };-- return Location;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(Location);-/**- * Represents a range of characters represented by a lexical token- * within a Source.- */--var Token = /*#__PURE__*/function () {- /**- * The kind of Token.- */-- /**- * The character offset at which this Node begins.- */-- /**- * The character offset at which this Node ends.- */-- /**- * The 1-indexed line number on which this Token appears.- */-- /**- * The 1-indexed column number at which this Token begins.- */-- /**- * For non-punctuation tokens, represents the interpreted value of the token.- */-- /**- * Tokens exist as nodes in a double-linked-list amongst all tokens- * including ignored tokens. <SOF> is always the first node and <EOF>- * the last.- */- function Token(kind, start, end, line, column, prev, value) {- this.kind = kind;- this.start = start;- this.end = end;- this.line = line;- this.column = column;- this.value = value;- this.prev = prev;- this.next = null;- }-- var _proto2 = Token.prototype;-- _proto2.toJSON = function toJSON() {- return {- kind: this.kind,- value: this.value,- line: this.line,- column: this.column- };- };-- return Token;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(Token);-/**- * @internal- */--function isNode(maybeNode) {- return maybeNode != null && typeof maybeNode.kind === 'string';-}-/**- * The list of all possible AST node types.- */--function _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); } }--function _createClass$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); return Constructor; }--/**- * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are- * optional, but they are useful for clients who store GraphQL documents in source files.- * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might- * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`.- * The `line` and `column` properties in `locationOffset` are 1-indexed.- */-var Source = /*#__PURE__*/function () {- function Source(body) {- var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GraphQL request';- var locationOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {- line: 1,- column: 1- };- this.body = body;- this.name = name;- this.locationOffset = locationOffset;- this.locationOffset.line > 0 || devAssert(0, 'line in locationOffset is 1-indexed and must be positive.');- this.locationOffset.column > 0 || devAssert(0, 'column in locationOffset is 1-indexed and must be positive.');- } // $FlowFixMe Flow doesn't support computed properties yet--- _createClass$1(Source, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'Source';- }- }]);-- return Source;-}();--/**- * An exported enum describing the different kinds of tokens that the- * lexer emits.- */-var TokenKind = Object.freeze({- SOF: '<SOF>',- EOF: '<EOF>',- BANG: '!',- DOLLAR: '$',- AMP: '&',- PAREN_L: '(',- PAREN_R: ')',- SPREAD: '...',- COLON: ':',- EQUALS: '=',- AT: '@',- BRACKET_L: '[',- BRACKET_R: ']',- BRACE_L: '{',- PIPE: '|',- BRACE_R: '}',- NAME: 'Name',- INT: 'Int',- FLOAT: 'Float',- STRING: 'String',- BLOCK_STRING: 'BlockString',- COMMENT: 'Comment'-});-/**- * The enum type representing the token kinds values.- */--/**- * The set of allowed directive location values.- */-var DirectiveLocation = Object.freeze({- // Request Definitions- QUERY: 'QUERY',- MUTATION: 'MUTATION',- SUBSCRIPTION: 'SUBSCRIPTION',- FIELD: 'FIELD',- FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',- FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',- INLINE_FRAGMENT: 'INLINE_FRAGMENT',- VARIABLE_DEFINITION: 'VARIABLE_DEFINITION',- // Type System Definitions- SCHEMA: 'SCHEMA',- SCALAR: 'SCALAR',- OBJECT: 'OBJECT',- FIELD_DEFINITION: 'FIELD_DEFINITION',- ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',- INTERFACE: 'INTERFACE',- UNION: 'UNION',- ENUM: 'ENUM',- ENUM_VALUE: 'ENUM_VALUE',- INPUT_OBJECT: 'INPUT_OBJECT',- INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'-});-/**- * The enum type representing the directive location values.- */--/**- * Produces the value of a block string from its parsed raw value, similar to- * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.- *- * This implements the GraphQL spec's BlockStringValue() static algorithm.- *- * @internal- */-function dedentBlockStringValue(rawString) {- // Expand a block string's raw value into independent lines.- var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.-- var commonIndent = getBlockStringIndentation(lines);-- if (commonIndent !== 0) {- for (var i = 1; i < lines.length; i++) {- lines[i] = lines[i].slice(commonIndent);- }- } // Remove leading and trailing blank lines.--- while (lines.length > 0 && isBlank(lines[0])) {- lines.shift();- }-- while (lines.length > 0 && isBlank(lines[lines.length - 1])) {- lines.pop();- } // Return a string of the lines joined with U+000A.--- return lines.join('\n');-}-/**- * @internal- */--function getBlockStringIndentation(lines) {- var commonIndent = null;-- for (var i = 1; i < lines.length; i++) {- var line = lines[i];- var indent = leadingWhitespace(line);-- if (indent === line.length) {- continue; // skip empty lines- }-- if (commonIndent === null || indent < commonIndent) {- commonIndent = indent;-- if (commonIndent === 0) {- break;- }- }- }-- return commonIndent === null ? 0 : commonIndent;-}--function leadingWhitespace(str) {- var i = 0;-- while (i < str.length && (str[i] === ' ' || str[i] === '\t')) {- i++;- }-- return i;-}--function isBlank(str) {- return leadingWhitespace(str) === str.length;-}-/**- * 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.- *- * @internal- */---function printBlockString(value) {- var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';- var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;- var isSingleLine = value.indexOf('\n') === -1;- var hasLeadingSpace = value[0] === ' ' || value[0] === '\t';- var hasTrailingQuote = value[value.length - 1] === '"';- var hasTrailingSlash = value[value.length - 1] === '\\';- var printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines;- var result = ''; // Format a multi-line block quote to account for leading space.-- if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) {- result += '\n' + indentation;- }-- result += indentation ? value.replace(/\n/g, '\n' + indentation) : value;-- if (printAsMultipleLines) {- result += '\n';- }-- return '"""' + result.replace(/"""/g, '\\"""') + '"""';-}--/**- * Given a Source object, creates a Lexer for that source.- * A Lexer is a stateful stream generator in that every time- * it is advanced, it returns the next token in the Source. Assuming the- * source lexes, the final Token emitted by the lexer will be of kind- * EOF, after which the lexer will repeatedly return the same EOF token- * whenever called.- */--var Lexer = /*#__PURE__*/function () {- /**- * The previously focused non-ignored token.- */-- /**- * The currently focused non-ignored token.- */-- /**- * The (1-indexed) line containing the current token.- */-- /**- * The character offset at which the current line begins.- */- function Lexer(source) {- var startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0, null);- this.source = source;- this.lastToken = startOfFileToken;- this.token = startOfFileToken;- this.line = 1;- this.lineStart = 0;- }- /**- * Advances the token stream to the next non-ignored token.- */--- var _proto = Lexer.prototype;-- _proto.advance = function advance() {- this.lastToken = this.token;- var token = this.token = this.lookahead();- return token;- }- /**- * Looks ahead and returns the next non-ignored token, but does not change- * the state of Lexer.- */- ;-- _proto.lookahead = function lookahead() {- var token = this.token;-- if (token.kind !== TokenKind.EOF) {- do {- var _token$next;-- // Note: next is only mutable during parsing, so we cast to allow this.- token = (_token$next = token.next) !== null && _token$next !== void 0 ? _token$next : token.next = readToken(this, token);- } while (token.kind === TokenKind.COMMENT);- }-- return token;- };-- return Lexer;-}();-/**- * @internal- */--function isPunctuatorTokenKind(kind) {- return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;-}--function printCharCode(code) {- return (// NaN/undefined represents access beyond the end of the file.- isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.- code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.- "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"")- );-}-/**- * Gets the next token from the source starting at the given position.- *- * This skips over whitespace until it finds the next lexable token, then lexes- * punctuators immediately or calls the appropriate helper function for more- * complicated tokens.- */---function readToken(lexer, prev) {- var source = lexer.source;- var body = source.body;- var bodyLength = body.length;- var pos = positionAfterWhitespace(body, prev.end, lexer);- var line = lexer.line;- var col = 1 + pos - lexer.lineStart;-- if (pos >= bodyLength) {- return new Token(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);- }-- var code = body.charCodeAt(pos); // SourceCharacter-- switch (code) {- // !- case 33:- return new Token(TokenKind.BANG, pos, pos + 1, line, col, prev);- // #-- case 35:- return readComment(source, pos, line, col, prev);- // $-- case 36:- return new Token(TokenKind.DOLLAR, pos, pos + 1, line, col, prev);- // &-- case 38:- return new Token(TokenKind.AMP, pos, pos + 1, line, col, prev);- // (-- case 40:- return new Token(TokenKind.PAREN_L, pos, pos + 1, line, col, prev);- // )-- case 41:- return new Token(TokenKind.PAREN_R, pos, pos + 1, line, col, prev);- // .-- case 46:- if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) {- return new Token(TokenKind.SPREAD, pos, pos + 3, line, col, prev);- }-- break;- // :-- case 58:- return new Token(TokenKind.COLON, pos, pos + 1, line, col, prev);- // =-- case 61:- return new Token(TokenKind.EQUALS, pos, pos + 1, line, col, prev);- // @-- case 64:- return new Token(TokenKind.AT, pos, pos + 1, line, col, prev);- // [-- case 91:- return new Token(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev);- // ]-- case 93:- return new Token(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev);- // {-- case 123:- return new Token(TokenKind.BRACE_L, pos, pos + 1, line, col, prev);- // |-- case 124:- return new Token(TokenKind.PIPE, pos, pos + 1, line, col, prev);- // }-- case 125:- return new Token(TokenKind.BRACE_R, pos, pos + 1, line, col, prev);- // A-Z _ a-z-- case 65:- case 66:- case 67:- case 68:- case 69:- case 70:- case 71:- case 72:- case 73:- case 74:- case 75:- case 76:- case 77:- case 78:- case 79:- case 80:- case 81:- case 82:- case 83:- case 84:- case 85:- case 86:- case 87:- case 88:- case 89:- case 90:- case 95:- case 97:- case 98:- case 99:- case 100:- case 101:- case 102:- case 103:- case 104:- case 105:- case 106:- case 107:- case 108:- case 109:- case 110:- case 111:- case 112:- case 113:- case 114:- case 115:- case 116:- case 117:- case 118:- case 119:- case 120:- case 121:- case 122:- return readName(source, pos, line, col, prev);- // - 0-9-- case 45:- case 48:- case 49:- case 50:- case 51:- case 52:- case 53:- case 54:- case 55:- case 56:- case 57:- return readNumber(source, pos, code, line, col, prev);- // "-- case 34:- if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) {- return readBlockString(source, pos, line, col, prev, lexer);- }-- return readString(source, pos, line, col, prev);- }-- throw syntaxError(source, pos, unexpectedCharacterMessage(code));-}-/**- * Report a message that an unexpected character was encountered.- */---function unexpectedCharacterMessage(code) {- if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {- return "Cannot contain the invalid character ".concat(printCharCode(code), ".");- }-- if (code === 39) {- // '- return 'Unexpected single quote character (\'), did you mean to use a double quote (")?';- }-- return "Cannot parse the unexpected character ".concat(printCharCode(code), ".");-}-/**- * Reads from body starting at startPosition until it finds a non-whitespace- * character, then returns the position of that character for lexing.- */---function positionAfterWhitespace(body, startPosition, lexer) {- var bodyLength = body.length;- var position = startPosition;-- while (position < bodyLength) {- var code = body.charCodeAt(position); // tab | space | comma | BOM-- if (code === 9 || code === 32 || code === 44 || code === 0xfeff) {- ++position;- } else if (code === 10) {- // new line- ++position;- ++lexer.line;- lexer.lineStart = position;- } else if (code === 13) {- // carriage return- if (body.charCodeAt(position + 1) === 10) {- position += 2;- } else {- ++position;- }-- ++lexer.line;- lexer.lineStart = position;- } else {- break;- }- }-- return position;-}-/**- * Reads a comment token from the source file.- *- * #[\u0009\u0020-\uFFFF]*- */---function readComment(source, start, line, col, prev) {- var body = source.body;- var code;- var position = start;-- do {- code = body.charCodeAt(++position);- } while (!isNaN(code) && ( // SourceCharacter but not LineTerminator- code > 0x001f || code === 0x0009));-- return new Token(TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position));-}-/**- * Reads a number token from the source file, either a float- * or an int depending on whether a decimal point appears.- *- * Int: -?(0|[1-9][0-9]*)- * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?- */---function readNumber(source, start, firstCode, line, col, prev) {- var body = source.body;- var code = firstCode;- var position = start;- var isFloat = false;-- if (code === 45) {- // -- code = body.charCodeAt(++position);- }-- if (code === 48) {- // 0- code = body.charCodeAt(++position);-- if (code >= 48 && code <= 57) {- throw syntaxError(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), "."));- }- } else {- position = readDigits(source, position, code);- code = body.charCodeAt(position);- }-- if (code === 46) {- // .- isFloat = true;- code = body.charCodeAt(++position);- position = readDigits(source, position, code);- code = body.charCodeAt(position);- }-- if (code === 69 || code === 101) {- // E e- isFloat = true;- code = body.charCodeAt(++position);-- if (code === 43 || code === 45) {- // + -- code = body.charCodeAt(++position);- }-- position = readDigits(source, position, code);- code = body.charCodeAt(position);- } // Numbers cannot be followed by . or NameStart--- if (code === 46 || isNameStart(code)) {- throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));- }-- return new Token(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, body.slice(start, position));-}-/**- * Returns the new position in the source after reading digits.- */---function readDigits(source, start, firstCode) {- var body = source.body;- var position = start;- var code = firstCode;-- if (code >= 48 && code <= 57) {- // 0 - 9- do {- code = body.charCodeAt(++position);- } while (code >= 48 && code <= 57); // 0 - 9--- return position;- }-- throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));-}-/**- * Reads a string token from the source file.- *- * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"- */---function readString(source, start, line, col, prev) {- var body = source.body;- var position = start + 1;- var chunkStart = position;- var code = 0;- var value = '';-- while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator- code !== 0x000a && code !== 0x000d) {- // Closing Quote (")- if (code === 34) {- value += body.slice(chunkStart, position);- return new Token(TokenKind.STRING, start, position + 1, line, col, prev, value);- } // SourceCharacter--- if (code < 0x0020 && code !== 0x0009) {- throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));- }-- ++position;-- if (code === 92) {- // \- value += body.slice(chunkStart, position - 1);- code = body.charCodeAt(position);-- switch (code) {- case 34:- value += '"';- break;-- case 47:- value += '/';- break;-- case 92:- value += '\\';- break;-- case 98:- value += '\b';- break;-- case 102:- value += '\f';- break;-- case 110:- value += '\n';- break;-- case 114:- value += '\r';- break;-- case 116:- value += '\t';- break;-- case 117:- {- // uXXXX- var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4));-- if (charCode < 0) {- var invalidSequence = body.slice(position + 1, position + 5);- throw syntaxError(source, position, "Invalid character escape sequence: \\u".concat(invalidSequence, "."));- }-- value += String.fromCharCode(charCode);- position += 4;- break;- }-- default:- throw syntaxError(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), "."));- }-- ++position;- chunkStart = position;- }- }-- throw syntaxError(source, position, 'Unterminated string.');-}-/**- * Reads a block string token from the source file.- *- * """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""- */---function readBlockString(source, start, line, col, prev, lexer) {- var body = source.body;- var position = start + 3;- var chunkStart = position;- var code = 0;- var rawValue = '';-- while (position < body.length && !isNaN(code = body.charCodeAt(position))) {- // Closing Triple-Quote (""")- if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {- rawValue += body.slice(chunkStart, position);- return new Token(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, dedentBlockStringValue(rawValue));- } // SourceCharacter--- if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {- throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));- }-- if (code === 10) {- // new line- ++position;- ++lexer.line;- lexer.lineStart = position;- } else if (code === 13) {- // carriage return- if (body.charCodeAt(position + 1) === 10) {- position += 2;- } else {- ++position;- }-- ++lexer.line;- lexer.lineStart = position;- } else if ( // Escape Triple-Quote (\""")- code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {- rawValue += body.slice(chunkStart, position) + '"""';- position += 4;- chunkStart = position;- } else {- ++position;- }- }-- throw syntaxError(source, position, 'Unterminated string.');-}-/**- * Converts four hexadecimal chars to the integer that the- * string represents. For example, uniCharCode('0','0','0','f')- * will return 15, and uniCharCode('0','0','f','f') returns 255.- *- * Returns a negative number on error, if a char was invalid.- *- * This is implemented by noting that char2hex() returns -1 on error,- * which means the result of ORing the char2hex() will also be negative.- */---function uniCharCode(a, b, c, d) {- return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);-}-/**- * Converts a hex character to its integer value.- * '0' becomes 0, '9' becomes 9- * 'A' becomes 10, 'F' becomes 15- * 'a' becomes 10, 'f' becomes 15- *- * Returns -1 on error.- */---function char2hex(a) {- return a >= 48 && a <= 57 ? a - 48 // 0-9- : a >= 65 && a <= 70 ? a - 55 // A-F- : a >= 97 && a <= 102 ? a - 87 // a-f- : -1;-}-/**- * Reads an alphanumeric + underscore name from the source.- *- * [_A-Za-z][_0-9A-Za-z]*- */---function readName(source, start, line, col, prev) {- var body = source.body;- var bodyLength = body.length;- var position = start + 1;- var code = 0;-- while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _- code >= 48 && code <= 57 || // 0-9- code >= 65 && code <= 90 || // A-Z- code >= 97 && code <= 122) // a-z- ) {- ++position;- }-- return new Token(TokenKind.NAME, start, position, line, col, prev, body.slice(start, position));-} // _ A-Z a-z---function isNameStart(code) {- return code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122;-}--/**- * Configuration options to control parser behavior- */--/**- * Given a GraphQL source, parses it into a Document.- * Throws GraphQLError if a syntax error is encountered.- */-function parse(source, options) {- var parser = new Parser(source, options);- return parser.parseDocument();-}-/**- * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for- * that value.- * Throws GraphQLError if a syntax error is encountered.- *- * This is useful within tools that operate upon GraphQL Values directly and- * in isolation of complete GraphQL documents.- *- * Consider providing the results to the utility function: valueFromAST().- */--function parseValue(source, options) {- var parser = new Parser(source, options);- parser.expectToken(TokenKind.SOF);- var value = parser.parseValueLiteral(false);- parser.expectToken(TokenKind.EOF);- return value;-}-/**- * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for- * that type.- * Throws GraphQLError if a syntax error is encountered.- *- * This is useful within tools that operate upon GraphQL Types directly and- * in isolation of complete GraphQL documents.- *- * Consider providing the results to the utility function: typeFromAST().- */--function parseType(source, options) {- var parser = new Parser(source, options);- parser.expectToken(TokenKind.SOF);- var type = parser.parseTypeReference();- parser.expectToken(TokenKind.EOF);- return type;-}--var Parser = /*#__PURE__*/function () {- function Parser(source, options) {- var sourceObj = typeof source === 'string' ? new Source(source) : source;- sourceObj instanceof Source || devAssert(0, "Must provide Source. Received: ".concat(inspect(sourceObj), "."));- this._lexer = new Lexer(sourceObj);- this._options = options;- }- /**- * Converts a name lex token into a name parse node.- */--- var _proto = Parser.prototype;-- _proto.parseName = function parseName() {- var token = this.expectToken(TokenKind.NAME);- return {- kind: Kind.NAME,- value: token.value,- loc: this.loc(token)- };- } // Implements the parsing rules in the Document section.-- /**- * Document : Definition+- */- ;-- _proto.parseDocument = function parseDocument() {- var start = this._lexer.token;- return {- kind: Kind.DOCUMENT,- definitions: this.many(TokenKind.SOF, this.parseDefinition, TokenKind.EOF),- loc: this.loc(start)- };- }- /**- * Definition :- * - ExecutableDefinition- * - TypeSystemDefinition- * - TypeSystemExtension- *- * ExecutableDefinition :- * - OperationDefinition- * - FragmentDefinition- */- ;-- _proto.parseDefinition = function parseDefinition() {- if (this.peek(TokenKind.NAME)) {- switch (this._lexer.token.value) {- case 'query':- case 'mutation':- case 'subscription':- return this.parseOperationDefinition();-- case 'fragment':- return this.parseFragmentDefinition();-- case 'schema':- case 'scalar':- case 'type':- case 'interface':- case 'union':- case 'enum':- case 'input':- case 'directive':- return this.parseTypeSystemDefinition();-- case 'extend':- return this.parseTypeSystemExtension();- }- } else if (this.peek(TokenKind.BRACE_L)) {- return this.parseOperationDefinition();- } else if (this.peekDescription()) {- return this.parseTypeSystemDefinition();- }-- throw this.unexpected();- } // Implements the parsing rules in the Operations section.-- /**- * OperationDefinition :- * - SelectionSet- * - OperationType Name? VariableDefinitions? Directives? SelectionSet- */- ;-- _proto.parseOperationDefinition = function parseOperationDefinition() {- var start = this._lexer.token;-- if (this.peek(TokenKind.BRACE_L)) {- return {- kind: Kind.OPERATION_DEFINITION,- operation: 'query',- name: undefined,- variableDefinitions: [],- directives: [],- selectionSet: this.parseSelectionSet(),- loc: this.loc(start)- };- }-- var operation = this.parseOperationType();- var name;-- if (this.peek(TokenKind.NAME)) {- name = this.parseName();- }-- return {- kind: Kind.OPERATION_DEFINITION,- operation: operation,- name: name,- variableDefinitions: this.parseVariableDefinitions(),- directives: this.parseDirectives(false),- selectionSet: this.parseSelectionSet(),- loc: this.loc(start)- };- }- /**- * OperationType : one of query mutation subscription- */- ;-- _proto.parseOperationType = function parseOperationType() {- var operationToken = this.expectToken(TokenKind.NAME);-- switch (operationToken.value) {- case 'query':- return 'query';-- case 'mutation':- return 'mutation';-- case 'subscription':- return 'subscription';- }-- throw this.unexpected(operationToken);- }- /**- * VariableDefinitions : ( VariableDefinition+ )- */- ;-- _proto.parseVariableDefinitions = function parseVariableDefinitions() {- return this.optionalMany(TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R);- }- /**- * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?- */- ;-- _proto.parseVariableDefinition = function parseVariableDefinition() {- var start = this._lexer.token;- return {- kind: Kind.VARIABLE_DEFINITION,- variable: this.parseVariable(),- type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),- defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined,- directives: this.parseDirectives(true),- loc: this.loc(start)- };- }- /**- * Variable : $ Name- */- ;-- _proto.parseVariable = function parseVariable() {- var start = this._lexer.token;- this.expectToken(TokenKind.DOLLAR);- return {- kind: Kind.VARIABLE,- name: this.parseName(),- loc: this.loc(start)- };- }- /**- * SelectionSet : { Selection+ }- */- ;-- _proto.parseSelectionSet = function parseSelectionSet() {- var start = this._lexer.token;- return {- kind: Kind.SELECTION_SET,- selections: this.many(TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R),- loc: this.loc(start)- };- }- /**- * Selection :- * - Field- * - FragmentSpread- * - InlineFragment- */- ;-- _proto.parseSelection = function parseSelection() {- return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();- }- /**- * Field : Alias? Name Arguments? Directives? SelectionSet?- *- * Alias : Name :- */- ;-- _proto.parseField = function parseField() {- var start = this._lexer.token;- var nameOrAlias = this.parseName();- var alias;- var name;-- if (this.expectOptionalToken(TokenKind.COLON)) {- alias = nameOrAlias;- name = this.parseName();- } else {- name = nameOrAlias;- }-- return {- kind: Kind.FIELD,- alias: alias,- name: name,- arguments: this.parseArguments(false),- directives: this.parseDirectives(false),- selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined,- loc: this.loc(start)- };- }- /**- * Arguments[Const] : ( Argument[?Const]+ )- */- ;-- _proto.parseArguments = function parseArguments(isConst) {- var item = isConst ? this.parseConstArgument : this.parseArgument;- return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);- }- /**- * Argument[Const] : Name : Value[?Const]- */- ;-- _proto.parseArgument = function parseArgument() {- var start = this._lexer.token;- var name = this.parseName();- this.expectToken(TokenKind.COLON);- return {- kind: Kind.ARGUMENT,- name: name,- value: this.parseValueLiteral(false),- loc: this.loc(start)- };- };-- _proto.parseConstArgument = function parseConstArgument() {- var start = this._lexer.token;- return {- kind: Kind.ARGUMENT,- name: this.parseName(),- value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)),- loc: this.loc(start)- };- } // Implements the parsing rules in the Fragments section.-- /**- * Corresponds to both FragmentSpread and InlineFragment in the spec.- *- * FragmentSpread : ... FragmentName Directives?- *- * InlineFragment : ... TypeCondition? Directives? SelectionSet- */- ;-- _proto.parseFragment = function parseFragment() {- var start = this._lexer.token;- this.expectToken(TokenKind.SPREAD);- var hasTypeCondition = this.expectOptionalKeyword('on');-- if (!hasTypeCondition && this.peek(TokenKind.NAME)) {- return {- kind: Kind.FRAGMENT_SPREAD,- name: this.parseFragmentName(),- directives: this.parseDirectives(false),- loc: this.loc(start)- };- }-- return {- kind: Kind.INLINE_FRAGMENT,- typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,- directives: this.parseDirectives(false),- selectionSet: this.parseSelectionSet(),- loc: this.loc(start)- };- }- /**- * FragmentDefinition :- * - fragment FragmentName on TypeCondition Directives? SelectionSet- *- * TypeCondition : NamedType- */- ;-- _proto.parseFragmentDefinition = function parseFragmentDefinition() {- var _this$_options;-- var start = this._lexer.token;- this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes- // the grammar of FragmentDefinition:- // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet-- if (((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.experimentalFragmentVariables) === true) {- return {- kind: Kind.FRAGMENT_DEFINITION,- name: this.parseFragmentName(),- variableDefinitions: this.parseVariableDefinitions(),- typeCondition: (this.expectKeyword('on'), this.parseNamedType()),- directives: this.parseDirectives(false),- selectionSet: this.parseSelectionSet(),- loc: this.loc(start)- };- }-- return {- kind: Kind.FRAGMENT_DEFINITION,- name: this.parseFragmentName(),- typeCondition: (this.expectKeyword('on'), this.parseNamedType()),- directives: this.parseDirectives(false),- selectionSet: this.parseSelectionSet(),- loc: this.loc(start)- };- }- /**- * FragmentName : Name but not `on`- */- ;-- _proto.parseFragmentName = function parseFragmentName() {- if (this._lexer.token.value === 'on') {- throw this.unexpected();- }-- return this.parseName();- } // Implements the parsing rules in the Values section.-- /**- * Value[Const] :- * - [~Const] Variable- * - IntValue- * - FloatValue- * - StringValue- * - BooleanValue- * - NullValue- * - EnumValue- * - ListValue[?Const]- * - ObjectValue[?Const]- *- * BooleanValue : one of `true` `false`- *- * NullValue : `null`- *- * EnumValue : Name but not `true`, `false` or `null`- */- ;-- _proto.parseValueLiteral = function parseValueLiteral(isConst) {- var token = this._lexer.token;-- switch (token.kind) {- case TokenKind.BRACKET_L:- return this.parseList(isConst);-- case TokenKind.BRACE_L:- return this.parseObject(isConst);-- case TokenKind.INT:- this._lexer.advance();-- return {- kind: Kind.INT,- value: token.value,- loc: this.loc(token)- };-- case TokenKind.FLOAT:- this._lexer.advance();-- return {- kind: Kind.FLOAT,- value: token.value,- loc: this.loc(token)- };-- case TokenKind.STRING:- case TokenKind.BLOCK_STRING:- return this.parseStringLiteral();-- case TokenKind.NAME:- this._lexer.advance();-- switch (token.value) {- case 'true':- return {- kind: Kind.BOOLEAN,- value: true,- loc: this.loc(token)- };-- case 'false':- return {- kind: Kind.BOOLEAN,- value: false,- loc: this.loc(token)- };-- case 'null':- return {- kind: Kind.NULL,- loc: this.loc(token)- };-- default:- return {- kind: Kind.ENUM,- value: token.value,- loc: this.loc(token)- };- }-- case TokenKind.DOLLAR:- if (!isConst) {- return this.parseVariable();- }-- break;- }-- throw this.unexpected();- };-- _proto.parseStringLiteral = function parseStringLiteral() {- var token = this._lexer.token;-- this._lexer.advance();-- return {- kind: Kind.STRING,- value: token.value,- block: token.kind === TokenKind.BLOCK_STRING,- loc: this.loc(token)- };- }- /**- * ListValue[Const] :- * - [ ]- * - [ Value[?Const]+ ]- */- ;-- _proto.parseList = function parseList(isConst) {- var _this = this;-- var start = this._lexer.token;-- var item = function item() {- return _this.parseValueLiteral(isConst);- };-- return {- kind: Kind.LIST,- values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),- loc: this.loc(start)- };- }- /**- * ObjectValue[Const] :- * - { }- * - { ObjectField[?Const]+ }- */- ;-- _proto.parseObject = function parseObject(isConst) {- var _this2 = this;-- var start = this._lexer.token;-- var item = function item() {- return _this2.parseObjectField(isConst);- };-- return {- kind: Kind.OBJECT,- fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),- loc: this.loc(start)- };- }- /**- * ObjectField[Const] : Name : Value[?Const]- */- ;-- _proto.parseObjectField = function parseObjectField(isConst) {- var start = this._lexer.token;- var name = this.parseName();- this.expectToken(TokenKind.COLON);- return {- kind: Kind.OBJECT_FIELD,- name: name,- value: this.parseValueLiteral(isConst),- loc: this.loc(start)- };- } // Implements the parsing rules in the Directives section.-- /**- * Directives[Const] : Directive[?Const]+- */- ;-- _proto.parseDirectives = function parseDirectives(isConst) {- var directives = [];-- while (this.peek(TokenKind.AT)) {- directives.push(this.parseDirective(isConst));- }-- return directives;- }- /**- * Directive[Const] : @ Name Arguments[?Const]?- */- ;-- _proto.parseDirective = function parseDirective(isConst) {- var start = this._lexer.token;- this.expectToken(TokenKind.AT);- return {- kind: Kind.DIRECTIVE,- name: this.parseName(),- arguments: this.parseArguments(isConst),- loc: this.loc(start)- };- } // Implements the parsing rules in the Types section.-- /**- * Type :- * - NamedType- * - ListType- * - NonNullType- */- ;-- _proto.parseTypeReference = function parseTypeReference() {- var start = this._lexer.token;- var type;-- if (this.expectOptionalToken(TokenKind.BRACKET_L)) {- type = this.parseTypeReference();- this.expectToken(TokenKind.BRACKET_R);- type = {- kind: Kind.LIST_TYPE,- type: type,- loc: this.loc(start)- };- } else {- type = this.parseNamedType();- }-- if (this.expectOptionalToken(TokenKind.BANG)) {- return {- kind: Kind.NON_NULL_TYPE,- type: type,- loc: this.loc(start)- };- }-- return type;- }- /**- * NamedType : Name- */- ;-- _proto.parseNamedType = function parseNamedType() {- var start = this._lexer.token;- return {- kind: Kind.NAMED_TYPE,- name: this.parseName(),- loc: this.loc(start)- };- } // Implements the parsing rules in the Type Definition section.-- /**- * TypeSystemDefinition :- * - SchemaDefinition- * - TypeDefinition- * - DirectiveDefinition- *- * TypeDefinition :- * - ScalarTypeDefinition- * - ObjectTypeDefinition- * - InterfaceTypeDefinition- * - UnionTypeDefinition- * - EnumTypeDefinition- * - InputObjectTypeDefinition- */- ;-- _proto.parseTypeSystemDefinition = function parseTypeSystemDefinition() {- // Many definitions begin with a description and require a lookahead.- var keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token;-- if (keywordToken.kind === TokenKind.NAME) {- switch (keywordToken.value) {- case 'schema':- return this.parseSchemaDefinition();-- case 'scalar':- return this.parseScalarTypeDefinition();-- case 'type':- return this.parseObjectTypeDefinition();-- case 'interface':- return this.parseInterfaceTypeDefinition();-- case 'union':- return this.parseUnionTypeDefinition();-- case 'enum':- return this.parseEnumTypeDefinition();-- case 'input':- return this.parseInputObjectTypeDefinition();-- case 'directive':- return this.parseDirectiveDefinition();- }- }-- throw this.unexpected(keywordToken);- };-- _proto.peekDescription = function peekDescription() {- return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);- }- /**- * Description : StringValue- */- ;-- _proto.parseDescription = function parseDescription() {- if (this.peekDescription()) {- return this.parseStringLiteral();- }- }- /**- * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }- */- ;-- _proto.parseSchemaDefinition = function parseSchemaDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- this.expectKeyword('schema');- var directives = this.parseDirectives(true);- var operationTypes = this.many(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);- return {- kind: Kind.SCHEMA_DEFINITION,- description: description,- directives: directives,- operationTypes: operationTypes,- loc: this.loc(start)- };- }- /**- * OperationTypeDefinition : OperationType : NamedType- */- ;-- _proto.parseOperationTypeDefinition = function parseOperationTypeDefinition() {- var start = this._lexer.token;- var operation = this.parseOperationType();- this.expectToken(TokenKind.COLON);- var type = this.parseNamedType();- return {- kind: Kind.OPERATION_TYPE_DEFINITION,- operation: operation,- type: type,- loc: this.loc(start)- };- }- /**- * ScalarTypeDefinition : Description? scalar Name Directives[Const]?- */- ;-- _proto.parseScalarTypeDefinition = function parseScalarTypeDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- this.expectKeyword('scalar');- var name = this.parseName();- var directives = this.parseDirectives(true);- return {- kind: Kind.SCALAR_TYPE_DEFINITION,- description: description,- name: name,- directives: directives,- loc: this.loc(start)- };- }- /**- * ObjectTypeDefinition :- * Description?- * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?- */- ;-- _proto.parseObjectTypeDefinition = function parseObjectTypeDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- this.expectKeyword('type');- var name = this.parseName();- var interfaces = this.parseImplementsInterfaces();- var directives = this.parseDirectives(true);- var fields = this.parseFieldsDefinition();- return {- kind: Kind.OBJECT_TYPE_DEFINITION,- description: description,- name: name,- interfaces: interfaces,- directives: directives,- fields: fields,- loc: this.loc(start)- };- }- /**- * ImplementsInterfaces :- * - implements `&`? NamedType- * - ImplementsInterfaces & NamedType- */- ;-- _proto.parseImplementsInterfaces = function parseImplementsInterfaces() {- var types = [];-- if (this.expectOptionalKeyword('implements')) {- // Optional leading ampersand- this.expectOptionalToken(TokenKind.AMP);-- do {- var _this$_options2;-- types.push(this.parseNamedType());- } while (this.expectOptionalToken(TokenKind.AMP) || // Legacy support for the SDL?- ((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.allowLegacySDLImplementsInterfaces) === true && this.peek(TokenKind.NAME));- }-- return types;- }- /**- * FieldsDefinition : { FieldDefinition+ }- */- ;-- _proto.parseFieldsDefinition = function parseFieldsDefinition() {- var _this$_options3;-- // Legacy support for the SDL?- if (((_this$_options3 = this._options) === null || _this$_options3 === void 0 ? void 0 : _this$_options3.allowLegacySDLEmptyFields) === true && this.peek(TokenKind.BRACE_L) && this._lexer.lookahead().kind === TokenKind.BRACE_R) {- this._lexer.advance();-- this._lexer.advance();-- return [];- }-- return this.optionalMany(TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R);- }- /**- * FieldDefinition :- * - Description? Name ArgumentsDefinition? : Type Directives[Const]?- */- ;-- _proto.parseFieldDefinition = function parseFieldDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- var name = this.parseName();- var args = this.parseArgumentDefs();- this.expectToken(TokenKind.COLON);- var type = this.parseTypeReference();- var directives = this.parseDirectives(true);- return {- kind: Kind.FIELD_DEFINITION,- description: description,- name: name,- arguments: args,- type: type,- directives: directives,- loc: this.loc(start)- };- }- /**- * ArgumentsDefinition : ( InputValueDefinition+ )- */- ;-- _proto.parseArgumentDefs = function parseArgumentDefs() {- return this.optionalMany(TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R);- }- /**- * InputValueDefinition :- * - Description? Name : Type DefaultValue? Directives[Const]?- */- ;-- _proto.parseInputValueDef = function parseInputValueDef() {- var start = this._lexer.token;- var description = this.parseDescription();- var name = this.parseName();- this.expectToken(TokenKind.COLON);- var type = this.parseTypeReference();- var defaultValue;-- if (this.expectOptionalToken(TokenKind.EQUALS)) {- defaultValue = this.parseValueLiteral(true);- }-- var directives = this.parseDirectives(true);- return {- kind: Kind.INPUT_VALUE_DEFINITION,- description: description,- name: name,- type: type,- defaultValue: defaultValue,- directives: directives,- loc: this.loc(start)- };- }- /**- * InterfaceTypeDefinition :- * - Description? interface Name Directives[Const]? FieldsDefinition?- */- ;-- _proto.parseInterfaceTypeDefinition = function parseInterfaceTypeDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- this.expectKeyword('interface');- var name = this.parseName();- var interfaces = this.parseImplementsInterfaces();- var directives = this.parseDirectives(true);- var fields = this.parseFieldsDefinition();- return {- kind: Kind.INTERFACE_TYPE_DEFINITION,- description: description,- name: name,- interfaces: interfaces,- directives: directives,- fields: fields,- loc: this.loc(start)- };- }- /**- * UnionTypeDefinition :- * - Description? union Name Directives[Const]? UnionMemberTypes?- */- ;-- _proto.parseUnionTypeDefinition = function parseUnionTypeDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- this.expectKeyword('union');- var name = this.parseName();- var directives = this.parseDirectives(true);- var types = this.parseUnionMemberTypes();- return {- kind: Kind.UNION_TYPE_DEFINITION,- description: description,- name: name,- directives: directives,- types: types,- loc: this.loc(start)- };- }- /**- * UnionMemberTypes :- * - = `|`? NamedType- * - UnionMemberTypes | NamedType- */- ;-- _proto.parseUnionMemberTypes = function parseUnionMemberTypes() {- var types = [];-- if (this.expectOptionalToken(TokenKind.EQUALS)) {- // Optional leading pipe- this.expectOptionalToken(TokenKind.PIPE);-- do {- types.push(this.parseNamedType());- } while (this.expectOptionalToken(TokenKind.PIPE));- }-- return types;- }- /**- * EnumTypeDefinition :- * - Description? enum Name Directives[Const]? EnumValuesDefinition?- */- ;-- _proto.parseEnumTypeDefinition = function parseEnumTypeDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- this.expectKeyword('enum');- var name = this.parseName();- var directives = this.parseDirectives(true);- var values = this.parseEnumValuesDefinition();- return {- kind: Kind.ENUM_TYPE_DEFINITION,- description: description,- name: name,- directives: directives,- values: values,- loc: this.loc(start)- };- }- /**- * EnumValuesDefinition : { EnumValueDefinition+ }- */- ;-- _proto.parseEnumValuesDefinition = function parseEnumValuesDefinition() {- return this.optionalMany(TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R);- }- /**- * EnumValueDefinition : Description? EnumValue Directives[Const]?- *- * EnumValue : Name- */- ;-- _proto.parseEnumValueDefinition = function parseEnumValueDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- var name = this.parseName();- var directives = this.parseDirectives(true);- return {- kind: Kind.ENUM_VALUE_DEFINITION,- description: description,- name: name,- directives: directives,- loc: this.loc(start)- };- }- /**- * InputObjectTypeDefinition :- * - Description? input Name Directives[Const]? InputFieldsDefinition?- */- ;-- _proto.parseInputObjectTypeDefinition = function parseInputObjectTypeDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- this.expectKeyword('input');- var name = this.parseName();- var directives = this.parseDirectives(true);- var fields = this.parseInputFieldsDefinition();- return {- kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,- description: description,- name: name,- directives: directives,- fields: fields,- loc: this.loc(start)- };- }- /**- * InputFieldsDefinition : { InputValueDefinition+ }- */- ;-- _proto.parseInputFieldsDefinition = function parseInputFieldsDefinition() {- return this.optionalMany(TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R);- }- /**- * TypeSystemExtension :- * - SchemaExtension- * - TypeExtension- *- * TypeExtension :- * - ScalarTypeExtension- * - ObjectTypeExtension- * - InterfaceTypeExtension- * - UnionTypeExtension- * - EnumTypeExtension- * - InputObjectTypeDefinition- */- ;-- _proto.parseTypeSystemExtension = function parseTypeSystemExtension() {- var keywordToken = this._lexer.lookahead();-- if (keywordToken.kind === TokenKind.NAME) {- switch (keywordToken.value) {- case 'schema':- return this.parseSchemaExtension();-- case 'scalar':- return this.parseScalarTypeExtension();-- case 'type':- return this.parseObjectTypeExtension();-- case 'interface':- return this.parseInterfaceTypeExtension();-- case 'union':- return this.parseUnionTypeExtension();-- case 'enum':- return this.parseEnumTypeExtension();-- case 'input':- return this.parseInputObjectTypeExtension();- }- }-- throw this.unexpected(keywordToken);- }- /**- * SchemaExtension :- * - extend schema Directives[Const]? { OperationTypeDefinition+ }- * - extend schema Directives[Const]- */- ;-- _proto.parseSchemaExtension = function parseSchemaExtension() {- var start = this._lexer.token;- this.expectKeyword('extend');- this.expectKeyword('schema');- var directives = this.parseDirectives(true);- var operationTypes = this.optionalMany(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);-- if (directives.length === 0 && operationTypes.length === 0) {- throw this.unexpected();- }-- return {- kind: Kind.SCHEMA_EXTENSION,- directives: directives,- operationTypes: operationTypes,- loc: this.loc(start)- };- }- /**- * ScalarTypeExtension :- * - extend scalar Name Directives[Const]- */- ;-- _proto.parseScalarTypeExtension = function parseScalarTypeExtension() {- var start = this._lexer.token;- this.expectKeyword('extend');- this.expectKeyword('scalar');- var name = this.parseName();- var directives = this.parseDirectives(true);-- if (directives.length === 0) {- throw this.unexpected();- }-- return {- kind: Kind.SCALAR_TYPE_EXTENSION,- name: name,- directives: directives,- loc: this.loc(start)- };- }- /**- * ObjectTypeExtension :- * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition- * - extend type Name ImplementsInterfaces? Directives[Const]- * - extend type Name ImplementsInterfaces- */- ;-- _proto.parseObjectTypeExtension = function parseObjectTypeExtension() {- var start = this._lexer.token;- this.expectKeyword('extend');- this.expectKeyword('type');- var name = this.parseName();- var interfaces = this.parseImplementsInterfaces();- var directives = this.parseDirectives(true);- var fields = this.parseFieldsDefinition();-- if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {- throw this.unexpected();- }-- return {- kind: Kind.OBJECT_TYPE_EXTENSION,- name: name,- interfaces: interfaces,- directives: directives,- fields: fields,- loc: this.loc(start)- };- }- /**- * InterfaceTypeExtension :- * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition- * - extend interface Name ImplementsInterfaces? Directives[Const]- * - extend interface Name ImplementsInterfaces- */- ;-- _proto.parseInterfaceTypeExtension = function parseInterfaceTypeExtension() {- var start = this._lexer.token;- this.expectKeyword('extend');- this.expectKeyword('interface');- var name = this.parseName();- var interfaces = this.parseImplementsInterfaces();- var directives = this.parseDirectives(true);- var fields = this.parseFieldsDefinition();-- if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {- throw this.unexpected();- }-- return {- kind: Kind.INTERFACE_TYPE_EXTENSION,- name: name,- interfaces: interfaces,- directives: directives,- fields: fields,- loc: this.loc(start)- };- }- /**- * UnionTypeExtension :- * - extend union Name Directives[Const]? UnionMemberTypes- * - extend union Name Directives[Const]- */- ;-- _proto.parseUnionTypeExtension = function parseUnionTypeExtension() {- var start = this._lexer.token;- this.expectKeyword('extend');- this.expectKeyword('union');- var name = this.parseName();- var directives = this.parseDirectives(true);- var types = this.parseUnionMemberTypes();-- if (directives.length === 0 && types.length === 0) {- throw this.unexpected();- }-- return {- kind: Kind.UNION_TYPE_EXTENSION,- name: name,- directives: directives,- types: types,- loc: this.loc(start)- };- }- /**- * EnumTypeExtension :- * - extend enum Name Directives[Const]? EnumValuesDefinition- * - extend enum Name Directives[Const]- */- ;-- _proto.parseEnumTypeExtension = function parseEnumTypeExtension() {- var start = this._lexer.token;- this.expectKeyword('extend');- this.expectKeyword('enum');- var name = this.parseName();- var directives = this.parseDirectives(true);- var values = this.parseEnumValuesDefinition();-- if (directives.length === 0 && values.length === 0) {- throw this.unexpected();- }-- return {- kind: Kind.ENUM_TYPE_EXTENSION,- name: name,- directives: directives,- values: values,- loc: this.loc(start)- };- }- /**- * InputObjectTypeExtension :- * - extend input Name Directives[Const]? InputFieldsDefinition- * - extend input Name Directives[Const]- */- ;-- _proto.parseInputObjectTypeExtension = function parseInputObjectTypeExtension() {- var start = this._lexer.token;- this.expectKeyword('extend');- this.expectKeyword('input');- var name = this.parseName();- var directives = this.parseDirectives(true);- var fields = this.parseInputFieldsDefinition();-- if (directives.length === 0 && fields.length === 0) {- throw this.unexpected();- }-- return {- kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,- name: name,- directives: directives,- fields: fields,- loc: this.loc(start)- };- }- /**- * DirectiveDefinition :- * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations- */- ;-- _proto.parseDirectiveDefinition = function parseDirectiveDefinition() {- var start = this._lexer.token;- var description = this.parseDescription();- this.expectKeyword('directive');- this.expectToken(TokenKind.AT);- var name = this.parseName();- var args = this.parseArgumentDefs();- var repeatable = this.expectOptionalKeyword('repeatable');- this.expectKeyword('on');- var locations = this.parseDirectiveLocations();- return {- kind: Kind.DIRECTIVE_DEFINITION,- description: description,- name: name,- arguments: args,- repeatable: repeatable,- locations: locations,- loc: this.loc(start)- };- }- /**- * DirectiveLocations :- * - `|`? DirectiveLocation- * - DirectiveLocations | DirectiveLocation- */- ;-- _proto.parseDirectiveLocations = function parseDirectiveLocations() {- // Optional leading pipe- this.expectOptionalToken(TokenKind.PIPE);- var locations = [];-- do {- locations.push(this.parseDirectiveLocation());- } while (this.expectOptionalToken(TokenKind.PIPE));-- return locations;- }- /*- * DirectiveLocation :- * - ExecutableDirectiveLocation- * - TypeSystemDirectiveLocation- *- * ExecutableDirectiveLocation : one of- * `QUERY`- * `MUTATION`- * `SUBSCRIPTION`- * `FIELD`- * `FRAGMENT_DEFINITION`- * `FRAGMENT_SPREAD`- * `INLINE_FRAGMENT`- *- * TypeSystemDirectiveLocation : one of- * `SCHEMA`- * `SCALAR`- * `OBJECT`- * `FIELD_DEFINITION`- * `ARGUMENT_DEFINITION`- * `INTERFACE`- * `UNION`- * `ENUM`- * `ENUM_VALUE`- * `INPUT_OBJECT`- * `INPUT_FIELD_DEFINITION`- */- ;-- _proto.parseDirectiveLocation = function parseDirectiveLocation() {- var start = this._lexer.token;- var name = this.parseName();-- if (DirectiveLocation[name.value] !== undefined) {- return name;- }-- throw this.unexpected(start);- } // Core parsing utility functions-- /**- * Returns a location object, used to identify the place in- * the source that created a given parsed object.- */- ;-- _proto.loc = function loc(startToken) {- var _this$_options4;-- if (((_this$_options4 = this._options) === null || _this$_options4 === void 0 ? void 0 : _this$_options4.noLocation) !== true) {- return new Location(startToken, this._lexer.lastToken, this._lexer.source);- }- }- /**- * Determines if the next token is of a given kind- */- ;-- _proto.peek = function peek(kind) {- return this._lexer.token.kind === kind;- }- /**- * If the next token is of the given kind, return that token after advancing- * the lexer. Otherwise, do not change the parser state and throw an error.- */- ;-- _proto.expectToken = function expectToken(kind) {- var token = this._lexer.token;-- if (token.kind === kind) {- this._lexer.advance();-- return token;- }-- throw syntaxError(this._lexer.source, token.start, "Expected ".concat(getTokenKindDesc(kind), ", found ").concat(getTokenDesc(token), "."));- }- /**- * If the next token is of the given kind, return that token after advancing- * the lexer. Otherwise, do not change the parser state and return undefined.- */- ;-- _proto.expectOptionalToken = function expectOptionalToken(kind) {- var token = this._lexer.token;-- if (token.kind === kind) {- this._lexer.advance();-- return token;- }-- return undefined;- }- /**- * If the next token is a given keyword, advance the lexer.- * Otherwise, do not change the parser state and throw an error.- */- ;-- _proto.expectKeyword = function expectKeyword(value) {- var token = this._lexer.token;-- if (token.kind === TokenKind.NAME && token.value === value) {- this._lexer.advance();- } else {- throw syntaxError(this._lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token), "."));- }- }- /**- * If the next token is a given keyword, return "true" after advancing- * the lexer. Otherwise, do not change the parser state and return "false".- */- ;-- _proto.expectOptionalKeyword = function expectOptionalKeyword(value) {- var token = this._lexer.token;-- if (token.kind === TokenKind.NAME && token.value === value) {- this._lexer.advance();-- return true;- }-- return false;- }- /**- * Helper function for creating an error when an unexpected lexed token- * is encountered.- */- ;-- _proto.unexpected = function unexpected(atToken) {- var token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;- return syntaxError(this._lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token), "."));- }- /**- * Returns a possibly empty list of parse nodes, determined by- * the parseFn. This list begins with a lex token of openKind- * and ends with a lex token of closeKind. Advances the parser- * to the next lex token after the closing token.- */- ;-- _proto.any = function any(openKind, parseFn, closeKind) {- this.expectToken(openKind);- var nodes = [];-- while (!this.expectOptionalToken(closeKind)) {- nodes.push(parseFn.call(this));- }-- return nodes;- }- /**- * Returns a list of parse nodes, determined by the parseFn.- * It can be empty only if open token is missing otherwise it will always- * return non-empty list that begins with a lex token of openKind and ends- * with a lex token of closeKind. Advances the parser to the next lex token- * after the closing token.- */- ;-- _proto.optionalMany = function optionalMany(openKind, parseFn, closeKind) {- if (this.expectOptionalToken(openKind)) {- var nodes = [];-- do {- nodes.push(parseFn.call(this));- } while (!this.expectOptionalToken(closeKind));-- return nodes;- }-- return [];- }- /**- * Returns a non-empty list of parse nodes, determined by- * the parseFn. This list begins with a lex token of openKind- * and ends with a lex token of closeKind. Advances the parser- * to the next lex token after the closing token.- */- ;-- _proto.many = function many(openKind, parseFn, closeKind) {- this.expectToken(openKind);- var nodes = [];-- do {- nodes.push(parseFn.call(this));- } while (!this.expectOptionalToken(closeKind));-- return nodes;- };-- return Parser;-}();-/**- * A helper function to describe a token as a string for debugging- */---function getTokenDesc(token) {- var value = token.value;- return getTokenKindDesc(token.kind) + (value != null ? " \"".concat(value, "\"") : '');-}-/**- * A helper function to describe a token kind as a string for debugging- */---function getTokenKindDesc(kind) {- return isPunctuatorTokenKind(kind) ? "\"".concat(kind, "\"") : kind;-}--/**- * A visitor is provided to visit, it contains the collection of- * relevant functions to be called during the visitor's traversal.- */--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: ['description', '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', 'interfaces', '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', 'interfaces', 'directives', 'fields'],- UnionTypeExtension: ['name', 'directives', 'types'],- EnumTypeExtension: ['name', 'directives', 'values'],- InputObjectTypeExtension: ['name', 'directives', 'fields']-};-var BREAK = Object.freeze({});-/**- * 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 the- * visitor API:- *- * 1) Named visitors triggered when entering a node of 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 _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) {- var k = _Object$keys2[_i2];- 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: ".concat(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 {- var _visitorKeys$node$kin;-- stack = {- inArray: inArray,- index: index,- keys: keys,- edits: edits,- prev: stack- };- inArray = Array.isArray(node);- keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : [];- 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;-}-/**- * Creates a new visitor instance which delegates to many visitors to run in- * parallel. Each visitor will be visited for each node before moving on.- *- * If a prior visitor edits a node, no following visitors will see that node.- */--function visitInParallel(visitors) {- var skipping = new Array(visitors.length);- return {- enter: function enter(node) {- for (var i = 0; i < visitors.length; i++) {- if (skipping[i] == null) {- var fn = getVisitFn(visitors[i], node.kind,- /* isLeaving */- false);-- if (fn) {- var result = fn.apply(visitors[i], arguments);-- if (result === false) {- skipping[i] = node;- } else if (result === BREAK) {- skipping[i] = BREAK;- } else if (result !== undefined) {- return result;- }- }- }- }- },- leave: function leave(node) {- for (var i = 0; i < visitors.length; i++) {- if (skipping[i] == null) {- var fn = getVisitFn(visitors[i], node.kind,- /* isLeaving */- true);-- if (fn) {- var result = fn.apply(visitors[i], arguments);-- if (result === BREAK) {- skipping[i] = BREAK;- } else if (result !== undefined && result !== false) {- return result;- }- }- } else if (skipping[i] === node) {- skipping[i] = null;- }- }- }- };-}-/**- * 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;- }- }- }-}--/* eslint-disable no-redeclare */-// $FlowFixMe-var find = Array.prototype.find ? function (list, predicate) {- return Array.prototype.find.call(list, predicate);-} : function (list, predicate) {- for (var _i2 = 0; _i2 < list.length; _i2++) {- var value = list[_i2];-- if (predicate(value)) {- return value;- }- }-};--var flatMapMethod = Array.prototype.flatMap;-/* eslint-disable no-redeclare */-// $FlowFixMe--var flatMap = flatMapMethod ? function (list, fn) {- return flatMapMethod.call(list, fn);-} : function (list, fn) {- var result = [];-- for (var _i2 = 0; _i2 < list.length; _i2++) {- var _item = list[_i2];- var value = fn(_item);-- if (Array.isArray(value)) {- result = result.concat(value);- } else {- result.push(value);- }- }-- return result;-};--/* eslint-disable no-redeclare */-// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221-var objectValues = Object.values || function (obj) {- return Object.keys(obj).map(function (key) {- return obj[key];- });-};--/**- * Given an arbitrary Error, presumably thrown while attempting to execute a- * GraphQL operation, produce a new GraphQLError aware of the location in the- * document responsible for the original Error.- */--function locatedError(originalError, nodes, path) {- var _nodes;-- // Note: this uses a brand-check to support GraphQL errors originating from- // other contexts.- if (Array.isArray(originalError.path)) {- return originalError;- }-- return new GraphQLError(originalError.message, (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes, originalError.source, originalError.positions, path, originalError);-}--var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;-/**- * Upholds the spec rules about naming.- */--function assertValidName(name) {- var error = isValidNameError(name);-- if (error) {- throw error;- }-- return name;-}-/**- * Returns an Error if a name is invalid.- */--function isValidNameError(name) {- typeof name === 'string' || devAssert(0, 'Expected name to be a string.');-- if (name.length > 1 && name[0] === '_' && name[1] === '_') {- return new GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by GraphQL introspection."));- }-- if (!NAME_RX.test(name)) {- return new GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."));- }-}--/* eslint-disable no-redeclare */-// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/5838-var objectEntries = Object.entries || function (obj) {- return Object.keys(obj).map(function (key) {- return [key, obj[key]];- });-};--/**- * Creates a keyed JS object from an array, given a function to produce the keys- * for each value in the array.- *- * This provides a convenient lookup for the array items if the key function- * produces unique results.- *- * const phoneBook = [- * { name: 'Jon', num: '555-1234' },- * { name: 'Jenny', num: '867-5309' }- * ]- *- * // { Jon: { name: 'Jon', num: '555-1234' },- * // Jenny: { name: 'Jenny', num: '867-5309' } }- * const entriesByName = keyMap(- * phoneBook,- * entry => entry.name- * )- *- * // { name: 'Jenny', num: '857-6309' }- * const jennyEntry = entriesByName['Jenny']- *- */-function keyMap(list, keyFn) {- return list.reduce(function (map, item) {- map[keyFn(item)] = item;- return map;- }, Object.create(null));-}--/**- * Creates an object map with the same keys as `map` and values generated by- * running each value of `map` thru `fn`.- */-function mapValue(map, fn) {- var result = Object.create(null);-- for (var _i2 = 0, _objectEntries2 = objectEntries(map); _i2 < _objectEntries2.length; _i2++) {- var _ref2 = _objectEntries2[_i2];- var _key = _ref2[0];- var _value = _ref2[1];- result[_key] = fn(_value, _key);- }-- return result;-}--function toObjMap(obj) {- /* eslint-enable no-redeclare */- if (Object.getPrototypeOf(obj) === null) {- return obj;- }-- var map = Object.create(null);-- for (var _i2 = 0, _objectEntries2 = objectEntries(obj); _i2 < _objectEntries2.length; _i2++) {- var _ref2 = _objectEntries2[_i2];- var key = _ref2[0];- var value = _ref2[1];- map[key] = value;- }-- return map;-}--/**- * Creates a keyed JS object from an array, given a function to produce the keys- * and a function to produce the values from each item in the array.- *- * const phoneBook = [- * { name: 'Jon', num: '555-1234' },- * { name: 'Jenny', num: '867-5309' }- * ]- *- * // { Jon: '555-1234', Jenny: '867-5309' }- * const phonesByName = keyValMap(- * phoneBook,- * entry => entry.name,- * entry => entry.num- * )- *- */-function keyValMap(list, keyFn, valFn) {- return list.reduce(function (map, item) {- map[keyFn(item)] = valFn(item);- return map;- }, Object.create(null));-}--/**- * A replacement for instanceof which includes an error warning when multi-realm- * constructors are detected.- */-// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production-// See: https://webpack.js.org/guides/production/-var instanceOf = process.env.NODE_ENV === 'production' ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')-// eslint-disable-next-line no-shadow-function instanceOf(value, constructor) {- return value instanceof constructor;-} : // eslint-disable-next-line no-shadow-function instanceOf(value, constructor) {- if (value instanceof constructor) {- return true;- }-- if (value) {- var valueClass = value.constructor;- var className = constructor.name;-- if (className && valueClass && valueClass.name === className) {- 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."));- }- }-- return false;-};--var MAX_SUGGESTIONS = 5;-/**- * Given [ A, B, C ] return ' Did you mean A, B, or C?'.- */--// eslint-disable-next-line no-redeclare-function didYouMean(firstArg, secondArg) {- var _ref = typeof firstArg === 'string' ? [firstArg, secondArg] : [undefined, firstArg],- subMessage = _ref[0],- suggestionsArg = _ref[1];-- var message = ' Did you mean ';-- if (subMessage) {- message += subMessage + ' ';- }-- var suggestions = suggestionsArg.map(function (x) {- return "\"".concat(x, "\"");- });-- switch (suggestions.length) {- case 0:- return '';-- case 1:- return message + suggestions[0] + '?';-- case 2:- return message + suggestions[0] + ' or ' + suggestions[1] + '?';- }-- var selected = suggestions.slice(0, MAX_SUGGESTIONS);- var lastItem = selected.pop();- return message + selected.join(', ') + ', or ' + lastItem + '?';-}--/**- * Returns the first argument it receives.- */-function identityFunc(x) {- return x;-}--/**- * Given an invalid input string and a list of valid options, returns a filtered- * list of valid options sorted based on their similarity with the input.- */-function suggestionList(input, options) {- var optionsByDistance = Object.create(null);- var lexicalDistance = new LexicalDistance(input);- var threshold = Math.floor(input.length * 0.4) + 1;-- for (var _i2 = 0; _i2 < options.length; _i2++) {- var option = options[_i2];- var distance = lexicalDistance.measure(option, threshold);-- if (distance !== undefined) {- optionsByDistance[option] = distance;- }- }-- return Object.keys(optionsByDistance).sort(function (a, b) {- var distanceDiff = optionsByDistance[a] - optionsByDistance[b];- return distanceDiff !== 0 ? distanceDiff : a.localeCompare(b);- });-}-/**- * Computes the lexical distance between strings A and B.- *- * The "distance" between two strings is given by counting the minimum number- * of edits needed to transform string A into string B. An edit can be an- * insertion, deletion, or substitution of a single character, or a swap of two- * adjacent characters.- *- * Includes a custom alteration from Damerau-Levenshtein to treat case changes- * as a single edit which helps identify mis-cased values with an edit distance- * of 1.- *- * This distance can be useful for detecting typos in input or sorting- */--var LexicalDistance = /*#__PURE__*/function () {- function LexicalDistance(input) {- this._input = input;- this._inputLowerCase = input.toLowerCase();- this._inputArray = stringToArray(this._inputLowerCase);- this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)];- }-- var _proto = LexicalDistance.prototype;-- _proto.measure = function measure(option, threshold) {- if (this._input === option) {- return 0;- }-- var optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit-- if (this._inputLowerCase === optionLowerCase) {- return 1;- }-- var a = stringToArray(optionLowerCase);- var b = this._inputArray;-- if (a.length < b.length) {- var tmp = a;- a = b;- b = tmp;- }-- var aLength = a.length;- var bLength = b.length;-- if (aLength - bLength > threshold) {- return undefined;- }-- var rows = this._rows;-- for (var j = 0; j <= bLength; j++) {- rows[0][j] = j;- }-- for (var i = 1; i <= aLength; i++) {- var upRow = rows[(i - 1) % 3];- var currentRow = rows[i % 3];- var smallestCell = currentRow[0] = i;-- for (var _j = 1; _j <= bLength; _j++) {- var cost = a[i - 1] === b[_j - 1] ? 0 : 1;- var currentCell = Math.min(upRow[_j] + 1, // delete- currentRow[_j - 1] + 1, // insert- upRow[_j - 1] + cost // substitute- );-- if (i > 1 && _j > 1 && a[i - 1] === b[_j - 2] && a[i - 2] === b[_j - 1]) {- // transposition- var doubleDiagonalCell = rows[(i - 2) % 3][_j - 2];- currentCell = Math.min(currentCell, doubleDiagonalCell + 1);- }-- if (currentCell < smallestCell) {- smallestCell = currentCell;- }-- currentRow[_j] = currentCell;- } // Early exit, since distance can't go smaller than smallest element of the previous row.--- if (smallestCell > threshold) {- return undefined;- }- }-- var distance = rows[aLength % 3][bLength];- return distance <= threshold ? distance : undefined;- };-- return LexicalDistance;-}();--function stringToArray(str) {- var strLength = str.length;- var array = new Array(strLength);-- for (var i = 0; i < strLength; ++i) {- array[i] = str.charCodeAt(i);- }-- return array;-}--/**- * Converts an AST into a string, using one set of reasonable- * formatting rules.- */--function print(ast) {- return visit(ast, {- leave: printDocASTReducer- });-} // TODO: provide better type coverage in future--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: addDescription(function (_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 + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + 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,- interfaces = _ref26.interfaces,- directives = _ref26.directives,- fields = _ref26.fields;- return join(['interface', name, wrap('implements ', join(interfaces, ' & ')), 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,- repeatable = _ref31.repeatable,- locations = _ref31.locations;- return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' 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,- interfaces = _ref35.interfaces,- directives = _ref35.directives,- fields = _ref35.fields;- return join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), 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) {- var _maybeArray$filter$jo;-- var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';- return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(function (x) {- return x;- }).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : '';-}-/**- * 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) {- var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';- return maybeString ? start + maybeString + end : '';-}--function indent(maybeString) {- return maybeString && ' ' + maybeString.replace(/\n/g, '\n ');-}--function isMultiline(string) {- return string.indexOf('\n') !== -1;-}--function hasMultilineItems(maybeArray) {- return maybeArray && maybeArray.some(isMultiline);-}--var printer = /*#__PURE__*/Object.freeze({- __proto__: null,- print: print-});--/**- * Produces a JavaScript value given a GraphQL Value AST.- *- * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value- * will reflect the provided GraphQL value AST.- *- * | GraphQL Value | JavaScript Value |- * | -------------------- | ---------------- |- * | Input Object | Object |- * | List | Array |- * | Boolean | Boolean |- * | String / Enum | String |- * | Int / Float | Number |- * | Null | null |- *- */-function valueFromASTUntyped(valueNode, variables) {- switch (valueNode.kind) {- case Kind.NULL:- return null;-- case Kind.INT:- return parseInt(valueNode.value, 10);-- case Kind.FLOAT:- return parseFloat(valueNode.value);-- case Kind.STRING:- case Kind.ENUM:- case Kind.BOOLEAN:- return valueNode.value;-- case Kind.LIST:- return valueNode.values.map(function (node) {- return valueFromASTUntyped(node, variables);- });-- case Kind.OBJECT:- return keyValMap(valueNode.fields, function (field) {- return field.name.value;- }, function (field) {- return valueFromASTUntyped(field.value, variables);- });-- case Kind.VARIABLE:- return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value];- } // istanbul ignore next (Not reachable. All possible value nodes have been considered)--- invariant(0, 'Unexpected value node: ' + inspect(valueNode));-}--function _defineProperties$2(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); } }--function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$2(Constructor.prototype, protoProps); if (staticProps) _defineProperties$2(Constructor, staticProps); return Constructor; }-function isType(type) {- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type);-}-function assertType(type) {- if (!isType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL type."));- }-- return type;-}-/**- * There are predicates for each kind of GraphQL type.- */--// eslint-disable-next-line no-redeclare-function isScalarType(type) {- return instanceOf(type, GraphQLScalarType);-}-function assertScalarType(type) {- if (!isScalarType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Scalar type."));- }-- return type;-}-// eslint-disable-next-line no-redeclare-function isObjectType(type) {- return instanceOf(type, GraphQLObjectType);-}-function assertObjectType(type) {- if (!isObjectType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Object type."));- }-- return type;-}-// eslint-disable-next-line no-redeclare-function isInterfaceType(type) {- return instanceOf(type, GraphQLInterfaceType);-}-function assertInterfaceType(type) {- if (!isInterfaceType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Interface type."));- }-- return type;-}-// eslint-disable-next-line no-redeclare-function isUnionType(type) {- return instanceOf(type, GraphQLUnionType);-}-function assertUnionType(type) {- if (!isUnionType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Union type."));- }-- return type;-}-// eslint-disable-next-line no-redeclare-function isEnumType(type) {- return instanceOf(type, GraphQLEnumType);-}-function assertEnumType(type) {- if (!isEnumType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Enum type."));- }-- return type;-}-// eslint-disable-next-line no-redeclare-function isInputObjectType(type) {- return instanceOf(type, GraphQLInputObjectType);-}-function assertInputObjectType(type) {- if (!isInputObjectType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Input Object type."));- }-- return type;-}-// eslint-disable-next-line no-redeclare-function isListType(type) {- return instanceOf(type, GraphQLList);-}-function assertListType(type) {- if (!isListType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL List type."));- }-- return type;-}-// eslint-disable-next-line no-redeclare-function isNonNullType(type) {- return instanceOf(type, GraphQLNonNull);-}-function assertNonNullType(type) {- if (!isNonNullType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Non-Null type."));- }-- return type;-}-/**- * These types may be used as input types for arguments and directives.- */--function isInputType(type) {- return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType);-}-function assertInputType(type) {- if (!isInputType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL input type."));- }-- return type;-}-/**- * These types may be used as output types as the result of fields.- */--function isOutputType(type) {- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType);-}-function assertOutputType(type) {- if (!isOutputType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL output type."));- }-- return type;-}-/**- * These types may describe types which may be leaf values.- */--function isLeafType(type) {- return isScalarType(type) || isEnumType(type);-}-function assertLeafType(type) {- if (!isLeafType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL leaf type."));- }-- return type;-}-/**- * These types may describe the parent context of a selection set.- */--function isCompositeType(type) {- return isObjectType(type) || isInterfaceType(type) || isUnionType(type);-}-function assertCompositeType(type) {- if (!isCompositeType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL composite type."));- }-- return type;-}-/**- * These types may describe the parent context of a selection set.- */--function isAbstractType(type) {- return isInterfaceType(type) || isUnionType(type);-}-function assertAbstractType(type) {- if (!isAbstractType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL abstract type."));- }-- return type;-}-/**- * List Type Wrapper- *- * A list is a wrapping type which points to another type.- * Lists are often created within the context of defining the fields of- * an object type.- *- * Example:- *- * const PersonType = new GraphQLObjectType({- * name: 'Person',- * fields: () => ({- * parents: { type: GraphQLList(PersonType) },- * children: { type: GraphQLList(PersonType) },- * })- * })- *- */-// FIXME: workaround to fix issue with Babel parser--/* ::-declare class GraphQLList<+T: GraphQLType> {- +ofType: T;- static <T>(ofType: T): GraphQLList<T>;- // Note: constructors cannot be used for covariant types. Drop the "new".- constructor(ofType: GraphQLType): void;-}-*/--function GraphQLList(ofType) {- if (this instanceof GraphQLList) {- this.ofType = assertType(ofType);- } else {- return new GraphQLList(ofType);- }-} // Need to cast through any to alter the prototype.--GraphQLList.prototype.toString = function toString() {- return '[' + String(this.ofType) + ']';-};--GraphQLList.prototype.toJSON = function toJSON() {- return this.toString();-};--Object.defineProperty(GraphQLList.prototype, SYMBOL_TO_STRING_TAG, {- get: function get() {- return 'GraphQLList';- }-}); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLList);-/**- * Non-Null Type Wrapper- *- * A non-null is a wrapping type which points to another type.- * Non-null types enforce that their values are never null and can ensure- * an error is raised if this ever occurs during a request. It is useful for- * fields which you can make a strong guarantee on non-nullability, for example- * usually the id field of a database row will never be null.- *- * Example:- *- * const RowType = new GraphQLObjectType({- * name: 'Row',- * fields: () => ({- * id: { type: GraphQLNonNull(GraphQLString) },- * })- * })- *- * Note: the enforcement of non-nullability occurs within the executor.- */-// FIXME: workaround to fix issue with Babel parser--/* ::-declare class GraphQLNonNull<+T: GraphQLNullableType> {- +ofType: T;- static <T>(ofType: T): GraphQLNonNull<T>;- // Note: constructors cannot be used for covariant types. Drop the "new".- constructor(ofType: GraphQLType): void;-}-*/--function GraphQLNonNull(ofType) {- if (this instanceof GraphQLNonNull) {- this.ofType = assertNullableType(ofType);- } else {- return new GraphQLNonNull(ofType);- }-} // Need to cast through any to alter the prototype.--GraphQLNonNull.prototype.toString = function toString() {- return String(this.ofType) + '!';-};--GraphQLNonNull.prototype.toJSON = function toJSON() {- return this.toString();-};--Object.defineProperty(GraphQLNonNull.prototype, SYMBOL_TO_STRING_TAG, {- get: function get() {- return 'GraphQLNonNull';- }-}); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLNonNull);-/**- * These types wrap and modify other types- */--function isWrappingType(type) {- return isListType(type) || isNonNullType(type);-}-function assertWrappingType(type) {- if (!isWrappingType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL wrapping type."));- }-- return type;-}-/**- * These types can all accept null as a value.- */--function isNullableType(type) {- return isType(type) && !isNonNullType(type);-}-function assertNullableType(type) {- if (!isNullableType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL nullable type."));- }-- return type;-}-/* eslint-disable no-redeclare */--function getNullableType(type) {- /* eslint-enable no-redeclare */- if (type) {- return isNonNullType(type) ? type.ofType : type;- }-}-/**- * These named types do not include modifiers like List or NonNull.- */--function isNamedType(type) {- return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type);-}-function assertNamedType(type) {- if (!isNamedType(type)) {- throw new Error("Expected ".concat(inspect(type), " to be a GraphQL named type."));- }-- return type;-}-/* eslint-disable no-redeclare */--function getNamedType(type) {- /* eslint-enable no-redeclare */- if (type) {- var unwrappedType = type;-- while (isWrappingType(unwrappedType)) {- unwrappedType = unwrappedType.ofType;- }-- return unwrappedType;- }-}-/**- * Used while defining GraphQL types to allow for circular references in- * otherwise immutable type definitions.- */--function resolveThunk(thunk) {- // $FlowFixMe(>=0.90.0)- return typeof thunk === 'function' ? thunk() : thunk;-}--function undefineIfEmpty(arr) {- return arr && arr.length > 0 ? arr : undefined;-}-/**- * Scalar Type Definition- *- * The leaf values of any request and input values to arguments are- * Scalars (or Enums) and are defined with a name and a series of functions- * used to parse input from ast or variables and to ensure validity.- *- * If a type's serialize function does not return a value (i.e. it returns- * `undefined`) then an error will be raised and a `null` value will be returned- * in the response. If the serialize function returns `null`, then no error will- * be included in the response.- *- * Example:- *- * const OddType = new GraphQLScalarType({- * name: 'Odd',- * serialize(value) {- * if (value % 2 === 1) {- * return value;- * }- * }- * });- *- */---var GraphQLScalarType = /*#__PURE__*/function () {- function GraphQLScalarType(config) {- var _config$parseValue, _config$serialize, _config$parseLiteral;-- var parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : identityFunc;- this.name = config.name;- this.description = config.description;- this.specifiedByUrl = config.specifiedByUrl;- this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : identityFunc;- this.parseValue = parseValue;- this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : function (node) {- return parseValue(valueFromASTUntyped(node));- };- this.extensions = config.extensions && toObjMap(config.extensions);- this.astNode = config.astNode;- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);- typeof config.name === 'string' || devAssert(0, 'Must provide name.');- config.specifiedByUrl == null || typeof config.specifiedByUrl === 'string' || devAssert(0, "".concat(this.name, " must provide \"specifiedByUrl\" as a string, ") + "but got: ".concat(inspect(config.specifiedByUrl), "."));- 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."));-- if (config.parseLiteral) {- typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || devAssert(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" functions."));- }- }-- var _proto = GraphQLScalarType.prototype;-- _proto.toConfig = function toConfig() {- var _this$extensionASTNod;-- return {- name: this.name,- description: this.description,- specifiedByUrl: this.specifiedByUrl,- serialize: this.serialize,- parseValue: this.parseValue,- parseLiteral: this.parseLiteral,- extensions: this.extensions,- astNode: this.astNode,- extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : []- };- };-- _proto.toString = function toString() {- return this.name;- };-- _proto.toJSON = function toJSON() {- return this.toString();- } // $FlowFixMe Flow doesn't support computed properties yet- ;-- _createClass$2(GraphQLScalarType, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'GraphQLScalarType';- }- }]);-- return GraphQLScalarType;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLScalarType);--/**- * Object Type Definition- *- * Almost all of the GraphQL types you define will be object types. Object types- * have a name, but most importantly describe their fields.- *- * Example:- *- * const AddressType = new GraphQLObjectType({- * name: 'Address',- * fields: {- * street: { type: GraphQLString },- * number: { type: GraphQLInt },- * formatted: {- * type: GraphQLString,- * resolve(obj) {- * return obj.number + ' ' + obj.street- * }- * }- * }- * });- *- * When two types need to refer to each other, or a type needs to refer to- * itself in a field, you can use a function expression (aka a closure or a- * thunk) to supply the fields lazily.- *- * Example:- *- * const PersonType = new GraphQLObjectType({- * name: 'Person',- * fields: () => ({- * name: { type: GraphQLString },- * bestFriend: { type: PersonType },- * })- * });- *- */-var GraphQLObjectType = /*#__PURE__*/function () {- function GraphQLObjectType(config) {- this.name = config.name;- this.description = config.description;- this.isTypeOf = config.isTypeOf;- this.extensions = config.extensions && toObjMap(config.extensions);- this.astNode = config.astNode;- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);- this._fields = defineFieldMap.bind(undefined, config);- this._interfaces = defineInterfaces.bind(undefined, config);- typeof config.name === 'string' || devAssert(0, 'Must provide name.');- config.isTypeOf == null || typeof config.isTypeOf === 'function' || devAssert(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat(inspect(config.isTypeOf), "."));- }-- var _proto2 = GraphQLObjectType.prototype;-- _proto2.getFields = function getFields() {- if (typeof this._fields === 'function') {- this._fields = this._fields();- }-- return this._fields;- };-- _proto2.getInterfaces = function getInterfaces() {- if (typeof this._interfaces === 'function') {- this._interfaces = this._interfaces();- }-- return this._interfaces;- };-- _proto2.toConfig = function toConfig() {- return {- name: this.name,- description: this.description,- interfaces: this.getInterfaces(),- fields: fieldsToFieldsConfig(this.getFields()),- isTypeOf: this.isTypeOf,- extensions: this.extensions,- astNode: this.astNode,- extensionASTNodes: this.extensionASTNodes || []- };- };-- _proto2.toString = function toString() {- return this.name;- };-- _proto2.toJSON = function toJSON() {- return this.toString();- } // $FlowFixMe Flow doesn't support computed properties yet- ;-- _createClass$2(GraphQLObjectType, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'GraphQLObjectType';- }- }]);-- return GraphQLObjectType;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLObjectType);--function defineInterfaces(config) {- var _resolveThunk;-- var interfaces = (_resolveThunk = resolveThunk(config.interfaces)) !== null && _resolveThunk !== void 0 ? _resolveThunk : [];- Array.isArray(interfaces) || devAssert(0, "".concat(config.name, " interfaces must be an Array or a function which returns an Array."));- return interfaces;-}--function defineFieldMap(config) {- var fieldMap = resolveThunk(config.fields);- 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."));- return mapValue(fieldMap, function (fieldConfig, fieldName) {- var _fieldConfig$args;-- isPlainObj(fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object."));- !('isDeprecated' in fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" instead of \"isDeprecated\"."));- 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), "."));- var argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {};- isPlainObj(argsConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument names as keys."));- var args = objectEntries(argsConfig).map(function (_ref) {- var argName = _ref[0],- argConfig = _ref[1];- return {- name: argName,- description: argConfig.description,- type: argConfig.type,- defaultValue: argConfig.defaultValue,- extensions: argConfig.extensions && toObjMap(argConfig.extensions),- astNode: argConfig.astNode- };- });- return {- name: fieldName,- description: fieldConfig.description,- type: fieldConfig.type,- args: args,- resolve: fieldConfig.resolve,- subscribe: fieldConfig.subscribe,- isDeprecated: fieldConfig.deprecationReason != null,- deprecationReason: fieldConfig.deprecationReason,- extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions),- astNode: fieldConfig.astNode- };- });-}--function isPlainObj(obj) {- return isObjectLike(obj) && !Array.isArray(obj);-}--function fieldsToFieldsConfig(fields) {- return mapValue(fields, function (field) {- return {- description: field.description,- type: field.type,- args: argsToArgsConfig(field.args),- resolve: field.resolve,- subscribe: field.subscribe,- deprecationReason: field.deprecationReason,- extensions: field.extensions,- astNode: field.astNode- };- });-}-/**- * @internal- */---function argsToArgsConfig(args) {- return keyValMap(args, function (arg) {- return arg.name;- }, function (arg) {- return {- description: arg.description,- type: arg.type,- defaultValue: arg.defaultValue,- extensions: arg.extensions,- astNode: arg.astNode- };- });-}-function isRequiredArgument(arg) {- return isNonNullType(arg.type) && arg.defaultValue === undefined;-}--/**- * Interface Type Definition- *- * When a field can return one of a heterogeneous set of types, a Interface type- * is used to describe what types are possible, what fields are in common across- * all types, as well as a function to determine which type is actually used- * when the field is resolved.- *- * Example:- *- * const EntityType = new GraphQLInterfaceType({- * name: 'Entity',- * fields: {- * name: { type: GraphQLString }- * }- * });- *- */-var GraphQLInterfaceType = /*#__PURE__*/function () {- function GraphQLInterfaceType(config) {- this.name = config.name;- this.description = config.description;- this.resolveType = config.resolveType;- this.extensions = config.extensions && toObjMap(config.extensions);- this.astNode = config.astNode;- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);- this._fields = defineFieldMap.bind(undefined, config);- this._interfaces = defineInterfaces.bind(undefined, config);- typeof config.name === 'string' || devAssert(0, 'Must provide name.');- config.resolveType == null || typeof config.resolveType === 'function' || devAssert(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), "."));- }-- var _proto3 = GraphQLInterfaceType.prototype;-- _proto3.getFields = function getFields() {- if (typeof this._fields === 'function') {- this._fields = this._fields();- }-- return this._fields;- };-- _proto3.getInterfaces = function getInterfaces() {- if (typeof this._interfaces === 'function') {- this._interfaces = this._interfaces();- }-- return this._interfaces;- };-- _proto3.toConfig = function toConfig() {- var _this$extensionASTNod2;-- return {- name: this.name,- description: this.description,- interfaces: this.getInterfaces(),- fields: fieldsToFieldsConfig(this.getFields()),- resolveType: this.resolveType,- extensions: this.extensions,- astNode: this.astNode,- extensionASTNodes: (_this$extensionASTNod2 = this.extensionASTNodes) !== null && _this$extensionASTNod2 !== void 0 ? _this$extensionASTNod2 : []- };- };-- _proto3.toString = function toString() {- return this.name;- };-- _proto3.toJSON = function toJSON() {- return this.toString();- } // $FlowFixMe Flow doesn't support computed properties yet- ;-- _createClass$2(GraphQLInterfaceType, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'GraphQLInterfaceType';- }- }]);-- return GraphQLInterfaceType;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLInterfaceType);--/**- * Union Type Definition- *- * When a field can return one of a heterogeneous set of types, a Union type- * is used to describe what types are possible as well as providing a function- * to determine which type is actually used when the field is resolved.- *- * Example:- *- * const PetType = new GraphQLUnionType({- * name: 'Pet',- * types: [ DogType, CatType ],- * resolveType(value) {- * if (value instanceof Dog) {- * return DogType;- * }- * if (value instanceof Cat) {- * return CatType;- * }- * }- * });- *- */-var GraphQLUnionType = /*#__PURE__*/function () {- function GraphQLUnionType(config) {- this.name = config.name;- this.description = config.description;- this.resolveType = config.resolveType;- this.extensions = config.extensions && toObjMap(config.extensions);- this.astNode = config.astNode;- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);- this._types = defineTypes.bind(undefined, config);- typeof config.name === 'string' || devAssert(0, 'Must provide name.');- config.resolveType == null || typeof config.resolveType === 'function' || devAssert(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), "."));- }-- var _proto4 = GraphQLUnionType.prototype;-- _proto4.getTypes = function getTypes() {- if (typeof this._types === 'function') {- this._types = this._types();- }-- return this._types;- };-- _proto4.toConfig = function toConfig() {- var _this$extensionASTNod3;-- return {- name: this.name,- description: this.description,- types: this.getTypes(),- resolveType: this.resolveType,- extensions: this.extensions,- astNode: this.astNode,- extensionASTNodes: (_this$extensionASTNod3 = this.extensionASTNodes) !== null && _this$extensionASTNod3 !== void 0 ? _this$extensionASTNod3 : []- };- };-- _proto4.toString = function toString() {- return this.name;- };-- _proto4.toJSON = function toJSON() {- return this.toString();- } // $FlowFixMe Flow doesn't support computed properties yet- ;-- _createClass$2(GraphQLUnionType, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'GraphQLUnionType';- }- }]);-- return GraphQLUnionType;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLUnionType);--function defineTypes(config) {- var types = resolveThunk(config.types);- Array.isArray(types) || devAssert(0, "Must provide Array of types or a function which returns such an array for Union ".concat(config.name, "."));- return types;-}--/**- * Enum Type Definition- *- * Some leaf values of requests and input values are Enums. GraphQL serializes- * Enum values as strings, however internally Enums can be represented by any- * kind of type, often integers.- *- * Example:- *- * const RGBType = new GraphQLEnumType({- * name: 'RGB',- * values: {- * RED: { value: 0 },- * GREEN: { value: 1 },- * BLUE: { value: 2 }- * }- * });- *- * Note: If a value is not provided in a definition, the name of the enum value- * will be used as its internal value.- */-var GraphQLEnumType-/* <T> */-= /*#__PURE__*/function () {- function GraphQLEnumType(config) {- this.name = config.name;- this.description = config.description;- this.extensions = config.extensions && toObjMap(config.extensions);- this.astNode = config.astNode;- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);- this._values = defineEnumValues(this.name, config.values);- this._valueLookup = new Map(this._values.map(function (enumValue) {- return [enumValue.value, enumValue];- }));- this._nameLookup = keyMap(this._values, function (value) {- return value.name;- });- typeof config.name === 'string' || devAssert(0, 'Must provide name.');- }-- var _proto5 = GraphQLEnumType.prototype;-- _proto5.getValues = function getValues() {- return this._values;- };-- _proto5.getValue = function getValue(name) {- return this._nameLookup[name];- };-- _proto5.serialize = function serialize(outputValue) {- var enumValue = this._valueLookup.get(outputValue);-- if (enumValue === undefined) {- throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent value: ").concat(inspect(outputValue)));- }-- return enumValue.name;- };-- _proto5.parseValue = function parseValue(inputValue)- /* T */- {- if (typeof inputValue !== 'string') {- var valueStr = inspect(inputValue);- throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-string value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr));- }-- var enumValue = this.getValue(inputValue);-- if (enumValue == null) {- throw new GraphQLError("Value \"".concat(inputValue, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, inputValue));- }-- return enumValue.value;- };-- _proto5.parseLiteral = function parseLiteral(valueNode, _variables)- /* T */- {- // Note: variables will be resolved to a value before calling this function.- if (valueNode.kind !== Kind.ENUM) {- var valueStr = print(valueNode);- throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-enum value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr), valueNode);- }-- var enumValue = this.getValue(valueNode.value);-- if (enumValue == null) {- var _valueStr = print(valueNode);-- throw new GraphQLError("Value \"".concat(_valueStr, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, _valueStr), valueNode);- }-- return enumValue.value;- };-- _proto5.toConfig = function toConfig() {- var _this$extensionASTNod4;-- var values = keyValMap(this.getValues(), function (value) {- return value.name;- }, function (value) {- return {- description: value.description,- value: value.value,- deprecationReason: value.deprecationReason,- extensions: value.extensions,- astNode: value.astNode- };- });- return {- name: this.name,- description: this.description,- values: values,- extensions: this.extensions,- astNode: this.astNode,- extensionASTNodes: (_this$extensionASTNod4 = this.extensionASTNodes) !== null && _this$extensionASTNod4 !== void 0 ? _this$extensionASTNod4 : []- };- };-- _proto5.toString = function toString() {- return this.name;- };-- _proto5.toJSON = function toJSON() {- return this.toString();- } // $FlowFixMe Flow doesn't support computed properties yet- ;-- _createClass$2(GraphQLEnumType, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'GraphQLEnumType';- }- }]);-- return GraphQLEnumType;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLEnumType);--function didYouMeanEnumValue(enumType, unknownValueStr) {- var allNames = enumType.getValues().map(function (value) {- return value.name;- });- var suggestedValues = suggestionList(unknownValueStr, allNames);- return didYouMean('the enum value', suggestedValues);-}--function defineEnumValues(typeName, valueMap) {- isPlainObj(valueMap) || devAssert(0, "".concat(typeName, " values must be an object with value names as keys."));- return objectEntries(valueMap).map(function (_ref2) {- var valueName = _ref2[0],- valueConfig = _ref2[1];- 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), "."));- !('isDeprecated' in valueConfig) || devAssert(0, "".concat(typeName, ".").concat(valueName, " should provide \"deprecationReason\" instead of \"isDeprecated\"."));- return {- name: valueName,- description: valueConfig.description,- value: valueConfig.value !== undefined ? valueConfig.value : valueName,- isDeprecated: valueConfig.deprecationReason != null,- deprecationReason: valueConfig.deprecationReason,- extensions: valueConfig.extensions && toObjMap(valueConfig.extensions),- astNode: valueConfig.astNode- };- });-}--/**- * Input Object Type Definition- *- * An input object defines a structured collection of fields which may be- * supplied to a field argument.- *- * Using `NonNull` will ensure that a value must be provided by the query- *- * Example:- *- * const GeoPoint = new GraphQLInputObjectType({- * name: 'GeoPoint',- * fields: {- * lat: { type: GraphQLNonNull(GraphQLFloat) },- * lon: { type: GraphQLNonNull(GraphQLFloat) },- * alt: { type: GraphQLFloat, defaultValue: 0 },- * }- * });- *- */-var GraphQLInputObjectType = /*#__PURE__*/function () {- function GraphQLInputObjectType(config) {- this.name = config.name;- this.description = config.description;- this.extensions = config.extensions && toObjMap(config.extensions);- this.astNode = config.astNode;- this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);- this._fields = defineInputFieldMap.bind(undefined, config);- typeof config.name === 'string' || devAssert(0, 'Must provide name.');- }-- var _proto6 = GraphQLInputObjectType.prototype;-- _proto6.getFields = function getFields() {- if (typeof this._fields === 'function') {- this._fields = this._fields();- }-- return this._fields;- };-- _proto6.toConfig = function toConfig() {- var _this$extensionASTNod5;-- var fields = mapValue(this.getFields(), function (field) {- return {- description: field.description,- type: field.type,- defaultValue: field.defaultValue,- extensions: field.extensions,- astNode: field.astNode- };- });- return {- name: this.name,- description: this.description,- fields: fields,- extensions: this.extensions,- astNode: this.astNode,- extensionASTNodes: (_this$extensionASTNod5 = this.extensionASTNodes) !== null && _this$extensionASTNod5 !== void 0 ? _this$extensionASTNod5 : []- };- };-- _proto6.toString = function toString() {- return this.name;- };-- _proto6.toJSON = function toJSON() {- return this.toString();- } // $FlowFixMe Flow doesn't support computed properties yet- ;-- _createClass$2(GraphQLInputObjectType, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'GraphQLInputObjectType';- }- }]);-- return GraphQLInputObjectType;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLInputObjectType);--function defineInputFieldMap(config) {- var fieldMap = resolveThunk(config.fields);- 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."));- return mapValue(fieldMap, function (fieldConfig, fieldName) {- !('resolve' in fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but Input Types cannot define resolvers."));- return {- name: fieldName,- description: fieldConfig.description,- type: fieldConfig.type,- defaultValue: fieldConfig.defaultValue,- extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions),- astNode: fieldConfig.astNode- };- });-}--function isRequiredInputField(field) {- return isNonNullType(field.type) && field.defaultValue === undefined;-}--/**- * Provided two types, return true if the types are equal (invariant).- */--function isEqualType(typeA, typeB) {- // Equivalent types are equal.- if (typeA === typeB) {- return true;- } // If either type is non-null, the other must also be non-null.--- if (isNonNullType(typeA) && isNonNullType(typeB)) {- return isEqualType(typeA.ofType, typeB.ofType);- } // If either type is a list, the other must also be a list.--- if (isListType(typeA) && isListType(typeB)) {- return isEqualType(typeA.ofType, typeB.ofType);- } // Otherwise the types are not equal.--- return false;-}-/**- * Provided a type and a super type, return true if the first type is either- * equal or a subset of the second super type (covariant).- */--function isTypeSubTypeOf(schema, maybeSubType, superType) {- // Equivalent type is a valid subtype- if (maybeSubType === superType) {- return true;- } // If superType is non-null, maybeSubType must also be non-null.--- if (isNonNullType(superType)) {- if (isNonNullType(maybeSubType)) {- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);- }-- return false;- }-- if (isNonNullType(maybeSubType)) {- // If superType is nullable, maybeSubType may be non-null or nullable.- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);- } // If superType type is a list, maybeSubType type must also be a list.--- if (isListType(superType)) {- if (isListType(maybeSubType)) {- return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);- }-- return false;- }-- if (isListType(maybeSubType)) {- // If superType is not a list, maybeSubType must also be not a list.- return false;- } // If superType type is an abstract type, check if it is super type of maybeSubType.- // Otherwise, the child type is not a valid subtype of the parent type.--- return isAbstractType(superType) && (isInterfaceType(maybeSubType) || isObjectType(maybeSubType)) && schema.isSubType(superType, maybeSubType);-}-/**- * Provided two composite types, determine if they "overlap". Two composite- * types overlap when the Sets of possible concrete types for each intersect.- *- * This is often used to determine if a fragment of a given type could possibly- * be visited in a context of another type.- *- * This function is commutative.- */--function doTypesOverlap(schema, typeA, typeB) {- // Equivalent types overlap- if (typeA === typeB) {- return true;- }-- if (isAbstractType(typeA)) {- if (isAbstractType(typeB)) {- // If both types are abstract, then determine if there is any intersection- // between possible concrete types of each.- return schema.getPossibleTypes(typeA).some(function (type) {- return schema.isSubType(typeB, type);- });- } // Determine if the latter type is a possible concrete type of the former.--- return schema.isSubType(typeA, typeB);- }-- if (isAbstractType(typeB)) {- // Determine if the former type is a possible concrete type of the latter.- return schema.isSubType(typeB, typeA);- } // Otherwise the types do not overlap.--- return false;-}--/* eslint-disable no-redeclare */-// $FlowFixMe-var arrayFrom = Array.from || function (obj, mapFn, thisArg) {- if (obj == null) {- throw new TypeError('Array.from requires an array-like object - not null or undefined');- } // Is Iterable?--- var iteratorMethod = obj[SYMBOL_ITERATOR];-- if (typeof iteratorMethod === 'function') {- var iterator = iteratorMethod.call(obj);- var result = [];- var step;-- for (var i = 0; !(step = iterator.next()).done; ++i) {- result.push(mapFn.call(thisArg, step.value, i)); // Infinite Iterators could cause forEach to run forever.- // After a very large number of iterations, produce an error.- // istanbul ignore if (Too big to actually test)-- if (i > 9999999) {- throw new TypeError('Near-infinite iteration.');- }- }-- return result;- } // Is Array like?--- var length = obj.length;-- if (typeof length === 'number' && length >= 0 && length % 1 === 0) {- var _result = [];-- for (var _i = 0; _i < length; ++_i) {- if (Object.prototype.hasOwnProperty.call(obj, _i)) {- _result.push(mapFn.call(thisArg, obj[_i], _i));- }- }-- return _result;- }-- return [];-};--/* eslint-disable no-redeclare */-// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441-var isFinitePolyfill = Number.isFinite || function (value) {- return typeof value === 'number' && isFinite(value);-};--function _typeof$3(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$3 = function _typeof(obj) { return typeof obj; }; } else { _typeof$3 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$3(obj); }-/**- * Returns true if the provided object is an Object (i.e. not a string literal)- * and is either Iterable or Array-like.- *- * This may be used in place of [Array.isArray()][isArray] to determine if an- * object should be iterated-over. It always excludes string literals and- * includes Arrays (regardless of if it is Iterable). It also includes other- * Array-like objects such as NodeList, TypedArray, and Buffer.- *- * @example- *- * isCollection([ 1, 2, 3 ]) // true- * isCollection('ABC') // false- * isCollection({ length: 1, 0: 'Alpha' }) // true- * isCollection({ key: 'value' }) // false- * isCollection(new Map()) // true- *- * @param obj- * An Object value which might implement the Iterable or Array-like protocols.- * @return {boolean} true if Iterable or Array-like Object.- */--function isCollection(obj) {- if (obj == null || _typeof$3(obj) !== 'object') {- return false;- } // Is Array like?--- var length = obj.length;-- if (typeof length === 'number' && length >= 0 && length % 1 === 0) {- return true;- } // Is Iterable?--- return typeof obj[SYMBOL_ITERATOR] === 'function';-}--/* eslint-disable no-redeclare */-// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441-var isInteger = Number.isInteger || function (value) {- return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;-};--// 32-bit signed integer, providing the broadest support across platforms.-//-// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because-// they are internally represented as IEEE 754 doubles.--var MAX_INT = 2147483647;-var MIN_INT = -2147483648;--function serializeInt(outputValue) {- var coercedValue = serializeObject(outputValue);-- if (typeof coercedValue === 'boolean') {- return coercedValue ? 1 : 0;- }-- var num = coercedValue;-- if (typeof coercedValue === 'string' && coercedValue !== '') {- num = Number(coercedValue);- }-- if (!isInteger(num)) {- throw new GraphQLError("Int cannot represent non-integer value: ".concat(inspect(coercedValue)));- }-- if (num > MAX_INT || num < MIN_INT) {- throw new GraphQLError('Int cannot represent non 32-bit signed integer value: ' + inspect(coercedValue));- }-- return num;-}--function coerceInt(inputValue) {- if (!isInteger(inputValue)) {- throw new GraphQLError("Int cannot represent non-integer value: ".concat(inspect(inputValue)));- }-- if (inputValue > MAX_INT || inputValue < MIN_INT) {- throw new GraphQLError("Int cannot represent non 32-bit signed integer value: ".concat(inputValue));- }-- return inputValue;-}--var GraphQLInt = new GraphQLScalarType({- name: 'Int',- description: 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.',- serialize: serializeInt,- parseValue: coerceInt,- parseLiteral: function parseLiteral(valueNode) {- if (valueNode.kind !== Kind.INT) {- throw new GraphQLError("Int cannot represent non-integer value: ".concat(print(valueNode)), valueNode);- }-- var num = parseInt(valueNode.value, 10);-- if (num > MAX_INT || num < MIN_INT) {- throw new GraphQLError("Int cannot represent non 32-bit signed integer value: ".concat(valueNode.value), valueNode);- }-- return num;- }-});--function serializeFloat(outputValue) {- var coercedValue = serializeObject(outputValue);-- if (typeof coercedValue === 'boolean') {- return coercedValue ? 1 : 0;- }-- var num = coercedValue;-- if (typeof coercedValue === 'string' && coercedValue !== '') {- num = Number(coercedValue);- }-- if (!isFinitePolyfill(num)) {- throw new GraphQLError("Float cannot represent non numeric value: ".concat(inspect(coercedValue)));- }-- return num;-}--function coerceFloat(inputValue) {- if (!isFinitePolyfill(inputValue)) {- throw new GraphQLError("Float cannot represent non numeric value: ".concat(inspect(inputValue)));- }-- return inputValue;-}--var GraphQLFloat = new GraphQLScalarType({- name: 'Float',- description: 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).',- serialize: serializeFloat,- parseValue: coerceFloat,- parseLiteral: function parseLiteral(valueNode) {- if (valueNode.kind !== Kind.FLOAT && valueNode.kind !== Kind.INT) {- throw new GraphQLError("Float cannot represent non numeric value: ".concat(print(valueNode)), valueNode);- }-- return parseFloat(valueNode.value);- }-}); // Support serializing objects with custom valueOf() or toJSON() functions --// a common way to represent a complex value which can be represented as-// a string (ex: MongoDB id objects).--function serializeObject(outputValue) {- if (isObjectLike(outputValue)) {- if (typeof outputValue.valueOf === 'function') {- var valueOfResult = outputValue.valueOf();-- if (!isObjectLike(valueOfResult)) {- return valueOfResult;- }- }-- if (typeof outputValue.toJSON === 'function') {- // $FlowFixMe(>=0.90.0)- return outputValue.toJSON();- }- }-- return outputValue;-}--function serializeString(outputValue) {- var coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not- // attempt to coerce object, function, symbol, or other types as strings.-- if (typeof coercedValue === 'string') {- return coercedValue;- }-- if (typeof coercedValue === 'boolean') {- return coercedValue ? 'true' : 'false';- }-- if (isFinitePolyfill(coercedValue)) {- return coercedValue.toString();- }-- throw new GraphQLError("String cannot represent value: ".concat(inspect(outputValue)));-}--function coerceString(inputValue) {- if (typeof inputValue !== 'string') {- throw new GraphQLError("String cannot represent a non string value: ".concat(inspect(inputValue)));- }-- return inputValue;-}--var GraphQLString = new GraphQLScalarType({- name: 'String',- description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.',- serialize: serializeString,- parseValue: coerceString,- parseLiteral: function parseLiteral(valueNode) {- if (valueNode.kind !== Kind.STRING) {- throw new GraphQLError("String cannot represent a non string value: ".concat(print(valueNode)), valueNode);- }-- return valueNode.value;- }-});--function serializeBoolean(outputValue) {- var coercedValue = serializeObject(outputValue);-- if (typeof coercedValue === 'boolean') {- return coercedValue;- }-- if (isFinitePolyfill(coercedValue)) {- return coercedValue !== 0;- }-- throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(inspect(coercedValue)));-}--function coerceBoolean(inputValue) {- if (typeof inputValue !== 'boolean') {- throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(inspect(inputValue)));- }-- return inputValue;-}--var GraphQLBoolean = new GraphQLScalarType({- name: 'Boolean',- description: 'The `Boolean` scalar type represents `true` or `false`.',- serialize: serializeBoolean,- parseValue: coerceBoolean,- parseLiteral: function parseLiteral(valueNode) {- if (valueNode.kind !== Kind.BOOLEAN) {- throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(print(valueNode)), valueNode);- }-- return valueNode.value;- }-});--function serializeID(outputValue) {- var coercedValue = serializeObject(outputValue);-- if (typeof coercedValue === 'string') {- return coercedValue;- }-- if (isInteger(coercedValue)) {- return String(coercedValue);- }-- throw new GraphQLError("ID cannot represent value: ".concat(inspect(outputValue)));-}--function coerceID(inputValue) {- if (typeof inputValue === 'string') {- return inputValue;- }-- if (isInteger(inputValue)) {- return inputValue.toString();- }-- throw new GraphQLError("ID cannot represent value: ".concat(inspect(inputValue)));-}--var GraphQLID = new GraphQLScalarType({- name: 'ID',- description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.',- serialize: serializeID,- parseValue: coerceID,- parseLiteral: function parseLiteral(valueNode) {- if (valueNode.kind !== Kind.STRING && valueNode.kind !== Kind.INT) {- throw new GraphQLError('ID cannot represent a non-string and non-integer value: ' + print(valueNode), valueNode);- }-- return valueNode.value;- }-});-var specifiedScalarTypes = Object.freeze([GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]);-function isSpecifiedScalarType(type) {- return specifiedScalarTypes.some(function (_ref) {- var name = _ref.name;- return type.name === name;- });-}--/**- * Produces a GraphQL Value AST given a JavaScript object.- * Function will match JavaScript/JSON values to GraphQL AST schema format- * by using suggested GraphQLInputType. For example:- *- * astFromValue("value", GraphQLString)- *- * A GraphQL type must be provided, which will be used to interpret different- * JavaScript values.- *- * | JSON Value | GraphQL Value |- * | ------------- | -------------------- |- * | Object | Input Object |- * | Array | List |- * | Boolean | Boolean |- * | String | String / Enum Value |- * | Number | Int / Float |- * | Mixed | Enum Value |- * | null | NullValue |- *- */--function astFromValue(value, type) {- if (isNonNullType(type)) {- var astValue = astFromValue(value, type.ofType);-- if ((astValue === null || astValue === void 0 ? void 0 : astValue.kind) === Kind.NULL) {- return null;- }-- return astValue;- } // only explicit null, not undefined, NaN--- if (value === null) {- return {- kind: Kind.NULL- };- } // undefined--- if (value === undefined) {- return null;- } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but- // the value is not an array, convert the value using the list's item type.--- if (isListType(type)) {- var itemType = type.ofType;-- if (isCollection(value)) {- var valuesNodes = []; // Since we transpile for-of in loose mode it doesn't support iterators- // and it's required to first convert iteratable into array-- for (var _i2 = 0, _arrayFrom2 = arrayFrom(value); _i2 < _arrayFrom2.length; _i2++) {- var item = _arrayFrom2[_i2];- var itemNode = astFromValue(item, itemType);-- if (itemNode != null) {- valuesNodes.push(itemNode);- }- }-- return {- kind: Kind.LIST,- values: valuesNodes- };- }-- return astFromValue(value, itemType);- } // Populate the fields of the input object by creating ASTs from each value- // in the JavaScript object according to the fields in the input type.--- if (isInputObjectType(type)) {- if (!isObjectLike(value)) {- return null;- }-- var fieldNodes = [];-- for (var _i4 = 0, _objectValues2 = objectValues(type.getFields()); _i4 < _objectValues2.length; _i4++) {- var field = _objectValues2[_i4];- var fieldValue = astFromValue(value[field.name], field.type);-- if (fieldValue) {- fieldNodes.push({- kind: Kind.OBJECT_FIELD,- name: {- kind: Kind.NAME,- value: field.name- },- value: fieldValue- });- }- }-- return {- kind: Kind.OBJECT,- fields: fieldNodes- };- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isLeafType(type)) {- // Since value is an internally represented value, it must be serialized- // to an externally represented value before converting into an AST.- var serialized = type.serialize(value);-- if (serialized == null) {- return null;- } // Others serialize based on their corresponding JavaScript scalar types.--- if (typeof serialized === 'boolean') {- return {- kind: Kind.BOOLEAN,- value: serialized- };- } // JavaScript numbers can be Int or Float values.--- if (typeof serialized === 'number' && isFinitePolyfill(serialized)) {- var stringNum = String(serialized);- return integerStringRegExp.test(stringNum) ? {- kind: Kind.INT,- value: stringNum- } : {- kind: Kind.FLOAT,- value: stringNum- };- }-- if (typeof serialized === 'string') {- // Enum types use Enum literals.- if (isEnumType(type)) {- return {- kind: Kind.ENUM,- value: serialized- };- } // ID types can use Int literals.--- if (type === GraphQLID && integerStringRegExp.test(serialized)) {- return {- kind: Kind.INT,- value: serialized- };- }-- return {- kind: Kind.STRING,- value: serialized- };- }-- throw new TypeError("Cannot convert value to AST: ".concat(inspect(serialized), "."));- } // istanbul ignore next (Not reachable. All possible input types have been considered)--- invariant(0, 'Unexpected input type: ' + inspect(type));-}-/**- * IntValue:- * - NegativeSign? 0- * - NegativeSign? NonZeroDigit ( Digit+ )?- */--var integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;--var __Schema = new GraphQLObjectType({- name: '__Schema',- description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.',- fields: function fields() {- return {- description: {- type: GraphQLString,- resolve: function resolve(schema) {- return schema.description;- }- },- types: {- description: 'A list of all types supported by this server.',- type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))),- resolve: function resolve(schema) {- return objectValues(schema.getTypeMap());- }- },- queryType: {- description: 'The type that query operations will be rooted at.',- type: GraphQLNonNull(__Type),- resolve: function resolve(schema) {- return schema.getQueryType();- }- },- mutationType: {- description: 'If this server supports mutation, the type that mutation operations will be rooted at.',- type: __Type,- resolve: function resolve(schema) {- return schema.getMutationType();- }- },- subscriptionType: {- description: 'If this server support subscription, the type that subscription operations will be rooted at.',- type: __Type,- resolve: function resolve(schema) {- return schema.getSubscriptionType();- }- },- directives: {- description: 'A list of all directives supported by this server.',- type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))),- resolve: function resolve(schema) {- return schema.getDirectives();- }- }- };- }-});-var __Directive = new GraphQLObjectType({- name: '__Directive',- description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.",- fields: function fields() {- return {- name: {- type: GraphQLNonNull(GraphQLString),- resolve: function resolve(directive) {- return directive.name;- }- },- description: {- type: GraphQLString,- resolve: function resolve(directive) {- return directive.description;- }- },- isRepeatable: {- type: GraphQLNonNull(GraphQLBoolean),- resolve: function resolve(directive) {- return directive.isRepeatable;- }- },- locations: {- type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))),- resolve: function resolve(directive) {- return directive.locations;- }- },- args: {- type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),- resolve: function resolve(directive) {- return directive.args;- }- }- };- }-});-var __DirectiveLocation = new GraphQLEnumType({- name: '__DirectiveLocation',- description: 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.',- values: {- QUERY: {- value: DirectiveLocation.QUERY,- description: 'Location adjacent to a query operation.'- },- MUTATION: {- value: DirectiveLocation.MUTATION,- description: 'Location adjacent to a mutation operation.'- },- SUBSCRIPTION: {- value: DirectiveLocation.SUBSCRIPTION,- description: 'Location adjacent to a subscription operation.'- },- FIELD: {- value: DirectiveLocation.FIELD,- description: 'Location adjacent to a field.'- },- FRAGMENT_DEFINITION: {- value: DirectiveLocation.FRAGMENT_DEFINITION,- description: 'Location adjacent to a fragment definition.'- },- FRAGMENT_SPREAD: {- value: DirectiveLocation.FRAGMENT_SPREAD,- description: 'Location adjacent to a fragment spread.'- },- INLINE_FRAGMENT: {- value: DirectiveLocation.INLINE_FRAGMENT,- description: 'Location adjacent to an inline fragment.'- },- VARIABLE_DEFINITION: {- value: DirectiveLocation.VARIABLE_DEFINITION,- description: 'Location adjacent to a variable definition.'- },- SCHEMA: {- value: DirectiveLocation.SCHEMA,- description: 'Location adjacent to a schema definition.'- },- SCALAR: {- value: DirectiveLocation.SCALAR,- description: 'Location adjacent to a scalar definition.'- },- OBJECT: {- value: DirectiveLocation.OBJECT,- description: 'Location adjacent to an object type definition.'- },- FIELD_DEFINITION: {- value: DirectiveLocation.FIELD_DEFINITION,- description: 'Location adjacent to a field definition.'- },- ARGUMENT_DEFINITION: {- value: DirectiveLocation.ARGUMENT_DEFINITION,- description: 'Location adjacent to an argument definition.'- },- INTERFACE: {- value: DirectiveLocation.INTERFACE,- description: 'Location adjacent to an interface definition.'- },- UNION: {- value: DirectiveLocation.UNION,- description: 'Location adjacent to a union definition.'- },- ENUM: {- value: DirectiveLocation.ENUM,- description: 'Location adjacent to an enum definition.'- },- ENUM_VALUE: {- value: DirectiveLocation.ENUM_VALUE,- description: 'Location adjacent to an enum value definition.'- },- INPUT_OBJECT: {- value: DirectiveLocation.INPUT_OBJECT,- description: 'Location adjacent to an input object type definition.'- },- INPUT_FIELD_DEFINITION: {- value: DirectiveLocation.INPUT_FIELD_DEFINITION,- description: 'Location adjacent to an input object field definition.'- }- }-});-var __Type = new GraphQLObjectType({- name: '__Type',- description: 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByUrl`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.',- fields: function fields() {- return {- kind: {- type: GraphQLNonNull(__TypeKind),- resolve: function resolve(type) {- if (isScalarType(type)) {- return TypeKind.SCALAR;- }-- if (isObjectType(type)) {- return TypeKind.OBJECT;- }-- if (isInterfaceType(type)) {- return TypeKind.INTERFACE;- }-- if (isUnionType(type)) {- return TypeKind.UNION;- }-- if (isEnumType(type)) {- return TypeKind.ENUM;- }-- if (isInputObjectType(type)) {- return TypeKind.INPUT_OBJECT;- }-- if (isListType(type)) {- return TypeKind.LIST;- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isNonNullType(type)) {- return TypeKind.NON_NULL;- } // istanbul ignore next (Not reachable. All possible types have been considered)--- invariant(0, "Unexpected type: \"".concat(inspect(type), "\"."));- }- },- name: {- type: GraphQLString,- resolve: function resolve(type) {- return type.name !== undefined ? type.name : undefined;- }- },- description: {- type: GraphQLString,- resolve: function resolve(type) {- return type.description !== undefined ? type.description : undefined;- }- },- specifiedByUrl: {- type: GraphQLString,- resolve: function resolve(obj) {- return obj.specifiedByUrl !== undefined ? obj.specifiedByUrl : undefined;- }- },- fields: {- type: GraphQLList(GraphQLNonNull(__Field)),- args: {- includeDeprecated: {- type: GraphQLBoolean,- defaultValue: false- }- },- resolve: function resolve(type, _ref) {- var includeDeprecated = _ref.includeDeprecated;-- if (isObjectType(type) || isInterfaceType(type)) {- var fields = objectValues(type.getFields());-- if (!includeDeprecated) {- fields = fields.filter(function (field) {- return !field.isDeprecated;- });- }-- return fields;- }-- return null;- }- },- interfaces: {- type: GraphQLList(GraphQLNonNull(__Type)),- resolve: function resolve(type) {- if (isObjectType(type) || isInterfaceType(type)) {- return type.getInterfaces();- }- }- },- possibleTypes: {- type: GraphQLList(GraphQLNonNull(__Type)),- resolve: function resolve(type, _args, _context, _ref2) {- var schema = _ref2.schema;-- if (isAbstractType(type)) {- return schema.getPossibleTypes(type);- }- }- },- enumValues: {- type: GraphQLList(GraphQLNonNull(__EnumValue)),- args: {- includeDeprecated: {- type: GraphQLBoolean,- defaultValue: false- }- },- resolve: function resolve(type, _ref3) {- var includeDeprecated = _ref3.includeDeprecated;-- if (isEnumType(type)) {- var values = type.getValues();-- if (!includeDeprecated) {- values = values.filter(function (value) {- return !value.isDeprecated;- });- }-- return values;- }- }- },- inputFields: {- type: GraphQLList(GraphQLNonNull(__InputValue)),- resolve: function resolve(type) {- if (isInputObjectType(type)) {- return objectValues(type.getFields());- }- }- },- ofType: {- type: __Type,- resolve: function resolve(type) {- return type.ofType !== undefined ? type.ofType : undefined;- }- }- };- }-});-var __Field = new GraphQLObjectType({- name: '__Field',- description: 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.',- fields: function fields() {- return {- name: {- type: GraphQLNonNull(GraphQLString),- resolve: function resolve(field) {- return field.name;- }- },- description: {- type: GraphQLString,- resolve: function resolve(field) {- return field.description;- }- },- args: {- type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),- resolve: function resolve(field) {- return field.args;- }- },- type: {- type: GraphQLNonNull(__Type),- resolve: function resolve(field) {- return field.type;- }- },- isDeprecated: {- type: GraphQLNonNull(GraphQLBoolean),- resolve: function resolve(field) {- return field.isDeprecated;- }- },- deprecationReason: {- type: GraphQLString,- resolve: function resolve(field) {- return field.deprecationReason;- }- }- };- }-});-var __InputValue = new GraphQLObjectType({- name: '__InputValue',- description: 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.',- fields: function fields() {- return {- name: {- type: GraphQLNonNull(GraphQLString),- resolve: function resolve(inputValue) {- return inputValue.name;- }- },- description: {- type: GraphQLString,- resolve: function resolve(inputValue) {- return inputValue.description;- }- },- type: {- type: GraphQLNonNull(__Type),- resolve: function resolve(inputValue) {- return inputValue.type;- }- },- defaultValue: {- type: GraphQLString,- description: 'A GraphQL-formatted string representing the default value for this input value.',- resolve: function resolve(inputValue) {- var type = inputValue.type,- defaultValue = inputValue.defaultValue;- var valueAST = astFromValue(defaultValue, type);- return valueAST ? print(valueAST) : null;- }- }- };- }-});-var __EnumValue = new GraphQLObjectType({- name: '__EnumValue',- description: 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.',- fields: function fields() {- return {- name: {- type: GraphQLNonNull(GraphQLString),- resolve: function resolve(enumValue) {- return enumValue.name;- }- },- description: {- type: GraphQLString,- resolve: function resolve(enumValue) {- return enumValue.description;- }- },- isDeprecated: {- type: GraphQLNonNull(GraphQLBoolean),- resolve: function resolve(enumValue) {- return enumValue.isDeprecated;- }- },- deprecationReason: {- type: GraphQLString,- resolve: function resolve(enumValue) {- return enumValue.deprecationReason;- }- }- };- }-});-var TypeKind = Object.freeze({- SCALAR: 'SCALAR',- OBJECT: 'OBJECT',- INTERFACE: 'INTERFACE',- UNION: 'UNION',- ENUM: 'ENUM',- INPUT_OBJECT: 'INPUT_OBJECT',- LIST: 'LIST',- NON_NULL: 'NON_NULL'-});-var __TypeKind = new GraphQLEnumType({- name: '__TypeKind',- description: 'An enum describing what kind of type a given `__Type` is.',- values: {- SCALAR: {- value: TypeKind.SCALAR,- description: 'Indicates this type is a scalar.'- },- OBJECT: {- value: TypeKind.OBJECT,- description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.'- },- INTERFACE: {- value: TypeKind.INTERFACE,- description: 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.'- },- UNION: {- value: TypeKind.UNION,- description: 'Indicates this type is a union. `possibleTypes` is a valid field.'- },- ENUM: {- value: TypeKind.ENUM,- description: 'Indicates this type is an enum. `enumValues` is a valid field.'- },- INPUT_OBJECT: {- value: TypeKind.INPUT_OBJECT,- description: 'Indicates this type is an input object. `inputFields` is a valid field.'- },- LIST: {- value: TypeKind.LIST,- description: 'Indicates this type is a list. `ofType` is a valid field.'- },- NON_NULL: {- value: TypeKind.NON_NULL,- description: 'Indicates this type is a non-null. `ofType` is a valid field.'- }- }-});-/**- * Note that these are GraphQLField and not GraphQLFieldConfig,- * so the format for args is different.- */--var SchemaMetaFieldDef = {- name: '__schema',- type: GraphQLNonNull(__Schema),- description: 'Access the current type schema of this server.',- args: [],- resolve: function resolve(_source, _args, _context, _ref4) {- var schema = _ref4.schema;- return schema;- },- isDeprecated: false,- deprecationReason: undefined,- extensions: undefined,- astNode: undefined-};-var TypeMetaFieldDef = {- name: '__type',- type: __Type,- description: 'Request the type information of a single type.',- args: [{- name: 'name',- description: undefined,- type: GraphQLNonNull(GraphQLString),- defaultValue: undefined,- extensions: undefined,- astNode: undefined- }],- resolve: function resolve(_source, _ref5, _context, _ref6) {- var name = _ref5.name;- var schema = _ref6.schema;- return schema.getType(name);- },- isDeprecated: false,- deprecationReason: undefined,- extensions: undefined,- astNode: undefined-};-var TypeNameMetaFieldDef = {- name: '__typename',- type: GraphQLNonNull(GraphQLString),- description: 'The name of the current Object type at runtime.',- args: [],- resolve: function resolve(_source, _args, _context, _ref7) {- var parentType = _ref7.parentType;- return parentType.name;- },- isDeprecated: false,- deprecationReason: undefined,- extensions: undefined,- astNode: undefined-};-var introspectionTypes = Object.freeze([__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]);-function isIntrospectionType(type) {- return introspectionTypes.some(function (_ref8) {- var name = _ref8.name;- return type.name === name;- });-}--function _defineProperties$3(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); } }--function _createClass$3(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$3(Constructor.prototype, protoProps); if (staticProps) _defineProperties$3(Constructor, staticProps); return Constructor; }-/**- * Test if the given value is a GraphQL directive.- */--// eslint-disable-next-line no-redeclare-function isDirective(directive) {- return instanceOf(directive, GraphQLDirective);-}-function assertDirective(directive) {- if (!isDirective(directive)) {- throw new Error("Expected ".concat(inspect(directive), " to be a GraphQL directive."));- }-- return directive;-}-/**- * Directives are used by the GraphQL runtime as a way of modifying execution- * behavior. Type system creators will usually not create these directly.- */--var GraphQLDirective = /*#__PURE__*/function () {- function GraphQLDirective(config) {- var _config$isRepeatable, _config$args;-- this.name = config.name;- this.description = config.description;- this.locations = config.locations;- this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false;- this.extensions = config.extensions && toObjMap(config.extensions);- this.astNode = config.astNode;- config.name || devAssert(0, 'Directive must be named.');- Array.isArray(config.locations) || devAssert(0, "@".concat(config.name, " locations must be an Array."));- var args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {};- isObjectLike(args) && !Array.isArray(args) || devAssert(0, "@".concat(config.name, " args must be an object with argument names as keys."));- this.args = objectEntries(args).map(function (_ref) {- var argName = _ref[0],- argConfig = _ref[1];- return {- name: argName,- description: argConfig.description,- type: argConfig.type,- defaultValue: argConfig.defaultValue,- extensions: argConfig.extensions && toObjMap(argConfig.extensions),- astNode: argConfig.astNode- };- });- }-- var _proto = GraphQLDirective.prototype;-- _proto.toConfig = function toConfig() {- return {- name: this.name,- description: this.description,- locations: this.locations,- args: argsToArgsConfig(this.args),- isRepeatable: this.isRepeatable,- extensions: this.extensions,- astNode: this.astNode- };- };-- _proto.toString = function toString() {- return '@' + this.name;- };-- _proto.toJSON = function toJSON() {- return this.toString();- } // $FlowFixMe Flow doesn't support computed properties yet- ;-- _createClass$3(GraphQLDirective, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'GraphQLDirective';- }- }]);-- return GraphQLDirective;-}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.--defineInspect(GraphQLDirective);--/**- * Used to conditionally include fields or fragments.- */-var GraphQLIncludeDirective = new GraphQLDirective({- name: 'include',- description: 'Directs the executor to include this field or fragment only when the `if` argument is true.',- locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT],- args: {- if: {- type: GraphQLNonNull(GraphQLBoolean),- description: 'Included when true.'- }- }-});-/**- * Used to conditionally skip (exclude) fields or fragments.- */--var GraphQLSkipDirective = new GraphQLDirective({- name: 'skip',- description: 'Directs the executor to skip this field or fragment when the `if` argument is true.',- locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT],- args: {- if: {- type: GraphQLNonNull(GraphQLBoolean),- description: 'Skipped when true.'- }- }-});-/**- * Constant string used for default reason for a deprecation.- */--var DEFAULT_DEPRECATION_REASON = 'No longer supported';-/**- * Used to declare element of a GraphQL schema as deprecated.- */--var GraphQLDeprecatedDirective = new GraphQLDirective({- name: 'deprecated',- description: 'Marks an element of a GraphQL schema as no longer supported.',- locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.ENUM_VALUE],- args: {- reason: {- type: GraphQLString,- description: 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).',- defaultValue: DEFAULT_DEPRECATION_REASON- }- }-});-/**- * Used to provide a URL for specifying the behaviour of custom scalar definitions.- */--var GraphQLSpecifiedByDirective = new GraphQLDirective({- name: 'specifiedBy',- description: 'Exposes a URL that specifies the behaviour of this scalar.',- locations: [DirectiveLocation.SCALAR],- args: {- url: {- type: GraphQLNonNull(GraphQLString),- description: 'The URL that specifies the behaviour of this scalar.'- }- }-});-/**- * The full list of specified directives.- */--var specifiedDirectives = Object.freeze([GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective]);-function isSpecifiedDirective(directive) {- return specifiedDirectives.some(function (_ref2) {- var name = _ref2.name;- return name === directive.name;- });-}--function _defineProperties$4(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); } }--function _createClass$4(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$4(Constructor.prototype, protoProps); if (staticProps) _defineProperties$4(Constructor, staticProps); return Constructor; }-/**- * Test if the given value is a GraphQL schema.- */--// eslint-disable-next-line no-redeclare-function isSchema(schema) {- return instanceOf(schema, GraphQLSchema);-}-function assertSchema(schema) {- if (!isSchema(schema)) {- throw new Error("Expected ".concat(inspect(schema), " to be a GraphQL schema."));- }-- return schema;-}-/**- * Schema Definition- *- * A Schema is created by supplying the root types of each type of operation,- * query and mutation (optional). A schema definition is then supplied to the- * validator and executor.- *- * Example:- *- * const MyAppSchema = new GraphQLSchema({- * query: MyAppQueryRootType,- * mutation: MyAppMutationRootType,- * })- *- * Note: When the schema is constructed, by default only the types that are- * reachable by traversing the root types are included, other types must be- * explicitly referenced.- *- * Example:- *- * const characterInterface = new GraphQLInterfaceType({- * name: 'Character',- * ...- * });- *- * const humanType = new GraphQLObjectType({- * name: 'Human',- * interfaces: [characterInterface],- * ...- * });- *- * const droidType = new GraphQLObjectType({- * name: 'Droid',- * interfaces: [characterInterface],- * ...- * });- *- * const schema = new GraphQLSchema({- * query: new GraphQLObjectType({- * name: 'Query',- * fields: {- * hero: { type: characterInterface, ... },- * }- * }),- * ...- * // Since this schema references only the `Character` interface it's- * // necessary to explicitly list the types that implement it if- * // you want them to be included in the final schema.- * types: [humanType, droidType],- * })- *- * Note: If an array of `directives` are provided to GraphQLSchema, that will be- * the exact list of directives represented and allowed. If `directives` is not- * provided then a default set of the specified directives (e.g. @include and- * @skip) will be used. If you wish to provide *additional* directives to these- * specified directives, you must explicitly declare them. Example:- *- * const MyAppSchema = new GraphQLSchema({- * ...- * directives: specifiedDirectives.concat([ myCustomDirective ]),- * })- *- */--var GraphQLSchema = /*#__PURE__*/function () {- // Used as a cache for validateSchema().- function GraphQLSchema(config) {- var _config$directives;-- // If this schema was built from a source known to be valid, then it may be- // marked with assumeValid to avoid an additional type system validation.- this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors.-- isObjectLike(config) || devAssert(0, 'Must provide configuration object.');- !config.types || Array.isArray(config.types) || devAssert(0, "\"types\" must be Array if provided but got: ".concat(inspect(config.types), "."));- !config.directives || Array.isArray(config.directives) || devAssert(0, '"directives" must be Array if provided but got: ' + "".concat(inspect(config.directives), "."));- this.description = config.description;- this.extensions = config.extensions && toObjMap(config.extensions);- this.astNode = config.astNode;- this.extensionASTNodes = config.extensionASTNodes;- this._queryType = config.query;- this._mutationType = config.mutation;- this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default.-- this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : specifiedDirectives; // To preserve order of user-provided types, we add first to add them to- // the set of "collected" types, so `collectReferencedTypes` ignore them.-- var allReferencedTypes = new Set(config.types);-- if (config.types != null) {- for (var _i2 = 0, _config$types2 = config.types; _i2 < _config$types2.length; _i2++) {- var type = _config$types2[_i2];- // When we ready to process this type, we remove it from "collected" types- // and then add it together with all dependent types in the correct position.- allReferencedTypes.delete(type);- collectReferencedTypes(type, allReferencedTypes);- }- }-- if (this._queryType != null) {- collectReferencedTypes(this._queryType, allReferencedTypes);- }-- if (this._mutationType != null) {- collectReferencedTypes(this._mutationType, allReferencedTypes);- }-- if (this._subscriptionType != null) {- collectReferencedTypes(this._subscriptionType, allReferencedTypes);- }-- for (var _i4 = 0, _this$_directives2 = this._directives; _i4 < _this$_directives2.length; _i4++) {- var directive = _this$_directives2[_i4];-- // Directives are not validated until validateSchema() is called.- if (isDirective(directive)) {- for (var _i6 = 0, _directive$args2 = directive.args; _i6 < _directive$args2.length; _i6++) {- var arg = _directive$args2[_i6];- collectReferencedTypes(arg.type, allReferencedTypes);- }- }- }-- collectReferencedTypes(__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema.-- this._typeMap = Object.create(null);- this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name.-- this._implementationsMap = Object.create(null);-- for (var _i8 = 0, _arrayFrom2 = arrayFrom(allReferencedTypes); _i8 < _arrayFrom2.length; _i8++) {- var namedType = _arrayFrom2[_i8];-- if (namedType == null) {- continue;- }-- var typeName = namedType.name;- typeName || devAssert(0, 'One of the provided types for building the Schema is missing a name.');-- if (this._typeMap[typeName] !== undefined) {- throw new Error("Schema must contain uniquely named types but contains multiple types named \"".concat(typeName, "\"."));- }-- this._typeMap[typeName] = namedType;-- if (isInterfaceType(namedType)) {- // Store implementations by interface.- for (var _i10 = 0, _namedType$getInterfa2 = namedType.getInterfaces(); _i10 < _namedType$getInterfa2.length; _i10++) {- var iface = _namedType$getInterfa2[_i10];-- if (isInterfaceType(iface)) {- var implementations = this._implementationsMap[iface.name];-- if (implementations === undefined) {- implementations = this._implementationsMap[iface.name] = {- objects: [],- interfaces: []- };- }-- implementations.interfaces.push(namedType);- }- }- } else if (isObjectType(namedType)) {- // Store implementations by objects.- for (var _i12 = 0, _namedType$getInterfa4 = namedType.getInterfaces(); _i12 < _namedType$getInterfa4.length; _i12++) {- var _iface = _namedType$getInterfa4[_i12];-- if (isInterfaceType(_iface)) {- var _implementations = this._implementationsMap[_iface.name];-- if (_implementations === undefined) {- _implementations = this._implementationsMap[_iface.name] = {- objects: [],- interfaces: []- };- }-- _implementations.objects.push(namedType);- }- }- }- }- }-- var _proto = GraphQLSchema.prototype;-- _proto.getQueryType = function getQueryType() {- return this._queryType;- };-- _proto.getMutationType = function getMutationType() {- return this._mutationType;- };-- _proto.getSubscriptionType = function getSubscriptionType() {- return this._subscriptionType;- };-- _proto.getTypeMap = function getTypeMap() {- return this._typeMap;- };-- _proto.getType = function getType(name) {- return this.getTypeMap()[name];- };-- _proto.getPossibleTypes = function getPossibleTypes(abstractType) {- return isUnionType(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects;- };-- _proto.getImplementations = function getImplementations(interfaceType) {- var implementations = this._implementationsMap[interfaceType.name];- return implementations !== null && implementations !== void 0 ? implementations : {- objects: [],- interfaces: []- };- } // @deprecated: use isSubType instead - will be removed in v16.- ;-- _proto.isPossibleType = function isPossibleType(abstractType, possibleType) {- return this.isSubType(abstractType, possibleType);- };-- _proto.isSubType = function isSubType(abstractType, maybeSubType) {- var map = this._subTypeMap[abstractType.name];-- if (map === undefined) {- map = Object.create(null);-- if (isUnionType(abstractType)) {- for (var _i14 = 0, _abstractType$getType2 = abstractType.getTypes(); _i14 < _abstractType$getType2.length; _i14++) {- var type = _abstractType$getType2[_i14];- map[type.name] = true;- }- } else {- var implementations = this.getImplementations(abstractType);-- for (var _i16 = 0, _implementations$obje2 = implementations.objects; _i16 < _implementations$obje2.length; _i16++) {- var _type = _implementations$obje2[_i16];- map[_type.name] = true;- }-- for (var _i18 = 0, _implementations$inte2 = implementations.interfaces; _i18 < _implementations$inte2.length; _i18++) {- var _type2 = _implementations$inte2[_i18];- map[_type2.name] = true;- }- }-- this._subTypeMap[abstractType.name] = map;- }-- return map[maybeSubType.name] !== undefined;- };-- _proto.getDirectives = function getDirectives() {- return this._directives;- };-- _proto.getDirective = function getDirective(name) {- return find(this.getDirectives(), function (directive) {- return directive.name === name;- });- };-- _proto.toConfig = function toConfig() {- var _this$extensionASTNod;-- return {- description: this.description,- query: this.getQueryType(),- mutation: this.getMutationType(),- subscription: this.getSubscriptionType(),- types: objectValues(this.getTypeMap()),- directives: this.getDirectives().slice(),- extensions: this.extensions,- astNode: this.astNode,- extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : [],- assumeValid: this.__validationErrors !== undefined- };- } // $FlowFixMe Flow doesn't support computed properties yet- ;-- _createClass$4(GraphQLSchema, [{- key: SYMBOL_TO_STRING_TAG,- get: function get() {- return 'GraphQLSchema';- }- }]);-- return GraphQLSchema;-}();--function collectReferencedTypes(type, typeSet) {- var namedType = getNamedType(type);-- if (!typeSet.has(namedType)) {- typeSet.add(namedType);-- if (isUnionType(namedType)) {- for (var _i20 = 0, _namedType$getTypes2 = namedType.getTypes(); _i20 < _namedType$getTypes2.length; _i20++) {- var memberType = _namedType$getTypes2[_i20];- collectReferencedTypes(memberType, typeSet);- }- } else if (isObjectType(namedType) || isInterfaceType(namedType)) {- for (var _i22 = 0, _namedType$getInterfa6 = namedType.getInterfaces(); _i22 < _namedType$getInterfa6.length; _i22++) {- var interfaceType = _namedType$getInterfa6[_i22];- collectReferencedTypes(interfaceType, typeSet);- }-- for (var _i24 = 0, _objectValues2 = objectValues(namedType.getFields()); _i24 < _objectValues2.length; _i24++) {- var field = _objectValues2[_i24];- collectReferencedTypes(field.type, typeSet);-- for (var _i26 = 0, _field$args2 = field.args; _i26 < _field$args2.length; _i26++) {- var arg = _field$args2[_i26];- collectReferencedTypes(arg.type, typeSet);- }- }- } else if (isInputObjectType(namedType)) {- for (var _i28 = 0, _objectValues4 = objectValues(namedType.getFields()); _i28 < _objectValues4.length; _i28++) {- var _field = _objectValues4[_i28];- collectReferencedTypes(_field.type, typeSet);- }- }- }-- return typeSet;-}--/**- * Implements the "Type Validation" sub-sections of the specification's- * "Type System" section.- *- * Validation runs synchronously, returning an array of encountered errors, or- * an empty array if no errors were encountered and the Schema is valid.- */--function validateSchema(schema) {- // First check to ensure the provided value is in fact a GraphQLSchema.- assertSchema(schema); // If this Schema has already been validated, return the previous results.-- if (schema.__validationErrors) {- return schema.__validationErrors;- } // Validate the schema, producing a list of errors.--- var context = new SchemaValidationContext(schema);- validateRootTypes(context);- validateDirectives(context);- validateTypes(context); // Persist the results of validation before returning to ensure validation- // does not run multiple times for this schema.-- var errors = context.getErrors();- schema.__validationErrors = errors;- return errors;-}-/**- * Utility function which asserts a schema is valid by throwing an error if- * it is invalid.- */--function assertValidSchema(schema) {- var errors = validateSchema(schema);-- if (errors.length !== 0) {- throw new Error(errors.map(function (error) {- return error.message;- }).join('\n\n'));- }-}--var SchemaValidationContext = /*#__PURE__*/function () {- function SchemaValidationContext(schema) {- this._errors = [];- this.schema = schema;- }-- var _proto = SchemaValidationContext.prototype;-- _proto.reportError = function reportError(message, nodes) {- var _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes;-- this.addError(new GraphQLError(message, _nodes));- };-- _proto.addError = function addError(error) {- this._errors.push(error);- };-- _proto.getErrors = function getErrors() {- return this._errors;- };-- return SchemaValidationContext;-}();--function validateRootTypes(context) {- var schema = context.schema;- var queryType = schema.getQueryType();-- if (!queryType) {- context.reportError('Query root type must be provided.', schema.astNode);- } else if (!isObjectType(queryType)) {- var _getOperationTypeNode;-- context.reportError("Query root type must be Object type, it cannot be ".concat(inspect(queryType), "."), (_getOperationTypeNode = getOperationTypeNode(schema, 'query')) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode);- }-- var mutationType = schema.getMutationType();-- if (mutationType && !isObjectType(mutationType)) {- var _getOperationTypeNode2;-- context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat(inspect(mutationType), "."), (_getOperationTypeNode2 = getOperationTypeNode(schema, 'mutation')) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode);- }-- var subscriptionType = schema.getSubscriptionType();-- if (subscriptionType && !isObjectType(subscriptionType)) {- var _getOperationTypeNode3;-- context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat(inspect(subscriptionType), "."), (_getOperationTypeNode3 = getOperationTypeNode(schema, 'subscription')) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode);- }-}--function getOperationTypeNode(schema, operation) {- var operationNodes = getAllSubNodes(schema, function (node) {- return node.operationTypes;- });-- for (var _i2 = 0; _i2 < operationNodes.length; _i2++) {- var node = operationNodes[_i2];-- if (node.operation === operation) {- return node.type;- }- }-- return undefined;-}--function validateDirectives(context) {- for (var _i4 = 0, _context$schema$getDi2 = context.schema.getDirectives(); _i4 < _context$schema$getDi2.length; _i4++) {- var directive = _context$schema$getDi2[_i4];-- // Ensure all directives are in fact GraphQL directives.- if (!isDirective(directive)) {- context.reportError("Expected directive but got: ".concat(inspect(directive), "."), directive === null || directive === void 0 ? void 0 : directive.astNode);- continue;- } // Ensure they are named correctly.--- validateName(context, directive); // TODO: Ensure proper locations.- // Ensure the arguments are valid.-- for (var _i6 = 0, _directive$args2 = directive.args; _i6 < _directive$args2.length; _i6++) {- var arg = _directive$args2[_i6];- // Ensure they are named correctly.- validateName(context, arg); // Ensure the type is an input type.-- if (!isInputType(arg.type)) {- context.reportError("The type of @".concat(directive.name, "(").concat(arg.name, ":) must be Input Type ") + "but got: ".concat(inspect(arg.type), "."), arg.astNode);- }- }- }-}--function validateName(context, node) {- // Ensure names are valid, however introspection types opt out.- var error = isValidNameError(node.name);-- if (error) {- context.addError(locatedError(error, node.astNode));- }-}--function validateTypes(context) {- var validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context);- var typeMap = context.schema.getTypeMap();-- for (var _i8 = 0, _objectValues2 = objectValues(typeMap); _i8 < _objectValues2.length; _i8++) {- var type = _objectValues2[_i8];-- // Ensure all provided types are in fact GraphQL type.- if (!isNamedType(type)) {- context.reportError("Expected GraphQL named type but got: ".concat(inspect(type), "."), type.astNode);- continue;- } // Ensure it is named correctly (excluding introspection types).--- if (!isIntrospectionType(type)) {- validateName(context, type);- }-- if (isObjectType(type)) {- // Ensure fields are valid- validateFields(context, type); // Ensure objects implement the interfaces they claim to.-- validateInterfaces(context, type);- } else if (isInterfaceType(type)) {- // Ensure fields are valid.- validateFields(context, type); // Ensure interfaces implement the interfaces they claim to.-- validateInterfaces(context, type);- } else if (isUnionType(type)) {- // Ensure Unions include valid member types.- validateUnionMembers(context, type);- } else if (isEnumType(type)) {- // Ensure Enums have valid values.- validateEnumValues(context, type);- } else if (isInputObjectType(type)) {- // Ensure Input Object fields are valid.- validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references-- validateInputObjectCircularRefs(type);- }- }-}--function validateFields(context, type) {- var fields = objectValues(type.getFields()); // Objects and Interfaces both must define one or more fields.-- if (fields.length === 0) {- context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type));- }-- for (var _i10 = 0; _i10 < fields.length; _i10++) {- var field = fields[_i10];- // Ensure they are named correctly.- validateName(context, field); // Ensure the type is an output type-- if (!isOutputType(field.type)) {- var _field$astNode;-- context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat(inspect(field.type), "."), (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type);- } // Ensure the arguments are valid--- for (var _i12 = 0, _field$args2 = field.args; _i12 < _field$args2.length; _i12++) {- var arg = _field$args2[_i12];- var argName = arg.name; // Ensure they are named correctly.-- validateName(context, arg); // Ensure the type is an input type-- if (!isInputType(arg.type)) {- var _arg$astNode;-- context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat(inspect(arg.type), "."), (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type);- }- }- }-}--function validateInterfaces(context, type) {- var ifaceTypeNames = Object.create(null);-- for (var _i14 = 0, _type$getInterfaces2 = type.getInterfaces(); _i14 < _type$getInterfaces2.length; _i14++) {- var iface = _type$getInterfaces2[_i14];-- if (!isInterfaceType(iface)) {- context.reportError("Type ".concat(inspect(type), " must only implement Interface types, ") + "it cannot implement ".concat(inspect(iface), "."), getAllImplementsInterfaceNodes(type, iface));- continue;- }-- if (type === iface) {- context.reportError("Type ".concat(type.name, " cannot implement itself because it would create a circular reference."), getAllImplementsInterfaceNodes(type, iface));- continue;- }-- if (ifaceTypeNames[iface.name]) {- context.reportError("Type ".concat(type.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(type, iface));- continue;- }-- ifaceTypeNames[iface.name] = true;- validateTypeImplementsAncestors(context, type, iface);- validateTypeImplementsInterface(context, type, iface);- }-}--function validateTypeImplementsInterface(context, type, iface) {- var typeFieldMap = type.getFields(); // Assert each interface field is implemented.-- for (var _i16 = 0, _objectValues4 = objectValues(iface.getFields()); _i16 < _objectValues4.length; _i16++) {- var ifaceField = _objectValues4[_i16];- var fieldName = ifaceField.name;- var typeField = typeFieldMap[fieldName]; // Assert interface field exists on type.-- if (!typeField) {- context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ").concat(type.name, " does not provide it."), [ifaceField.astNode].concat(getAllNodes(type)));- continue;- } // Assert interface field type is satisfied by type field type, by being- // a valid subtype. (covariant)--- if (!isTypeSubTypeOf(context.schema, typeField.type, ifaceField.type)) {- var _ifaceField$astNode, _typeField$astNode;-- context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat(inspect(ifaceField.type), " but ").concat(type.name, ".").concat(fieldName, " ") + "is type ".concat(inspect(typeField.type), "."), [// istanbul ignore next (TODO need to write coverage tests)- (_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type, // istanbul ignore next (TODO need to write coverage tests)- (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type]);- } // Assert each interface field arg is implemented.--- var _loop = function _loop(_i18, _ifaceField$args2) {- var ifaceArg = _ifaceField$args2[_i18];- var argName = ifaceArg.name;- var typeArg = find(typeField.args, function (arg) {- return arg.name === argName;- }); // Assert interface field arg exists on object field.-- if (!typeArg) {- context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) expected but ").concat(type.name, ".").concat(fieldName, " does not provide it."), [ifaceArg.astNode, typeField.astNode]);- return "continue";- } // Assert interface field arg type matches object field arg type.- // (invariant)- // TODO: change to contravariant?--- if (!isEqualType(ifaceArg.type, typeArg.type)) {- var _ifaceArg$astNode, _typeArg$astNode;-- context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat(inspect(ifaceArg.type), " but ") + "".concat(type.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat(inspect(typeArg.type), "."), [// istanbul ignore next (TODO need to write coverage tests)- (_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type, // istanbul ignore next (TODO need to write coverage tests)- (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type]);- } // TODO: validate default values?-- };-- for (var _i18 = 0, _ifaceField$args2 = ifaceField.args; _i18 < _ifaceField$args2.length; _i18++) {- var _ret = _loop(_i18, _ifaceField$args2);-- if (_ret === "continue") continue;- } // Assert additional arguments must not be required.--- var _loop2 = function _loop2(_i20, _typeField$args2) {- var typeArg = _typeField$args2[_i20];- var argName = typeArg.name;- var ifaceArg = find(ifaceField.args, function (arg) {- return arg.name === argName;- });-- if (!ifaceArg && isRequiredArgument(typeArg)) {- context.reportError("Object field ".concat(type.name, ".").concat(fieldName, " includes required argument ").concat(argName, " that is missing from the Interface field ").concat(iface.name, ".").concat(fieldName, "."), [typeArg.astNode, ifaceField.astNode]);- }- };-- for (var _i20 = 0, _typeField$args2 = typeField.args; _i20 < _typeField$args2.length; _i20++) {- _loop2(_i20, _typeField$args2);- }- }-}--function validateTypeImplementsAncestors(context, type, iface) {- var ifaceInterfaces = type.getInterfaces();-- for (var _i22 = 0, _iface$getInterfaces2 = iface.getInterfaces(); _i22 < _iface$getInterfaces2.length; _i22++) {- var transitive = _iface$getInterfaces2[_i22];-- if (ifaceInterfaces.indexOf(transitive) === -1) {- context.reportError(transitive === type ? "Type ".concat(type.name, " cannot implement ").concat(iface.name, " because it would create a circular reference.") : "Type ".concat(type.name, " must implement ").concat(transitive.name, " because it is implemented by ").concat(iface.name, "."), [].concat(getAllImplementsInterfaceNodes(iface, transitive), getAllImplementsInterfaceNodes(type, iface)));- }- }-}--function validateUnionMembers(context, union) {- var memberTypes = union.getTypes();-- if (memberTypes.length === 0) {- context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union));- }-- var includedTypeNames = Object.create(null);-- for (var _i24 = 0; _i24 < memberTypes.length; _i24++) {- var memberType = memberTypes[_i24];-- if (includedTypeNames[memberType.name]) {- context.reportError("Union type ".concat(union.name, " can only include type ").concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name));- continue;- }-- includedTypeNames[memberType.name] = true;-- if (!isObjectType(memberType)) {- context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat(inspect(memberType), "."), getUnionMemberTypeNodes(union, String(memberType)));- }- }-}--function validateEnumValues(context, enumType) {- var enumValues = enumType.getValues();-- if (enumValues.length === 0) {- context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType));- }-- for (var _i26 = 0; _i26 < enumValues.length; _i26++) {- var enumValue = enumValues[_i26];- var valueName = enumValue.name; // Ensure valid name.-- validateName(context, enumValue);-- if (valueName === 'true' || valueName === 'false' || valueName === 'null') {- context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode);- }- }-}--function validateInputFields(context, inputObj) {- var fields = objectValues(inputObj.getFields());-- if (fields.length === 0) {- context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj));- } // Ensure the arguments are valid--- for (var _i28 = 0; _i28 < fields.length; _i28++) {- var field = fields[_i28];- // Ensure they are named correctly.- validateName(context, field); // Ensure the type is an input type-- if (!isInputType(field.type)) {- var _field$astNode2;-- context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat(inspect(field.type), "."), (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type);- }- }-}--function createInputObjectCircularRefsValidator(context) {- // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'.- // Tracks already visited types to maintain O(N) and to ensure that cycles- // are not redundantly reported.- var visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors-- var fieldPath = []; // Position in the type path-- var fieldPathIndexByTypeName = Object.create(null);- return detectCycleRecursive; // This does a straight-forward DFS to find cycles.- // It does not terminate when a cycle was found but continues to explore- // the graph to find all possible cycles.-- function detectCycleRecursive(inputObj) {- if (visitedTypes[inputObj.name]) {- return;- }-- visitedTypes[inputObj.name] = true;- fieldPathIndexByTypeName[inputObj.name] = fieldPath.length;- var fields = objectValues(inputObj.getFields());-- for (var _i30 = 0; _i30 < fields.length; _i30++) {- var field = fields[_i30];-- if (isNonNullType(field.type) && isInputObjectType(field.type.ofType)) {- var fieldType = field.type.ofType;- var cycleIndex = fieldPathIndexByTypeName[fieldType.name];- fieldPath.push(field);-- if (cycleIndex === undefined) {- detectCycleRecursive(fieldType);- } else {- var cyclePath = fieldPath.slice(cycleIndex);- var pathStr = cyclePath.map(function (fieldObj) {- return fieldObj.name;- }).join('.');- context.reportError("Cannot reference Input Object \"".concat(fieldType.name, "\" within itself through a series of non-null fields: \"").concat(pathStr, "\"."), cyclePath.map(function (fieldObj) {- return fieldObj.astNode;- }));- }-- fieldPath.pop();- }- }-- fieldPathIndexByTypeName[inputObj.name] = undefined;- }-}--function getAllNodes(object) {- var astNode = object.astNode,- extensionASTNodes = object.extensionASTNodes;- return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes !== null && extensionASTNodes !== void 0 ? extensionASTNodes : [];-}--function getAllSubNodes(object, getter) {- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- return flatMap(getAllNodes(object), function (item) {- var _getter;-- return (_getter = getter(item)) !== null && _getter !== void 0 ? _getter : [];- });-}--function getAllImplementsInterfaceNodes(type, iface) {- return getAllSubNodes(type, function (typeNode) {- return typeNode.interfaces;- }).filter(function (ifaceNode) {- return ifaceNode.name.value === iface.name;- });-}--function getUnionMemberTypeNodes(union, typeName) {- return getAllSubNodes(union, function (unionNode) {- return unionNode.types;- }).filter(function (typeNode) {- return typeNode.name.value === typeName;- });-}--/**- * Given a Schema and an AST node describing a type, return a GraphQLType- * definition which applies to that type. For example, if provided the parsed- * AST node for `[User]`, a GraphQLList instance will be returned, containing- * the type called "User" found in the schema. If a type called "User" is not- * found in the schema, then undefined will be returned.- */--/* eslint-disable no-redeclare */--function typeFromAST(schema, typeNode) {- /* eslint-enable no-redeclare */- var innerType;-- if (typeNode.kind === Kind.LIST_TYPE) {- innerType = typeFromAST(schema, typeNode.type);- return innerType && GraphQLList(innerType);- }-- if (typeNode.kind === Kind.NON_NULL_TYPE) {- innerType = typeFromAST(schema, typeNode.type);- return innerType && GraphQLNonNull(innerType);- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (typeNode.kind === Kind.NAMED_TYPE) {- return schema.getType(typeNode.name.value);- } // istanbul ignore next (Not reachable. All possible type nodes have been considered)--- invariant(0, 'Unexpected type node: ' + inspect(typeNode));-}--/**- * TypeInfo is a utility class which, given a GraphQL schema, can keep track- * of the current field and type definitions at any point in a GraphQL document- * AST during a recursive descent by calling `enter(node)` and `leave(node)`.- */--var TypeInfo = /*#__PURE__*/function () {- function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order- // to support non-spec-compliant code bases. You should never need to use it.- // It may disappear in the future.- getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals- // beginning somewhere other than documents.- initialType) {- this._schema = schema;- this._typeStack = [];- this._parentTypeStack = [];- this._inputTypeStack = [];- this._fieldDefStack = [];- this._defaultValueStack = [];- this._directive = null;- this._argument = null;- this._enumValue = null;- this._getFieldDef = getFieldDefFn !== null && getFieldDefFn !== void 0 ? getFieldDefFn : getFieldDef;-- if (initialType) {- if (isInputType(initialType)) {- this._inputTypeStack.push(initialType);- }-- if (isCompositeType(initialType)) {- this._parentTypeStack.push(initialType);- }-- if (isOutputType(initialType)) {- this._typeStack.push(initialType);- }- }- }-- var _proto = TypeInfo.prototype;-- _proto.getType = function getType() {- if (this._typeStack.length > 0) {- return this._typeStack[this._typeStack.length - 1];- }- };-- _proto.getParentType = function getParentType() {- if (this._parentTypeStack.length > 0) {- return this._parentTypeStack[this._parentTypeStack.length - 1];- }- };-- _proto.getInputType = function getInputType() {- if (this._inputTypeStack.length > 0) {- return this._inputTypeStack[this._inputTypeStack.length - 1];- }- };-- _proto.getParentInputType = function getParentInputType() {- if (this._inputTypeStack.length > 1) {- return this._inputTypeStack[this._inputTypeStack.length - 2];- }- };-- _proto.getFieldDef = function getFieldDef() {- if (this._fieldDefStack.length > 0) {- return this._fieldDefStack[this._fieldDefStack.length - 1];- }- };-- _proto.getDefaultValue = function getDefaultValue() {- if (this._defaultValueStack.length > 0) {- return this._defaultValueStack[this._defaultValueStack.length - 1];- }- };-- _proto.getDirective = function getDirective() {- return this._directive;- };-- _proto.getArgument = function getArgument() {- return this._argument;- };-- _proto.getEnumValue = function getEnumValue() {- return this._enumValue;- };-- _proto.enter = function enter(node) {- var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop- // any assumptions of a valid schema to ensure runtime types are properly- // checked before continuing since TypeInfo is used as part of validation- // which occurs before guarantees of schema and document validity.-- switch (node.kind) {- case Kind.SELECTION_SET:- {- var namedType = getNamedType(this.getType());-- this._parentTypeStack.push(isCompositeType(namedType) ? namedType : undefined);-- break;- }-- case Kind.FIELD:- {- var parentType = this.getParentType();- var fieldDef;- var fieldType;-- if (parentType) {- fieldDef = this._getFieldDef(schema, parentType, node);-- if (fieldDef) {- fieldType = fieldDef.type;- }- }-- this._fieldDefStack.push(fieldDef);-- this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined);-- break;- }-- case Kind.DIRECTIVE:- this._directive = schema.getDirective(node.name.value);- break;-- case Kind.OPERATION_DEFINITION:- {- var type;-- switch (node.operation) {- case 'query':- type = schema.getQueryType();- break;-- case 'mutation':- type = schema.getMutationType();- break;-- case 'subscription':- type = schema.getSubscriptionType();- break;- }-- this._typeStack.push(isObjectType(type) ? type : undefined);-- break;- }-- case Kind.INLINE_FRAGMENT:- case Kind.FRAGMENT_DEFINITION:- {- var typeConditionAST = node.typeCondition;- var outputType = typeConditionAST ? typeFromAST(schema, typeConditionAST) : getNamedType(this.getType());-- this._typeStack.push(isOutputType(outputType) ? outputType : undefined);-- break;- }-- case Kind.VARIABLE_DEFINITION:- {- var inputType = typeFromAST(schema, node.type);-- this._inputTypeStack.push(isInputType(inputType) ? inputType : undefined);-- break;- }-- case Kind.ARGUMENT:- {- var _this$getDirective;-- var argDef;- var argType;- var fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef();-- if (fieldOrDirective) {- argDef = find(fieldOrDirective.args, function (arg) {- return arg.name === node.name.value;- });-- if (argDef) {- argType = argDef.type;- }- }-- this._argument = argDef;-- this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);-- this._inputTypeStack.push(isInputType(argType) ? argType : undefined);-- break;- }-- case Kind.LIST:- {- var listType = getNullableType(this.getInputType());- var itemType = isListType(listType) ? listType.ofType : listType; // List positions never have a default value.-- this._defaultValueStack.push(undefined);-- this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined);-- break;- }-- case Kind.OBJECT_FIELD:- {- var objectType = getNamedType(this.getInputType());- var inputFieldType;- var inputField;-- if (isInputObjectType(objectType)) {- inputField = objectType.getFields()[node.name.value];-- if (inputField) {- inputFieldType = inputField.type;- }- }-- this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined);-- this._inputTypeStack.push(isInputType(inputFieldType) ? inputFieldType : undefined);-- break;- }-- case Kind.ENUM:- {- var enumType = getNamedType(this.getInputType());- var enumValue;-- if (isEnumType(enumType)) {- enumValue = enumType.getValue(node.value);- }-- this._enumValue = enumValue;- break;- }- }- };-- _proto.leave = function leave(node) {- switch (node.kind) {- case Kind.SELECTION_SET:- this._parentTypeStack.pop();-- break;-- case Kind.FIELD:- this._fieldDefStack.pop();-- this._typeStack.pop();-- break;-- case Kind.DIRECTIVE:- this._directive = null;- break;-- case Kind.OPERATION_DEFINITION:- case Kind.INLINE_FRAGMENT:- case Kind.FRAGMENT_DEFINITION:- this._typeStack.pop();-- break;-- case Kind.VARIABLE_DEFINITION:- this._inputTypeStack.pop();-- break;-- case Kind.ARGUMENT:- this._argument = null;-- this._defaultValueStack.pop();-- this._inputTypeStack.pop();-- break;-- case Kind.LIST:- case Kind.OBJECT_FIELD:- this._defaultValueStack.pop();-- this._inputTypeStack.pop();-- break;-- case Kind.ENUM:- this._enumValue = null;- break;- }- };-- return TypeInfo;-}();-/**- * Not exactly the same as the executor's definition of getFieldDef, in this- * statically evaluated environment we do not always have an Object type,- * and need to handle Interface and Union types.- */--function getFieldDef(schema, parentType, fieldNode) {- var name = fieldNode.name.value;-- if (name === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {- return SchemaMetaFieldDef;- }-- if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {- return TypeMetaFieldDef;- }-- if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) {- return TypeNameMetaFieldDef;- }-- if (isObjectType(parentType) || isInterfaceType(parentType)) {- return parentType.getFields()[name];- }-}-/**- * 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;- }- };-}--function isDefinitionNode(node) {- return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node);-}-function isExecutableDefinitionNode(node) {- return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION;-}-function isSelectionNode(node) {- return node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_SPREAD || node.kind === Kind.INLINE_FRAGMENT;-}-function isValueNode(node) {- return node.kind === Kind.VARIABLE || node.kind === Kind.INT || node.kind === Kind.FLOAT || node.kind === Kind.STRING || node.kind === Kind.BOOLEAN || node.kind === Kind.NULL || node.kind === Kind.ENUM || node.kind === Kind.LIST || node.kind === Kind.OBJECT;-}-function isTypeNode(node) {- return node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || node.kind === Kind.NON_NULL_TYPE;-}-function isTypeSystemDefinitionNode(node) {- return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION;-}-function isTypeDefinitionNode(node) {- return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION;-}-function isTypeSystemExtensionNode(node) {- return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);-}-function isTypeExtensionNode(node) {- return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION;-}--/**- * Executable definitions- *- * A GraphQL document is only valid for execution if all definitions are either- * operation or fragment definitions.- */-function ExecutableDefinitionsRule(context) {- return {- Document: function Document(node) {- for (var _i2 = 0, _node$definitions2 = node.definitions; _i2 < _node$definitions2.length; _i2++) {- var definition = _node$definitions2[_i2];-- if (!isExecutableDefinitionNode(definition)) {- var defName = definition.kind === Kind.SCHEMA_DEFINITION || definition.kind === Kind.SCHEMA_EXTENSION ? 'schema' : '"' + definition.name.value + '"';- context.reportError(new GraphQLError("The ".concat(defName, " definition is not executable."), definition));- }- }-- return false;- }- };-}--/**- * Unique operation names- *- * A GraphQL document is only valid if all defined operations have unique names.- */-function UniqueOperationNamesRule(context) {- var knownOperationNames = Object.create(null);- return {- OperationDefinition: function OperationDefinition(node) {- var operationName = node.name;-- if (operationName) {- if (knownOperationNames[operationName.value]) {- context.reportError(new GraphQLError("There can be only one operation named \"".concat(operationName.value, "\"."), [knownOperationNames[operationName.value], operationName]));- } else {- knownOperationNames[operationName.value] = operationName;- }- }-- return false;- },- FragmentDefinition: function FragmentDefinition() {- return false;- }- };-}--/**- * Lone anonymous operation- *- * A GraphQL document is only valid if when it contains an anonymous operation- * (the query short-hand) that it contains only that one operation definition.- */-function LoneAnonymousOperationRule(context) {- var operationCount = 0;- return {- Document: function Document(node) {- operationCount = node.definitions.filter(function (definition) {- return definition.kind === Kind.OPERATION_DEFINITION;- }).length;- },- OperationDefinition: function OperationDefinition(node) {- if (!node.name && operationCount > 1) {- context.reportError(new GraphQLError('This anonymous operation must be the only defined operation.', node));- }- }- };-}--/**- * Subscriptions must only include one field.- *- * A GraphQL subscription is valid only if it contains a single root field.- */-function SingleFieldSubscriptionsRule(context) {- return {- OperationDefinition: function OperationDefinition(node) {- if (node.operation === 'subscription') {- if (node.selectionSet.selections.length !== 1) {- context.reportError(new GraphQLError(node.name ? "Subscription \"".concat(node.name.value, "\" must select only one top level field.") : 'Anonymous Subscription must select only one top level field.', node.selectionSet.selections.slice(1)));- }- }- }- };-}--/**- * Known type names- *- * A GraphQL document is only valid if referenced types (specifically- * variable definitions and fragment conditions) are defined by the type schema.- */-function KnownTypeNamesRule(context) {- var schema = context.getSchema();- var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);- var definedTypes = Object.create(null);-- for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {- var def = _context$getDocument$2[_i2];-- if (isTypeDefinitionNode(def)) {- definedTypes[def.name.value] = true;- }- }-- var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));- return {- NamedType: function NamedType(node, _1, parent, _2, ancestors) {- var typeName = node.name.value;-- if (!existingTypesMap[typeName] && !definedTypes[typeName]) {- var _ancestors$;-- var definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent;- var isSDL = definitionNode != null && isSDLNode(definitionNode);-- if (isSDL && isStandardTypeName(typeName)) {- return;- }-- var suggestedTypes = suggestionList(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames);- context.reportError(new GraphQLError("Unknown type \"".concat(typeName, "\".") + didYouMean(suggestedTypes), node));- }- }- };-}-var standardTypeNames = [].concat(specifiedScalarTypes, introspectionTypes).map(function (type) {- return type.name;-});--function isStandardTypeName(typeName) {- return standardTypeNames.indexOf(typeName) !== -1;-}--function isSDLNode(value) {- return !Array.isArray(value) && (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value));-}--/**- * Fragments on composite type- *- * Fragments use a type condition to determine if they apply, since fragments- * can only be spread into a composite type (object, interface, or union), the- * type condition must also be a composite type.- */-function FragmentsOnCompositeTypesRule(context) {- return {- InlineFragment: function InlineFragment(node) {- var typeCondition = node.typeCondition;-- if (typeCondition) {- var type = typeFromAST(context.getSchema(), typeCondition);-- if (type && !isCompositeType(type)) {- var typeStr = print(typeCondition);- context.reportError(new GraphQLError("Fragment cannot condition on non composite type \"".concat(typeStr, "\"."), typeCondition));- }- }- },- FragmentDefinition: function FragmentDefinition(node) {- var type = typeFromAST(context.getSchema(), node.typeCondition);-- if (type && !isCompositeType(type)) {- var typeStr = print(node.typeCondition);- context.reportError(new GraphQLError("Fragment \"".concat(node.name.value, "\" cannot condition on non composite type \"").concat(typeStr, "\"."), node.typeCondition));- }- }- };-}--/**- * Variables are input types- *- * A GraphQL operation is only valid if all the variables it defines are of- * input types (scalar, enum, or input object).- */-function VariablesAreInputTypesRule(context) {- return {- VariableDefinition: function VariableDefinition(node) {- var type = typeFromAST(context.getSchema(), node.type);-- if (type && !isInputType(type)) {- var variableName = node.variable.name.value;- var typeName = print(node.type);- context.reportError(new GraphQLError("Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\"."), node.type));- }- }- };-}--/**- * Scalar leafs- *- * A GraphQL document is valid only if all leaf fields (fields without- * sub selections) are of scalar or enum types.- */-function ScalarLeafsRule(context) {- return {- Field: function Field(node) {- var type = context.getType();- var selectionSet = node.selectionSet;-- if (type) {- if (isLeafType(getNamedType(type))) {- if (selectionSet) {- var fieldName = node.name.value;- var typeStr = inspect(type);- context.reportError(new GraphQLError("Field \"".concat(fieldName, "\" must not have a selection since type \"").concat(typeStr, "\" has no subfields."), selectionSet));- }- } else if (!selectionSet) {- var _fieldName = node.name.value;-- var _typeStr = inspect(type);-- context.reportError(new GraphQLError("Field \"".concat(_fieldName, "\" of type \"").concat(_typeStr, "\" must have a selection of subfields. Did you mean \"").concat(_fieldName, " { ... }\"?"), node));- }- }- }- };-}--/**- * Fields on correct type- *- * A GraphQL document is only valid if all fields selected are defined by the- * parent type, or are an allowed meta field such as __typename.- */-function FieldsOnCorrectTypeRule(context) {- return {- Field: function Field(node) {- var type = context.getParentType();-- if (type) {- var fieldDef = context.getFieldDef();-- if (!fieldDef) {- // This field doesn't exist, lets look for suggestions.- var schema = context.getSchema();- var fieldName = node.name.value; // First determine if there are any suggested types to condition on.-- var suggestion = didYouMean('to use an inline fragment on', getSuggestedTypeNames(schema, type, fieldName)); // If there are no suggested types, then perhaps this was a typo?-- if (suggestion === '') {- suggestion = didYouMean(getSuggestedFieldNames(type, fieldName));- } // Report an error, including helpful suggestions.--- context.reportError(new GraphQLError("Cannot query field \"".concat(fieldName, "\" on type \"").concat(type.name, "\".") + suggestion, node));- }- }- }- };-}-/**- * Go through all of the implementations of type, as well as the interfaces that- * they implement. If any of those types include the provided field, suggest them,- * sorted by how often the type is referenced.- */--function getSuggestedTypeNames(schema, type, fieldName) {- if (!isAbstractType(type)) {- // Must be an Object type, which does not have possible fields.- return [];- }-- var suggestedTypes = new Set();- var usageCount = Object.create(null);-- for (var _i2 = 0, _schema$getPossibleTy2 = schema.getPossibleTypes(type); _i2 < _schema$getPossibleTy2.length; _i2++) {- var possibleType = _schema$getPossibleTy2[_i2];-- if (!possibleType.getFields()[fieldName]) {- continue;- } // This object type defines this field.--- suggestedTypes.add(possibleType);- usageCount[possibleType.name] = 1;-- for (var _i4 = 0, _possibleType$getInte2 = possibleType.getInterfaces(); _i4 < _possibleType$getInte2.length; _i4++) {- var _usageCount$possibleI;-- var possibleInterface = _possibleType$getInte2[_i4];-- if (!possibleInterface.getFields()[fieldName]) {- continue;- } // This interface type defines this field.--- suggestedTypes.add(possibleInterface);- usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1;- }- }-- return arrayFrom(suggestedTypes).sort(function (typeA, typeB) {- // Suggest both interface and object types based on how common they are.- var usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name];-- if (usageCountDiff !== 0) {- return usageCountDiff;- } // Suggest super types first followed by subtypes--- if (isInterfaceType(typeA) && schema.isSubType(typeA, typeB)) {- return -1;- }-- if (isInterfaceType(typeB) && schema.isSubType(typeB, typeA)) {- return 1;- }-- return typeA.name.localeCompare(typeB.name);- }).map(function (x) {- return x.name;- });-}-/**- * For the field name provided, determine if there are any similar field names- * that may be the result of a typo.- */---function getSuggestedFieldNames(type, fieldName) {- if (isObjectType(type) || isInterfaceType(type)) {- var possibleFieldNames = Object.keys(type.getFields());- return suggestionList(fieldName, possibleFieldNames);- } // Otherwise, must be a Union type, which does not define fields.--- return [];-}--/**- * Unique fragment names- *- * A GraphQL document is only valid if all defined fragments have unique names.- */-function UniqueFragmentNamesRule(context) {- var knownFragmentNames = Object.create(null);- return {- OperationDefinition: function OperationDefinition() {- return false;- },- FragmentDefinition: function FragmentDefinition(node) {- var fragmentName = node.name.value;-- if (knownFragmentNames[fragmentName]) {- context.reportError(new GraphQLError("There can be only one fragment named \"".concat(fragmentName, "\"."), [knownFragmentNames[fragmentName], node.name]));- } else {- knownFragmentNames[fragmentName] = node.name;- }-- return false;- }- };-}--/**- * Known fragment names- *- * A GraphQL document is only valid if all `...Fragment` fragment spreads refer- * to fragments defined in the same document.- */-function KnownFragmentNamesRule(context) {- return {- FragmentSpread: function FragmentSpread(node) {- var fragmentName = node.name.value;- var fragment = context.getFragment(fragmentName);-- if (!fragment) {- context.reportError(new GraphQLError("Unknown fragment \"".concat(fragmentName, "\"."), node.name));- }- }- };-}--/**- * No unused fragments- *- * A GraphQL document is only valid if all fragment definitions are spread- * within operations, or spread within other fragments spread within operations.- */-function NoUnusedFragmentsRule(context) {- var operationDefs = [];- var fragmentDefs = [];- return {- OperationDefinition: function OperationDefinition(node) {- operationDefs.push(node);- return false;- },- FragmentDefinition: function FragmentDefinition(node) {- fragmentDefs.push(node);- return false;- },- Document: {- leave: function leave() {- var fragmentNameUsed = Object.create(null);-- for (var _i2 = 0; _i2 < operationDefs.length; _i2++) {- var operation = operationDefs[_i2];-- for (var _i4 = 0, _context$getRecursive2 = context.getRecursivelyReferencedFragments(operation); _i4 < _context$getRecursive2.length; _i4++) {- var fragment = _context$getRecursive2[_i4];- fragmentNameUsed[fragment.name.value] = true;- }- }-- for (var _i6 = 0; _i6 < fragmentDefs.length; _i6++) {- var fragmentDef = fragmentDefs[_i6];- var fragName = fragmentDef.name.value;-- if (fragmentNameUsed[fragName] !== true) {- context.reportError(new GraphQLError("Fragment \"".concat(fragName, "\" is never used."), fragmentDef));- }- }- }- }- };-}--/**- * Possible fragment spread- *- * A fragment spread is only valid if the type condition could ever possibly- * be true: if there is a non-empty intersection of the possible parent types,- * and possible types which pass the type condition.- */-function PossibleFragmentSpreadsRule(context) {- return {- InlineFragment: function InlineFragment(node) {- var fragType = context.getType();- var parentType = context.getParentType();-- if (isCompositeType(fragType) && isCompositeType(parentType) && !doTypesOverlap(context.getSchema(), fragType, parentType)) {- var parentTypeStr = inspect(parentType);- var fragTypeStr = inspect(fragType);- context.reportError(new GraphQLError("Fragment cannot be spread here as objects of type \"".concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node));- }- },- FragmentSpread: function FragmentSpread(node) {- var fragName = node.name.value;- var fragType = getFragmentType(context, fragName);- var parentType = context.getParentType();-- if (fragType && parentType && !doTypesOverlap(context.getSchema(), fragType, parentType)) {- var parentTypeStr = inspect(parentType);- var fragTypeStr = inspect(fragType);- context.reportError(new GraphQLError("Fragment \"".concat(fragName, "\" cannot be spread here as objects of type \"").concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node));- }- }- };-}--function getFragmentType(context, name) {- var frag = context.getFragment(name);-- if (frag) {- var type = typeFromAST(context.getSchema(), frag.typeCondition);-- if (isCompositeType(type)) {- return type;- }- }-}--function NoFragmentCyclesRule(context) {- // Tracks already visited fragments to maintain O(N) and to ensure that cycles- // are not redundantly reported.- var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors-- var spreadPath = []; // Position in the spread path-- var spreadPathIndexByName = Object.create(null);- return {- OperationDefinition: function OperationDefinition() {- return false;- },- FragmentDefinition: function FragmentDefinition(node) {- detectCycleRecursive(node);- return false;- }- }; // This does a straight-forward DFS to find cycles.- // It does not terminate when a cycle was found but continues to explore- // the graph to find all possible cycles.-- function detectCycleRecursive(fragment) {- if (visitedFrags[fragment.name.value]) {- return;- }-- var fragmentName = fragment.name.value;- visitedFrags[fragmentName] = true;- var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);-- if (spreadNodes.length === 0) {- return;- }-- spreadPathIndexByName[fragmentName] = spreadPath.length;-- for (var _i2 = 0; _i2 < spreadNodes.length; _i2++) {- var spreadNode = spreadNodes[_i2];- var spreadName = spreadNode.name.value;- var cycleIndex = spreadPathIndexByName[spreadName];- spreadPath.push(spreadNode);-- if (cycleIndex === undefined) {- var spreadFragment = context.getFragment(spreadName);-- if (spreadFragment) {- detectCycleRecursive(spreadFragment);- }- } else {- var cyclePath = spreadPath.slice(cycleIndex);- var viaPath = cyclePath.slice(0, -1).map(function (s) {- return '"' + s.name.value + '"';- }).join(', ');- context.reportError(new GraphQLError("Cannot spread fragment \"".concat(spreadName, "\" within itself") + (viaPath !== '' ? " via ".concat(viaPath, ".") : '.'), cyclePath));- }-- spreadPath.pop();- }-- spreadPathIndexByName[fragmentName] = undefined;- }-}--/**- * Unique variable names- *- * A GraphQL operation is only valid if all its variables are uniquely named.- */-function UniqueVariableNamesRule(context) {- var knownVariableNames = Object.create(null);- return {- OperationDefinition: function OperationDefinition() {- knownVariableNames = Object.create(null);- },- VariableDefinition: function VariableDefinition(node) {- var variableName = node.variable.name.value;-- if (knownVariableNames[variableName]) {- context.reportError(new GraphQLError("There can be only one variable named \"$".concat(variableName, "\"."), [knownVariableNames[variableName], node.variable.name]));- } else {- knownVariableNames[variableName] = node.variable.name;- }- }- };-}--/**- * No undefined variables- *- * A GraphQL operation is only valid if all variables encountered, both directly- * and via fragment spreads, are defined by that operation.- */-function NoUndefinedVariablesRule(context) {- var variableNameDefined = Object.create(null);- return {- OperationDefinition: {- enter: function enter() {- variableNameDefined = Object.create(null);- },- leave: function leave(operation) {- var usages = context.getRecursiveVariableUsages(operation);-- for (var _i2 = 0; _i2 < usages.length; _i2++) {- var _ref2 = usages[_i2];- var node = _ref2.node;- var varName = node.name.value;-- if (variableNameDefined[varName] !== true) {- context.reportError(new GraphQLError(operation.name ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(varName, "\" is not defined."), [node, operation]));- }- }- }- },- VariableDefinition: function VariableDefinition(node) {- variableNameDefined[node.variable.name.value] = true;- }- };-}--/**- * No unused variables- *- * A GraphQL operation is only valid if all variables defined by an operation- * are used, either directly or within a spread fragment.- */-function NoUnusedVariablesRule(context) {- var variableDefs = [];- return {- OperationDefinition: {- enter: function enter() {- variableDefs = [];- },- leave: function leave(operation) {- var variableNameUsed = Object.create(null);- var usages = context.getRecursiveVariableUsages(operation);-- for (var _i2 = 0; _i2 < usages.length; _i2++) {- var _ref2 = usages[_i2];- var node = _ref2.node;- variableNameUsed[node.name.value] = true;- }-- for (var _i4 = 0, _variableDefs2 = variableDefs; _i4 < _variableDefs2.length; _i4++) {- var variableDef = _variableDefs2[_i4];- var variableName = variableDef.variable.name.value;-- if (variableNameUsed[variableName] !== true) {- context.reportError(new GraphQLError(operation.name ? "Variable \"$".concat(variableName, "\" is never used in operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(variableName, "\" is never used."), variableDef));- }- }- }- },- VariableDefinition: function VariableDefinition(def) {- variableDefs.push(def);- }- };-}--/**- * Known directives- *- * A GraphQL document is only valid if all `@directives` are known by the- * schema and legally positioned.- */-function KnownDirectivesRule(context) {- var locationsMap = Object.create(null);- var schema = context.getSchema();- var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;-- for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {- var directive = definedDirectives[_i2];- locationsMap[directive.name] = directive.locations;- }-- var astDefinitions = context.getDocument().definitions;-- for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {- var def = astDefinitions[_i4];-- if (def.kind === Kind.DIRECTIVE_DEFINITION) {- locationsMap[def.name.value] = def.locations.map(function (name) {- return name.value;- });- }- }-- return {- Directive: function Directive(node, _key, _parent, _path, ancestors) {- var name = node.name.value;- var locations = locationsMap[name];-- if (!locations) {- context.reportError(new GraphQLError("Unknown directive \"@".concat(name, "\"."), node));- return;- }-- var candidateLocation = getDirectiveLocationForASTPath(ancestors);-- if (candidateLocation && locations.indexOf(candidateLocation) === -1) {- context.reportError(new GraphQLError("Directive \"@".concat(name, "\" may not be used on ").concat(candidateLocation, "."), node));- }- }- };-}--function getDirectiveLocationForASTPath(ancestors) {- var appliedTo = ancestors[ancestors.length - 1];- !Array.isArray(appliedTo) || invariant(0);-- switch (appliedTo.kind) {- case Kind.OPERATION_DEFINITION:- return getDirectiveLocationForOperation(appliedTo.operation);-- case Kind.FIELD:- return DirectiveLocation.FIELD;-- case Kind.FRAGMENT_SPREAD:- return DirectiveLocation.FRAGMENT_SPREAD;-- case Kind.INLINE_FRAGMENT:- return DirectiveLocation.INLINE_FRAGMENT;-- case Kind.FRAGMENT_DEFINITION:- return DirectiveLocation.FRAGMENT_DEFINITION;-- case Kind.VARIABLE_DEFINITION:- return DirectiveLocation.VARIABLE_DEFINITION;-- case Kind.SCHEMA_DEFINITION:- case Kind.SCHEMA_EXTENSION:- return DirectiveLocation.SCHEMA;-- case Kind.SCALAR_TYPE_DEFINITION:- case Kind.SCALAR_TYPE_EXTENSION:- return DirectiveLocation.SCALAR;-- case Kind.OBJECT_TYPE_DEFINITION:- case Kind.OBJECT_TYPE_EXTENSION:- return DirectiveLocation.OBJECT;-- case Kind.FIELD_DEFINITION:- return DirectiveLocation.FIELD_DEFINITION;-- case Kind.INTERFACE_TYPE_DEFINITION:- case Kind.INTERFACE_TYPE_EXTENSION:- return DirectiveLocation.INTERFACE;-- case Kind.UNION_TYPE_DEFINITION:- case Kind.UNION_TYPE_EXTENSION:- return DirectiveLocation.UNION;-- case Kind.ENUM_TYPE_DEFINITION:- case Kind.ENUM_TYPE_EXTENSION:- return DirectiveLocation.ENUM;-- case Kind.ENUM_VALUE_DEFINITION:- return DirectiveLocation.ENUM_VALUE;-- case Kind.INPUT_OBJECT_TYPE_DEFINITION:- case Kind.INPUT_OBJECT_TYPE_EXTENSION:- return DirectiveLocation.INPUT_OBJECT;-- case Kind.INPUT_VALUE_DEFINITION:- {- var parentNode = ancestors[ancestors.length - 3];- return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? DirectiveLocation.INPUT_FIELD_DEFINITION : DirectiveLocation.ARGUMENT_DEFINITION;- }- }-}--function getDirectiveLocationForOperation(operation) {- switch (operation) {- case 'query':- return DirectiveLocation.QUERY;-- case 'mutation':- return DirectiveLocation.MUTATION;-- case 'subscription':- return DirectiveLocation.SUBSCRIPTION;- } // istanbul ignore next (Not reachable. All possible types have been considered)--- invariant(0, 'Unexpected operation: ' + inspect(operation));-}--/**- * Unique directive names per location- *- * A GraphQL document is only valid if all non-repeatable directives at- * a given location are uniquely named.- */-function UniqueDirectivesPerLocationRule(context) {- var uniqueDirectiveMap = Object.create(null);- var schema = context.getSchema();- var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;-- for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {- var directive = definedDirectives[_i2];- uniqueDirectiveMap[directive.name] = !directive.isRepeatable;- }-- var astDefinitions = context.getDocument().definitions;-- for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {- var def = astDefinitions[_i4];-- if (def.kind === Kind.DIRECTIVE_DEFINITION) {- uniqueDirectiveMap[def.name.value] = !def.repeatable;- }- }-- var schemaDirectives = Object.create(null);- var typeDirectivesMap = Object.create(null);- return {- // Many different AST nodes may contain directives. Rather than listing- // them all, just listen for entering any node, and check to see if it- // defines any directives.- enter: function enter(node) {- if (node.directives == null) {- return;- }-- var seenDirectives;-- if (node.kind === Kind.SCHEMA_DEFINITION || node.kind === Kind.SCHEMA_EXTENSION) {- seenDirectives = schemaDirectives;- } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) {- var typeName = node.name.value;- seenDirectives = typeDirectivesMap[typeName];-- if (seenDirectives === undefined) {- typeDirectivesMap[typeName] = seenDirectives = Object.create(null);- }- } else {- seenDirectives = Object.create(null);- }-- for (var _i6 = 0, _node$directives2 = node.directives; _i6 < _node$directives2.length; _i6++) {- var _directive = _node$directives2[_i6];- var directiveName = _directive.name.value;-- if (uniqueDirectiveMap[directiveName]) {- if (seenDirectives[directiveName]) {- context.reportError(new GraphQLError("The directive \"@".concat(directiveName, "\" can only be used once at this location."), [seenDirectives[directiveName], _directive]));- } else {- seenDirectives[directiveName] = _directive;- }- }- }- }- };-}--function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }--function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }--function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }--/**- * Known argument names- *- * A GraphQL field is only valid if all supplied arguments are defined by- * that field.- */-function KnownArgumentNamesRule(context) {- return _objectSpread(_objectSpread({}, KnownArgumentNamesOnDirectivesRule(context)), {}, {- Argument: function Argument(argNode) {- var argDef = context.getArgument();- var fieldDef = context.getFieldDef();- var parentType = context.getParentType();-- if (!argDef && fieldDef && parentType) {- var argName = argNode.name.value;- var knownArgsNames = fieldDef.args.map(function (arg) {- return arg.name;- });- var suggestions = suggestionList(argName, knownArgsNames);- context.reportError(new GraphQLError("Unknown argument \"".concat(argName, "\" on field \"").concat(parentType.name, ".").concat(fieldDef.name, "\".") + didYouMean(suggestions), argNode));- }- }- });-}-/**- * @internal- */--function KnownArgumentNamesOnDirectivesRule(context) {- var directiveArgs = Object.create(null);- var schema = context.getSchema();- var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;-- for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {- var directive = definedDirectives[_i2];- directiveArgs[directive.name] = directive.args.map(function (arg) {- return arg.name;- });- }-- var astDefinitions = context.getDocument().definitions;-- for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {- var def = astDefinitions[_i4];-- if (def.kind === Kind.DIRECTIVE_DEFINITION) {- var _def$arguments;-- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var argsNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : [];- directiveArgs[def.name.value] = argsNodes.map(function (arg) {- return arg.name.value;- });- }- }-- return {- Directive: function Directive(directiveNode) {- var directiveName = directiveNode.name.value;- var knownArgs = directiveArgs[directiveName];-- if (directiveNode.arguments && knownArgs) {- for (var _i6 = 0, _directiveNode$argume2 = directiveNode.arguments; _i6 < _directiveNode$argume2.length; _i6++) {- var argNode = _directiveNode$argume2[_i6];- var argName = argNode.name.value;-- if (knownArgs.indexOf(argName) === -1) {- var suggestions = suggestionList(argName, knownArgs);- context.reportError(new GraphQLError("Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\".") + didYouMean(suggestions), argNode));- }- }- }-- return false;- }- };-}--/**- * Unique argument names- *- * A GraphQL field or directive is only valid if all supplied arguments are- * uniquely named.- */-function UniqueArgumentNamesRule(context) {- var knownArgNames = Object.create(null);- return {- Field: function Field() {- knownArgNames = Object.create(null);- },- Directive: function Directive() {- knownArgNames = Object.create(null);- },- Argument: function Argument(node) {- var argName = node.name.value;-- if (knownArgNames[argName]) {- context.reportError(new GraphQLError("There can be only one argument named \"".concat(argName, "\"."), [knownArgNames[argName], node.name]));- } else {- knownArgNames[argName] = node.name;- }-- return false;- }- };-}--/**- * Value literals of correct type- *- * A GraphQL document is only valid if all value literals are of the type- * expected at their position.- */-function ValuesOfCorrectTypeRule(context) {- return {- ListValue: function ListValue(node) {- // Note: TypeInfo will traverse into a list's item type, so look to the- // parent input type to check if it is a list.- var type = getNullableType(context.getParentInputType());-- if (!isListType(type)) {- isValidValueNode(context, node);- return false; // Don't traverse further.- }- },- ObjectValue: function ObjectValue(node) {- var type = getNamedType(context.getInputType());-- if (!isInputObjectType(type)) {- isValidValueNode(context, node);- return false; // Don't traverse further.- } // Ensure every required field exists.--- var fieldNodeMap = keyMap(node.fields, function (field) {- return field.name.value;- });-- for (var _i2 = 0, _objectValues2 = objectValues(type.getFields()); _i2 < _objectValues2.length; _i2++) {- var fieldDef = _objectValues2[_i2];- var fieldNode = fieldNodeMap[fieldDef.name];-- if (!fieldNode && isRequiredInputField(fieldDef)) {- var typeStr = inspect(fieldDef.type);- context.reportError(new GraphQLError("Field \"".concat(type.name, ".").concat(fieldDef.name, "\" of required type \"").concat(typeStr, "\" was not provided."), node));- }- }- },- ObjectField: function ObjectField(node) {- var parentType = getNamedType(context.getParentInputType());- var fieldType = context.getInputType();-- if (!fieldType && isInputObjectType(parentType)) {- var suggestions = suggestionList(node.name.value, Object.keys(parentType.getFields()));- context.reportError(new GraphQLError("Field \"".concat(node.name.value, "\" is not defined by type \"").concat(parentType.name, "\".") + didYouMean(suggestions), node));- }- },- NullValue: function NullValue(node) {- var type = context.getInputType();-- if (isNonNullType(type)) {- context.reportError(new GraphQLError("Expected value of type \"".concat(inspect(type), "\", found ").concat(print(node), "."), node));- }- },- EnumValue: function EnumValue(node) {- return isValidValueNode(context, node);- },- IntValue: function IntValue(node) {- return isValidValueNode(context, node);- },- FloatValue: function FloatValue(node) {- return isValidValueNode(context, node);- },- StringValue: function StringValue(node) {- return isValidValueNode(context, node);- },- BooleanValue: function BooleanValue(node) {- return isValidValueNode(context, node);- }- };-}-/**- * Any value literal may be a valid representation of a Scalar, depending on- * that scalar type.- */--function isValidValueNode(context, node) {- // Report any error at the full type expected by the location.- var locationType = context.getInputType();-- if (!locationType) {- return;- }-- var type = getNamedType(locationType);-- if (!isLeafType(type)) {- var typeStr = inspect(locationType);- context.reportError(new GraphQLError("Expected value of type \"".concat(typeStr, "\", found ").concat(print(node), "."), node));- return;- } // Scalars and Enums determine if a literal value is valid via parseLiteral(),- // which may throw or return an invalid value to indicate failure.--- try {- var parseResult = type.parseLiteral(node, undefined- /* variables */- );-- if (parseResult === undefined) {- var _typeStr = inspect(locationType);-- context.reportError(new GraphQLError("Expected value of type \"".concat(_typeStr, "\", found ").concat(print(node), "."), node));- }- } catch (error) {- var _typeStr2 = inspect(locationType);-- if (error instanceof GraphQLError) {- context.reportError(error);- } else {- context.reportError(new GraphQLError("Expected value of type \"".concat(_typeStr2, "\", found ").concat(print(node), "; ") + error.message, node, undefined, undefined, undefined, error));- }- }-}--function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }--function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }--function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }--/**- * Provided required arguments- *- * A field or directive is only valid if all required (non-null without a- * default value) field arguments have been provided.- */-function ProvidedRequiredArgumentsRule(context) {- return _objectSpread$1(_objectSpread$1({}, ProvidedRequiredArgumentsOnDirectivesRule(context)), {}, {- Field: {- // Validate on leave to allow for deeper errors to appear first.- leave: function leave(fieldNode) {- var _fieldNode$arguments;-- var fieldDef = context.getFieldDef();-- if (!fieldDef) {- return false;- } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')--- var argNodes = (_fieldNode$arguments = fieldNode.arguments) !== null && _fieldNode$arguments !== void 0 ? _fieldNode$arguments : [];- var argNodeMap = keyMap(argNodes, function (arg) {- return arg.name.value;- });-- for (var _i2 = 0, _fieldDef$args2 = fieldDef.args; _i2 < _fieldDef$args2.length; _i2++) {- var argDef = _fieldDef$args2[_i2];- var argNode = argNodeMap[argDef.name];-- if (!argNode && isRequiredArgument(argDef)) {- var argTypeStr = inspect(argDef.type);- context.reportError(new GraphQLError("Field \"".concat(fieldDef.name, "\" argument \"").concat(argDef.name, "\" of type \"").concat(argTypeStr, "\" is required, but it was not provided."), fieldNode));- }- }- }- }- });-}-/**- * @internal- */--function ProvidedRequiredArgumentsOnDirectivesRule(context) {- var requiredArgsMap = Object.create(null);- var schema = context.getSchema();- var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;-- for (var _i4 = 0; _i4 < definedDirectives.length; _i4++) {- var directive = definedDirectives[_i4];- requiredArgsMap[directive.name] = keyMap(directive.args.filter(isRequiredArgument), function (arg) {- return arg.name;- });- }-- var astDefinitions = context.getDocument().definitions;-- for (var _i6 = 0; _i6 < astDefinitions.length; _i6++) {- var def = astDefinitions[_i6];-- if (def.kind === Kind.DIRECTIVE_DEFINITION) {- var _def$arguments;-- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var argNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : [];- requiredArgsMap[def.name.value] = keyMap(argNodes.filter(isRequiredArgumentNode), function (arg) {- return arg.name.value;- });- }- }-- return {- Directive: {- // Validate on leave to allow for deeper errors to appear first.- leave: function leave(directiveNode) {- var directiveName = directiveNode.name.value;- var requiredArgs = requiredArgsMap[directiveName];-- if (requiredArgs) {- var _directiveNode$argume;-- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var _argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : [];-- var argNodeMap = keyMap(_argNodes, function (arg) {- return arg.name.value;- });-- for (var _i8 = 0, _Object$keys2 = Object.keys(requiredArgs); _i8 < _Object$keys2.length; _i8++) {- var argName = _Object$keys2[_i8];-- if (!argNodeMap[argName]) {- var argType = requiredArgs[argName].type;- var argTypeStr = isType(argType) ? inspect(argType) : print(argType);- context.reportError(new GraphQLError("Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type \"").concat(argTypeStr, "\" is required, but it was not provided."), directiveNode));- }- }- }- }- }- };-}--function isRequiredArgumentNode(arg) {- return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null;-}--/**- * Variables passed to field arguments conform to type- */-function VariablesInAllowedPositionRule(context) {- var varDefMap = Object.create(null);- return {- OperationDefinition: {- enter: function enter() {- varDefMap = Object.create(null);- },- leave: function leave(operation) {- var usages = context.getRecursiveVariableUsages(operation);-- for (var _i2 = 0; _i2 < usages.length; _i2++) {- var _ref2 = usages[_i2];- var node = _ref2.node;- var type = _ref2.type;- var defaultValue = _ref2.defaultValue;- var varName = node.name.value;- var varDef = varDefMap[varName];-- if (varDef && type) {- // A var type is allowed if it is the same or more strict (e.g. is- // a subtype of) than the expected type. It can be more strict if- // the variable type is non-null when the expected type is nullable.- // If both are list types, the variable item type can be more strict- // than the expected item type (contravariant).- var schema = context.getSchema();- var varType = typeFromAST(schema, varDef.type);-- if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) {- var varTypeStr = inspect(varType);- var typeStr = inspect(type);- context.reportError(new GraphQLError("Variable \"$".concat(varName, "\" of type \"").concat(varTypeStr, "\" used in position expecting type \"").concat(typeStr, "\"."), [varDef, node]));- }- }- }- }- },- VariableDefinition: function VariableDefinition(node) {- varDefMap[node.variable.name.value] = node;- }- };-}-/**- * Returns true if the variable is allowed in the location it was found,- * which includes considering if default values exist for either the variable- * or the location at which it is located.- */--function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) {- if (isNonNullType(locationType) && !isNonNullType(varType)) {- var hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== Kind.NULL;- var hasLocationDefaultValue = locationDefaultValue !== undefined;-- if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) {- return false;- }-- var nullableLocationType = locationType.ofType;- return isTypeSubTypeOf(schema, varType, nullableLocationType);- }-- return isTypeSubTypeOf(schema, varType, locationType);-}--function reasonMessage(reason) {- if (Array.isArray(reason)) {- return reason.map(function (_ref) {- var responseName = _ref[0],- subReason = _ref[1];- return "subfields \"".concat(responseName, "\" conflict because ") + reasonMessage(subReason);- }).join(' and ');- }-- return reason;-}-/**- * Overlapping fields can be merged- *- * A selection set is only valid if all fields (including spreading any- * fragments) either correspond to distinct response names or can be merged- * without ambiguity.- */---function OverlappingFieldsCanBeMergedRule(context) {- // A memoization for when two fragments are compared "between" each other for- // conflicts. Two fragments may be compared many times, so memoizing this can- // dramatically improve the performance of this validator.- var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given- // selection set. Selection sets may be asked for this information multiple- // times, so this improves the performance of this validator.-- var cachedFieldsAndFragmentNames = new Map();- return {- SelectionSet: function SelectionSet(selectionSet) {- var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet);-- for (var _i2 = 0; _i2 < conflicts.length; _i2++) {- var _ref3 = conflicts[_i2];- var _ref2$ = _ref3[0];- var responseName = _ref2$[0];- var reason = _ref2$[1];- var fields1 = _ref3[1];- var fields2 = _ref3[2];- var reasonMsg = reasonMessage(reason);- context.reportError(new GraphQLError("Fields \"".concat(responseName, "\" conflict because ").concat(reasonMsg, ". Use different aliases on the fields to fetch both if this was intentional."), fields1.concat(fields2)));- }- }- };-}--/**- * Algorithm:- *- * Conflicts occur when two fields exist in a query which will produce the same- * response name, but represent differing values, thus creating a conflict.- * The algorithm below finds all conflicts via making a series of comparisons- * between fields. In order to compare as few fields as possible, this makes- * a series of comparisons "within" sets of fields and "between" sets of fields.- *- * Given any selection set, a collection produces both a set of fields by- * also including all inline fragments, as well as a list of fragments- * referenced by fragment spreads.- *- * A) Each selection set represented in the document first compares "within" its- * collected set of fields, finding any conflicts between every pair of- * overlapping fields.- * Note: This is the *only time* that a the fields "within" a set are compared- * to each other. After this only fields "between" sets are compared.- *- * B) Also, if any fragment is referenced in a selection set, then a- * comparison is made "between" the original set of fields and the- * referenced fragment.- *- * C) Also, if multiple fragments are referenced, then comparisons- * are made "between" each referenced fragment.- *- * D) When comparing "between" a set of fields and a referenced fragment, first- * a comparison is made between each field in the original set of fields and- * each field in the the referenced set of fields.- *- * E) Also, if any fragment is referenced in the referenced selection set,- * then a comparison is made "between" the original set of fields and the- * referenced fragment (recursively referring to step D).- *- * F) When comparing "between" two fragments, first a comparison is made between- * each field in the first referenced set of fields and each field in the the- * second referenced set of fields.- *- * G) Also, any fragments referenced by the first must be compared to the- * second, and any fragments referenced by the second must be compared to the- * first (recursively referring to step F).- *- * H) When comparing two fields, if both have selection sets, then a comparison- * is made "between" both selection sets, first comparing the set of fields in- * the first selection set with the set of fields in the second.- *- * I) Also, if any fragment is referenced in either selection set, then a- * comparison is made "between" the other set of fields and the- * referenced fragment.- *- * J) Also, if two fragments are referenced in both selection sets, then a- * comparison is made "between" the two fragments.- *- */-// Find all conflicts found "within" a selection set, including those found-// via spreading in fragments. Called when visiting each SelectionSet in the-// GraphQL Document.-function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) {- var conflicts = [];-- var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet),- fieldMap = _getFieldsAndFragment[0],- fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set.- // Note: this is the *only place* `collectConflictsWithin` is called.--- collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap);-- if (fragmentNames.length !== 0) {- // (B) Then collect conflicts between these fields and those represented by- // each spread fragment name found.- for (var i = 0; i < fragmentNames.length; i++) {- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this- // selection set to collect conflicts between fragments spread together.- // This compares each item in the list of fragment names to every other- // item in that same list (except for itself).-- for (var j = i + 1; j < fragmentNames.length; j++) {- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]);- }- }- }-- return conflicts;-} // Collect all conflicts found between a set of fields and a fragment reference-// including via spreading in any nested fragments.---function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) {- var fragment = context.getFragment(fragmentName);-- if (!fragment) {- return;- }-- var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment),- fieldMap2 = _getReferencedFieldsA[0],- fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself.--- if (fieldMap === fieldMap2) {- return;- } // (D) First collect any conflicts between the provided collection of fields- // and the collection of fields represented by the given fragment.--- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields- // and any fragment names found in the given fragment.-- for (var i = 0; i < fragmentNames2.length; i++) {- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]);- }-} // Collect all conflicts found between two fragments, including via spreading in-// any nested fragments.---function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) {- // No need to compare a fragment to itself.- if (fragmentName1 === fragmentName2) {- return;- } // Memoize so two fragments are not compared for conflicts more than once.--- if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) {- return;- }-- comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);- var fragment1 = context.getFragment(fragmentName1);- var fragment2 = context.getFragment(fragmentName2);-- if (!fragment1 || !fragment2) {- return;- }-- var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1),- fieldMap1 = _getReferencedFieldsA2[0],- fragmentNames1 = _getReferencedFieldsA2[1];-- var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2),- fieldMap2 = _getReferencedFieldsA3[0],- fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields- // (not including any nested fragments).--- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested- // fragments spread in the second fragment.-- for (var j = 0; j < fragmentNames2.length; j++) {- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]);- } // (G) Then collect conflicts between the second fragment and any nested- // fragments spread in the first fragment.--- for (var i = 0; i < fragmentNames1.length; i++) {- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2);- }-} // Find all conflicts found between two selection sets, including those found-// via spreading in fragments. Called when determining if conflicts exist-// between the sub-fields of two overlapping fields.---function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) {- var conflicts = [];-- var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1),- fieldMap1 = _getFieldsAndFragment2[0],- fragmentNames1 = _getFieldsAndFragment2[1];-- var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2),- fieldMap2 = _getFieldsAndFragment3[0],- fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field.--- collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and- // those referenced by each fragment name associated with the second.-- if (fragmentNames2.length !== 0) {- for (var j = 0; j < fragmentNames2.length; j++) {- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]);- }- } // (I) Then collect conflicts between the second collection of fields and- // those referenced by each fragment name associated with the first.--- if (fragmentNames1.length !== 0) {- for (var i = 0; i < fragmentNames1.length; i++) {- collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]);- }- } // (J) Also collect conflicts between any fragment names by the first and- // fragment names by the second. This compares each item in the first set of- // names to each item in the second set of names.--- for (var _i3 = 0; _i3 < fragmentNames1.length; _i3++) {- for (var _j = 0; _j < fragmentNames2.length; _j++) {- collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i3], fragmentNames2[_j]);- }- }-- return conflicts;-} // Collect all Conflicts "within" one collection of fields.---function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) {- // A field map is a keyed collection, where each key represents a response- // name and the value at that key is a list of all fields which provide that- // response name. For every response name, if there are multiple fields, they- // must be compared to find a potential conflict.- for (var _i5 = 0, _objectEntries2 = objectEntries(fieldMap); _i5 < _objectEntries2.length; _i5++) {- var _ref5 = _objectEntries2[_i5];- var responseName = _ref5[0];- var fields = _ref5[1];-- // This compares every field in the list to every other field in this list- // (except to itself). If the list only has one item, nothing needs to- // be compared.- if (fields.length > 1) {- for (var i = 0; i < fields.length; i++) {- for (var j = i + 1; j < fields.length; j++) {- var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive- responseName, fields[i], fields[j]);-- if (conflict) {- conflicts.push(conflict);- }- }- }- }- }-} // Collect all Conflicts between two collections of fields. This is similar to,-// but different from the `collectConflictsWithin` function above. This check-// assumes that `collectConflictsWithin` has already been called on each-// provided collection of fields. This is true because this validator traverses-// each individual selection set.---function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) {- // A field map is a keyed collection, where each key represents a response- // name and the value at that key is a list of all fields which provide that- // response name. For any response name which appears in both provided field- // maps, each field from the first field map must be compared to every field- // in the second field map to find potential conflicts.- for (var _i7 = 0, _Object$keys2 = Object.keys(fieldMap1); _i7 < _Object$keys2.length; _i7++) {- var responseName = _Object$keys2[_i7];- var fields2 = fieldMap2[responseName];-- if (fields2) {- var fields1 = fieldMap1[responseName];-- for (var i = 0; i < fields1.length; i++) {- for (var j = 0; j < fields2.length; j++) {- var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]);-- if (conflict) {- conflicts.push(conflict);- }- }- }- }- }-} // Determines if there is a conflict between two particular fields, including-// comparing their sub-fields.---function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) {- var parentType1 = field1[0],- node1 = field1[1],- def1 = field1[2];- var parentType2 = field2[0],- node2 = field2[1],- def2 = field2[2]; // If it is known that two fields could not possibly apply at the same- // time, due to the parent types, then it is safe to permit them to diverge- // in aliased field or arguments used as they will not present any ambiguity- // by differing.- // It is known that two parent types could never overlap if they are- // different Object types. Interface or Union types might overlap - if not- // in the current state of the schema, then perhaps in some future version,- // thus may not safely diverge.-- var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && isObjectType(parentType1) && isObjectType(parentType2);-- if (!areMutuallyExclusive) {- var _node1$arguments, _node2$arguments;-- // Two aliases must refer to the same field.- var name1 = node1.name.value;- var name2 = node2.name.value;-- if (name1 !== name2) {- return [[responseName, "\"".concat(name1, "\" and \"").concat(name2, "\" are different fields")], [node1], [node2]];- } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')--- var args1 = (_node1$arguments = node1.arguments) !== null && _node1$arguments !== void 0 ? _node1$arguments : []; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')-- var args2 = (_node2$arguments = node2.arguments) !== null && _node2$arguments !== void 0 ? _node2$arguments : []; // Two field calls must have the same arguments.-- if (!sameArguments(args1, args2)) {- return [[responseName, 'they have differing arguments'], [node1], [node2]];- }- } // The return type for each field.--- var type1 = def1 === null || def1 === void 0 ? void 0 : def1.type;- var type2 = def2 === null || def2 === void 0 ? void 0 : def2.type;-- if (type1 && type2 && doTypesConflict(type1, type2)) {- return [[responseName, "they return conflicting types \"".concat(inspect(type1), "\" and \"").concat(inspect(type2), "\"")], [node1], [node2]];- } // Collect and compare sub-fields. Use the same "visited fragment names" list- // for both collections so fields in a fragment reference are never- // compared to themselves.--- var selectionSet1 = node1.selectionSet;- var selectionSet2 = node2.selectionSet;-- if (selectionSet1 && selectionSet2) {- var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, getNamedType(type1), selectionSet1, getNamedType(type2), selectionSet2);- return subfieldConflicts(conflicts, responseName, node1, node2);- }-}--function sameArguments(arguments1, arguments2) {- if (arguments1.length !== arguments2.length) {- return false;- }-- return arguments1.every(function (argument1) {- var argument2 = find(arguments2, function (argument) {- return argument.name.value === argument1.name.value;- });-- if (!argument2) {- return false;- }-- return sameValue(argument1.value, argument2.value);- });-}--function sameValue(value1, value2) {- return print(value1) === print(value2);-} // Two types conflict if both types could not apply to a value simultaneously.-// Composite types are ignored as their individual field types will be compared-// later recursively. However List and Non-Null types must match.---function doTypesConflict(type1, type2) {- if (isListType(type1)) {- return isListType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;- }-- if (isListType(type2)) {- return true;- }-- if (isNonNullType(type1)) {- return isNonNullType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;- }-- if (isNonNullType(type2)) {- return true;- }-- if (isLeafType(type1) || isLeafType(type2)) {- return type1 !== type2;- }-- return false;-} // Given a selection set, return the collection of fields (a mapping of response-// name to field nodes and definitions) as well as a list of fragment names-// referenced via fragment spreads.---function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) {- var cached = cachedFieldsAndFragmentNames.get(selectionSet);-- if (!cached) {- var nodeAndDefs = Object.create(null);- var fragmentNames = Object.create(null);-- _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames);-- cached = [nodeAndDefs, Object.keys(fragmentNames)];- cachedFieldsAndFragmentNames.set(selectionSet, cached);- }-- return cached;-} // Given a reference to a fragment, return the represented collection of fields-// as well as a list of nested fragment names referenced via fragment spreads.---function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) {- // Short-circuit building a type from the node if possible.- var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);-- if (cached) {- return cached;- }-- var fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition);- return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet);-}--function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) {- for (var _i9 = 0, _selectionSet$selecti2 = selectionSet.selections; _i9 < _selectionSet$selecti2.length; _i9++) {- var selection = _selectionSet$selecti2[_i9];-- switch (selection.kind) {- case Kind.FIELD:- {- var fieldName = selection.name.value;- var fieldDef = void 0;-- if (isObjectType(parentType) || isInterfaceType(parentType)) {- fieldDef = parentType.getFields()[fieldName];- }-- var responseName = selection.alias ? selection.alias.value : fieldName;-- if (!nodeAndDefs[responseName]) {- nodeAndDefs[responseName] = [];- }-- nodeAndDefs[responseName].push([parentType, selection, fieldDef]);- break;- }-- case Kind.FRAGMENT_SPREAD:- fragmentNames[selection.name.value] = true;- break;-- case Kind.INLINE_FRAGMENT:- {- var typeCondition = selection.typeCondition;- var inlineFragmentType = typeCondition ? typeFromAST(context.getSchema(), typeCondition) : parentType;-- _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames);-- break;- }- }- }-} // Given a series of Conflicts which occurred between two sub-fields, generate-// a single Conflict.---function subfieldConflicts(conflicts, responseName, node1, node2) {- if (conflicts.length > 0) {- return [[responseName, conflicts.map(function (_ref6) {- var reason = _ref6[0];- return reason;- })], conflicts.reduce(function (allFields, _ref7) {- var fields1 = _ref7[1];- return allFields.concat(fields1);- }, [node1]), conflicts.reduce(function (allFields, _ref8) {- var fields2 = _ref8[2];- return allFields.concat(fields2);- }, [node2])];- }-}-/**- * A way to keep track of pairs of things when the ordering of the pair does- * not matter. We do this by maintaining a sort of double adjacency sets.- */---var PairSet = /*#__PURE__*/function () {- function PairSet() {- this._data = Object.create(null);- }-- var _proto = PairSet.prototype;-- _proto.has = function has(a, b, areMutuallyExclusive) {- var first = this._data[a];- var result = first && first[b];-- if (result === undefined) {- return false;- } // areMutuallyExclusive being false is a superset of being true,- // hence if we want to know if this PairSet "has" these two with no- // exclusivity, we have to ensure it was added as such.--- if (areMutuallyExclusive === false) {- return result === false;- }-- return true;- };-- _proto.add = function add(a, b, areMutuallyExclusive) {- _pairSetAdd(this._data, a, b, areMutuallyExclusive);-- _pairSetAdd(this._data, b, a, areMutuallyExclusive);- };-- return PairSet;-}();--function _pairSetAdd(data, a, b, areMutuallyExclusive) {- var map = data[a];-- if (!map) {- map = Object.create(null);- data[a] = map;- }-- map[b] = areMutuallyExclusive;-}--/**- * Unique input field names- *- * A GraphQL input object value is only valid if all supplied fields are- * uniquely named.- */-function UniqueInputFieldNamesRule(context) {- var knownNameStack = [];- var knownNames = Object.create(null);- return {- ObjectValue: {- enter: function enter() {- knownNameStack.push(knownNames);- knownNames = Object.create(null);- },- leave: function leave() {- knownNames = knownNameStack.pop();- }- },- ObjectField: function ObjectField(node) {- var fieldName = node.name.value;-- if (knownNames[fieldName]) {- context.reportError(new GraphQLError("There can be only one input field named \"".concat(fieldName, "\"."), [knownNames[fieldName], node.name]));- } else {- knownNames[fieldName] = node.name;- }- }- };-}--/**- * Lone Schema definition- *- * A GraphQL document is only valid if it contains only one schema definition.- */-function LoneSchemaDefinitionRule(context) {- var _ref, _ref2, _oldSchema$astNode;-- var oldSchema = context.getSchema();- var alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType();- var schemaDefinitionsCount = 0;- return {- SchemaDefinition: function SchemaDefinition(node) {- if (alreadyDefined) {- context.reportError(new GraphQLError('Cannot define a new schema within a schema extension.', node));- return;- }-- if (schemaDefinitionsCount > 0) {- context.reportError(new GraphQLError('Must provide only one schema definition.', node));- }-- ++schemaDefinitionsCount;- }- };-}--/**- * Unique operation types- *- * A GraphQL document is only valid if it has only one type per operation.- */-function UniqueOperationTypesRule(context) {- var schema = context.getSchema();- var definedOperationTypes = Object.create(null);- var existingOperationTypes = schema ? {- query: schema.getQueryType(),- mutation: schema.getMutationType(),- subscription: schema.getSubscriptionType()- } : {};- return {- SchemaDefinition: checkOperationTypes,- SchemaExtension: checkOperationTypes- };-- function checkOperationTypes(node) {- var _node$operationTypes;-- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : [];-- for (var _i2 = 0; _i2 < operationTypesNodes.length; _i2++) {- var operationType = operationTypesNodes[_i2];- var operation = operationType.operation;- var alreadyDefinedOperationType = definedOperationTypes[operation];-- if (existingOperationTypes[operation]) {- context.reportError(new GraphQLError("Type for ".concat(operation, " already defined in the schema. It cannot be redefined."), operationType));- } else if (alreadyDefinedOperationType) {- context.reportError(new GraphQLError("There can be only one ".concat(operation, " type in schema."), [alreadyDefinedOperationType, operationType]));- } else {- definedOperationTypes[operation] = operationType;- }- }-- return false;- }-}--/**- * Unique type names- *- * A GraphQL document is only valid if all defined types have unique names.- */-function UniqueTypeNamesRule(context) {- var knownTypeNames = Object.create(null);- var schema = context.getSchema();- return {- ScalarTypeDefinition: checkTypeName,- ObjectTypeDefinition: checkTypeName,- InterfaceTypeDefinition: checkTypeName,- UnionTypeDefinition: checkTypeName,- EnumTypeDefinition: checkTypeName,- InputObjectTypeDefinition: checkTypeName- };-- function checkTypeName(node) {- var typeName = node.name.value;-- if (schema === null || schema === void 0 ? void 0 : schema.getType(typeName)) {- context.reportError(new GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also be defined in this type definition."), node.name));- return;- }-- if (knownTypeNames[typeName]) {- context.reportError(new GraphQLError("There can be only one type named \"".concat(typeName, "\"."), [knownTypeNames[typeName], node.name]));- } else {- knownTypeNames[typeName] = node.name;- }-- return false;- }-}--/**- * Unique enum value names- *- * A GraphQL enum type is only valid if all its values are uniquely named.- */-function UniqueEnumValueNamesRule(context) {- var schema = context.getSchema();- var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);- var knownValueNames = Object.create(null);- return {- EnumTypeDefinition: checkValueUniqueness,- EnumTypeExtension: checkValueUniqueness- };-- function checkValueUniqueness(node) {- var _node$values;-- var typeName = node.name.value;-- if (!knownValueNames[typeName]) {- knownValueNames[typeName] = Object.create(null);- } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')--- var valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : [];- var valueNames = knownValueNames[typeName];-- for (var _i2 = 0; _i2 < valueNodes.length; _i2++) {- var valueDef = valueNodes[_i2];- var valueName = valueDef.name.value;- var existingType = existingTypeMap[typeName];-- if (isEnumType(existingType) && existingType.getValue(valueName)) {- context.reportError(new GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. It cannot also be defined in this type extension."), valueDef.name));- } else if (valueNames[valueName]) {- context.reportError(new GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once."), [valueNames[valueName], valueDef.name]));- } else {- valueNames[valueName] = valueDef.name;- }- }-- return false;- }-}--/**- * Unique field definition names- *- * A GraphQL complex type is only valid if all its fields are uniquely named.- */-function UniqueFieldDefinitionNamesRule(context) {- var schema = context.getSchema();- var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);- var knownFieldNames = Object.create(null);- return {- InputObjectTypeDefinition: checkFieldUniqueness,- InputObjectTypeExtension: checkFieldUniqueness,- InterfaceTypeDefinition: checkFieldUniqueness,- InterfaceTypeExtension: checkFieldUniqueness,- ObjectTypeDefinition: checkFieldUniqueness,- ObjectTypeExtension: checkFieldUniqueness- };-- function checkFieldUniqueness(node) {- var _node$fields;-- var typeName = node.name.value;-- if (!knownFieldNames[typeName]) {- knownFieldNames[typeName] = Object.create(null);- } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')--- var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];- var fieldNames = knownFieldNames[typeName];-- for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) {- var fieldDef = fieldNodes[_i2];- var fieldName = fieldDef.name.value;-- if (hasField(existingTypeMap[typeName], fieldName)) {- context.reportError(new GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. It cannot also be defined in this type extension."), fieldDef.name));- } else if (fieldNames[fieldName]) {- context.reportError(new GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once."), [fieldNames[fieldName], fieldDef.name]));- } else {- fieldNames[fieldName] = fieldDef.name;- }- }-- return false;- }-}--function hasField(type, fieldName) {- if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {- return type.getFields()[fieldName];- }-- return false;-}--/**- * Unique directive names- *- * A GraphQL document is only valid if all defined directives have unique names.- */-function UniqueDirectiveNamesRule(context) {- var knownDirectiveNames = Object.create(null);- var schema = context.getSchema();- return {- DirectiveDefinition: function DirectiveDefinition(node) {- var directiveName = node.name.value;-- if (schema === null || schema === void 0 ? void 0 : schema.getDirective(directiveName)) {- context.reportError(new GraphQLError("Directive \"@".concat(directiveName, "\" already exists in the schema. It cannot be redefined."), node.name));- return;- }-- if (knownDirectiveNames[directiveName]) {- context.reportError(new GraphQLError("There can be only one directive named \"@".concat(directiveName, "\"."), [knownDirectiveNames[directiveName], node.name]));- } else {- knownDirectiveNames[directiveName] = node.name;- }-- return false;- }- };-}--var _defKindToExtKind;--function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }--/**- * Possible type extension- *- * A type extension is only valid if the type is defined and has the same kind.- */-function PossibleTypeExtensionsRule(context) {- var schema = context.getSchema();- var definedTypes = Object.create(null);-- for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {- var def = _context$getDocument$2[_i2];-- if (isTypeDefinitionNode(def)) {- definedTypes[def.name.value] = def;- }- }-- return {- ScalarTypeExtension: checkExtension,- ObjectTypeExtension: checkExtension,- InterfaceTypeExtension: checkExtension,- UnionTypeExtension: checkExtension,- EnumTypeExtension: checkExtension,- InputObjectTypeExtension: checkExtension- };-- function checkExtension(node) {- var typeName = node.name.value;- var defNode = definedTypes[typeName];- var existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName);- var expectedKind;-- if (defNode) {- expectedKind = defKindToExtKind[defNode.kind];- } else if (existingType) {- expectedKind = typeToExtKind(existingType);- }-- if (expectedKind) {- if (expectedKind !== node.kind) {- var kindStr = extensionKindToTypeName(node.kind);- context.reportError(new GraphQLError("Cannot extend non-".concat(kindStr, " type \"").concat(typeName, "\"."), defNode ? [defNode, node] : node));- }- } else {- var allTypeNames = Object.keys(definedTypes);-- if (schema) {- allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap()));- }-- var suggestedTypes = suggestionList(typeName, allTypeNames);- context.reportError(new GraphQLError("Cannot extend type \"".concat(typeName, "\" because it is not defined.") + didYouMean(suggestedTypes), node.name));- }- }-}-var defKindToExtKind = (_defKindToExtKind = {}, _defineProperty$2(_defKindToExtKind, Kind.SCALAR_TYPE_DEFINITION, Kind.SCALAR_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.OBJECT_TYPE_DEFINITION, Kind.OBJECT_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.INTERFACE_TYPE_DEFINITION, Kind.INTERFACE_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.UNION_TYPE_DEFINITION, Kind.UNION_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.ENUM_TYPE_DEFINITION, Kind.ENUM_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.INPUT_OBJECT_TYPE_DEFINITION, Kind.INPUT_OBJECT_TYPE_EXTENSION), _defKindToExtKind);--function typeToExtKind(type) {- if (isScalarType(type)) {- return Kind.SCALAR_TYPE_EXTENSION;- }-- if (isObjectType(type)) {- return Kind.OBJECT_TYPE_EXTENSION;- }-- if (isInterfaceType(type)) {- return Kind.INTERFACE_TYPE_EXTENSION;- }-- if (isUnionType(type)) {- return Kind.UNION_TYPE_EXTENSION;- }-- if (isEnumType(type)) {- return Kind.ENUM_TYPE_EXTENSION;- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isInputObjectType(type)) {- return Kind.INPUT_OBJECT_TYPE_EXTENSION;- } // istanbul ignore next (Not reachable. All possible types have been considered)--- invariant(0, 'Unexpected type: ' + inspect(type));-}--function extensionKindToTypeName(kind) {- switch (kind) {- case Kind.SCALAR_TYPE_EXTENSION:- return 'scalar';-- case Kind.OBJECT_TYPE_EXTENSION:- return 'object';-- case Kind.INTERFACE_TYPE_EXTENSION:- return 'interface';-- case Kind.UNION_TYPE_EXTENSION:- return 'union';-- case Kind.ENUM_TYPE_EXTENSION:- return 'enum';-- case Kind.INPUT_OBJECT_TYPE_EXTENSION:- return 'input object';- } // istanbul ignore next (Not reachable. All possible types have been considered)--- invariant(0, 'Unexpected kind: ' + inspect(kind));-}--// Spec Section: "Executable Definitions"-/**- * This set includes all validation rules defined by the GraphQL spec.- *- * The order of the rules in this list has been adjusted to lead to the- * most clear output when encountering multiple validation errors.- */--var specifiedRules = Object.freeze([ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule, SingleFieldSubscriptionsRule, KnownTypeNamesRule, FragmentsOnCompositeTypesRule, VariablesAreInputTypesRule, ScalarLeafsRule, FieldsOnCorrectTypeRule, UniqueFragmentNamesRule, KnownFragmentNamesRule, NoUnusedFragmentsRule, PossibleFragmentSpreadsRule, NoFragmentCyclesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule, NoUnusedVariablesRule, KnownDirectivesRule, UniqueDirectivesPerLocationRule, KnownArgumentNamesRule, UniqueArgumentNamesRule, ValuesOfCorrectTypeRule, ProvidedRequiredArgumentsRule, VariablesInAllowedPositionRule, OverlappingFieldsCanBeMergedRule, UniqueInputFieldNamesRule]);-/**- * @internal- */--var specifiedSDLRules = Object.freeze([LoneSchemaDefinitionRule, UniqueOperationTypesRule, UniqueTypeNamesRule, UniqueEnumValueNamesRule, UniqueFieldDefinitionNamesRule, UniqueDirectiveNamesRule, KnownTypeNamesRule, KnownDirectivesRule, UniqueDirectivesPerLocationRule, PossibleTypeExtensionsRule, KnownArgumentNamesOnDirectivesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule, ProvidedRequiredArgumentsOnDirectivesRule]);--function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }--/**- * An instance of this class is passed as the "this" context to all validators,- * allowing access to commonly useful contextual information from within a- * validation rule.- */-var ASTValidationContext = /*#__PURE__*/function () {- function ASTValidationContext(ast, onError) {- this._ast = ast;- this._fragments = undefined;- this._fragmentSpreads = new Map();- this._recursivelyReferencedFragments = new Map();- this._onError = onError;- }-- var _proto = ASTValidationContext.prototype;-- _proto.reportError = function reportError(error) {- this._onError(error);- };-- _proto.getDocument = function getDocument() {- return this._ast;- };-- _proto.getFragment = function getFragment(name) {- var fragments = this._fragments;-- if (!fragments) {- this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) {- if (statement.kind === Kind.FRAGMENT_DEFINITION) {- frags[statement.name.value] = statement;- }-- return frags;- }, Object.create(null));- }-- return fragments[name];- };-- _proto.getFragmentSpreads = function getFragmentSpreads(node) {- var spreads = this._fragmentSpreads.get(node);-- if (!spreads) {- spreads = [];- var setsToVisit = [node];-- while (setsToVisit.length !== 0) {- var set = setsToVisit.pop();-- for (var _i2 = 0, _set$selections2 = set.selections; _i2 < _set$selections2.length; _i2++) {- var selection = _set$selections2[_i2];-- if (selection.kind === Kind.FRAGMENT_SPREAD) {- spreads.push(selection);- } else if (selection.selectionSet) {- setsToVisit.push(selection.selectionSet);- }- }- }-- this._fragmentSpreads.set(node, spreads);- }-- return spreads;- };-- _proto.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) {- var fragments = this._recursivelyReferencedFragments.get(operation);-- if (!fragments) {- fragments = [];- var collectedNames = Object.create(null);- var nodesToVisit = [operation.selectionSet];-- while (nodesToVisit.length !== 0) {- var node = nodesToVisit.pop();-- for (var _i4 = 0, _this$getFragmentSpre2 = this.getFragmentSpreads(node); _i4 < _this$getFragmentSpre2.length; _i4++) {- var spread = _this$getFragmentSpre2[_i4];- var fragName = spread.name.value;-- if (collectedNames[fragName] !== true) {- collectedNames[fragName] = true;- var fragment = this.getFragment(fragName);-- if (fragment) {- fragments.push(fragment);- nodesToVisit.push(fragment.selectionSet);- }- }- }- }-- this._recursivelyReferencedFragments.set(operation, fragments);- }-- return fragments;- };-- return ASTValidationContext;-}();-var SDLValidationContext = /*#__PURE__*/function (_ASTValidationContext) {- _inheritsLoose(SDLValidationContext, _ASTValidationContext);-- function SDLValidationContext(ast, schema, onError) {- var _this;-- _this = _ASTValidationContext.call(this, ast, onError) || this;- _this._schema = schema;- return _this;- }-- var _proto2 = SDLValidationContext.prototype;-- _proto2.getSchema = function getSchema() {- return this._schema;- };-- return SDLValidationContext;-}(ASTValidationContext);-var ValidationContext = /*#__PURE__*/function (_ASTValidationContext2) {- _inheritsLoose(ValidationContext, _ASTValidationContext2);-- function ValidationContext(schema, ast, typeInfo, onError) {- var _this2;-- _this2 = _ASTValidationContext2.call(this, ast, onError) || this;- _this2._schema = schema;- _this2._typeInfo = typeInfo;- _this2._variableUsages = new Map();- _this2._recursiveVariableUsages = new Map();- return _this2;- }-- var _proto3 = ValidationContext.prototype;-- _proto3.getSchema = function getSchema() {- return this._schema;- };-- _proto3.getVariableUsages = function getVariableUsages(node) {- var usages = this._variableUsages.get(node);-- if (!usages) {- var newUsages = [];- var typeInfo = new TypeInfo(this._schema);- visit(node, visitWithTypeInfo(typeInfo, {- VariableDefinition: function VariableDefinition() {- return false;- },- Variable: function Variable(variable) {- newUsages.push({- node: variable,- type: typeInfo.getInputType(),- defaultValue: typeInfo.getDefaultValue()- });- }- }));- usages = newUsages;-- this._variableUsages.set(node, usages);- }-- return usages;- };-- _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) {- var usages = this._recursiveVariableUsages.get(operation);-- if (!usages) {- usages = this.getVariableUsages(operation);-- for (var _i6 = 0, _this$getRecursivelyR2 = this.getRecursivelyReferencedFragments(operation); _i6 < _this$getRecursivelyR2.length; _i6++) {- var frag = _this$getRecursivelyR2[_i6];- usages = usages.concat(this.getVariableUsages(frag));- }-- this._recursiveVariableUsages.set(operation, usages);- }-- return usages;- };-- _proto3.getType = function getType() {- return this._typeInfo.getType();- };-- _proto3.getParentType = function getParentType() {- return this._typeInfo.getParentType();- };-- _proto3.getInputType = function getInputType() {- return this._typeInfo.getInputType();- };-- _proto3.getParentInputType = function getParentInputType() {- return this._typeInfo.getParentInputType();- };-- _proto3.getFieldDef = function getFieldDef() {- return this._typeInfo.getFieldDef();- };-- _proto3.getDirective = function getDirective() {- return this._typeInfo.getDirective();- };-- _proto3.getArgument = function getArgument() {- return this._typeInfo.getArgument();- };-- _proto3.getEnumValue = function getEnumValue() {- return this._typeInfo.getEnumValue();- };-- return ValidationContext;-}(ASTValidationContext);--/**- * Implements the "Validation" section of the spec.- *- * Validation runs synchronously, returning an array of encountered errors, or- * an empty array if no errors were encountered and the document is valid.- *- * A list of specific validation rules may be provided. If not provided, the- * default list of rules defined by the GraphQL specification will be used.- *- * Each validation rules is a function which returns a visitor- * (see the language/visitor API). Visitor methods are expected to return- * GraphQLErrors, or Arrays of GraphQLErrors when invalid.- *- * Optionally a custom TypeInfo instance may be provided. If not provided, one- * will be created from the provided schema.- */--function validate(schema, documentAST) {- var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedRules;- var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new TypeInfo(schema);- var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {- maxErrors: undefined- };- documentAST || devAssert(0, 'Must provide document.'); // If the schema used for validation is invalid, throw an error.-- assertValidSchema(schema);- var abortObj = Object.freeze({});- var errors = [];- var context = new ValidationContext(schema, documentAST, typeInfo, function (error) {- if (options.maxErrors != null && errors.length >= options.maxErrors) {- errors.push(new GraphQLError('Too many validation errors, error limit reached. Validation aborted.'));- throw abortObj;- }-- errors.push(error);- }); // This uses a specialized visitor which runs multiple visitors in parallel,- // while maintaining the visitor skip and break API.-- var visitor = visitInParallel(rules.map(function (rule) {- return rule(context);- })); // Visit the whole document with each instance of all provided rules.-- try {- visit(documentAST, visitWithTypeInfo(typeInfo, visitor));- } catch (e) {- if (e !== abortObj) {- throw e;- }- }-- return errors;-}-/**- * @internal- */--function validateSDL(documentAST, schemaToExtend) {- var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedSDLRules;- var errors = [];- var context = new SDLValidationContext(documentAST, schemaToExtend, function (error) {- errors.push(error);- });- var visitors = rules.map(function (rule) {- return rule(context);- });- visit(documentAST, visitInParallel(visitors));- return errors;-}-/**- * Utility function which asserts a SDL document is valid by throwing an error- * if it is invalid.- *- * @internal- */--function assertValidSDL(documentAST) {- var errors = validateSDL(documentAST);-- if (errors.length !== 0) {- throw new Error(errors.map(function (error) {- return error.message;- }).join('\n\n'));- }-}-/**- * Utility function which asserts a SDL document is valid by throwing an error- * if it is invalid.- *- * @internal- */--function assertValidSDLExtension(documentAST, schema) {- var errors = validateSDL(documentAST, schema);-- if (errors.length !== 0) {- throw new Error(errors.map(function (error) {- return error.message;- }).join('\n\n'));- }-}--/**- * Memoizes the provided three-argument function.- */-function memoize3(fn) {- var cache0;-- function memoized(a1, a2, a3) {- if (!cache0) {- cache0 = new WeakMap();- }-- var cache1 = cache0.get(a1);- var cache2;-- if (cache1) {- cache2 = cache1.get(a2);-- if (cache2) {- var cachedValue = cache2.get(a3);-- if (cachedValue !== undefined) {- return cachedValue;- }- }- } else {- cache1 = new WeakMap();- cache0.set(a1, cache1);- }-- if (!cache2) {- cache2 = new WeakMap();- cache1.set(a2, cache2);- }-- var newValue = fn(a1, a2, a3);- cache2.set(a3, newValue);- return newValue;- }-- return memoized;-}--/**- * Similar to Array.prototype.reduce(), however the reducing callback may return- * a Promise, in which case reduction will continue after each promise resolves.- *- * If the callback does not return a Promise, then this function will also not- * return a Promise.- */--function promiseReduce(values, callback, initialValue) {- return values.reduce(function (previous, value) {- return isPromise(previous) ? previous.then(function (resolved) {- return callback(resolved, value);- }) : callback(previous, value);- }, initialValue);-}--/**- * This function transforms a JS object `ObjMap<Promise<T>>` into- * a `Promise<ObjMap<T>>`- *- * This is akin to bluebird's `Promise.props`, but implemented only using- * `Promise.all` so it will work with any implementation of ES6 promises.- */-function promiseForObject(object) {- var keys = Object.keys(object);- var valuesAndPromises = keys.map(function (name) {- return object[name];- });- return Promise.all(valuesAndPromises).then(function (values) {- return values.reduce(function (resolvedObject, value, i) {- resolvedObject[keys[i]] = value;- return resolvedObject;- }, Object.create(null));- });-}--/**- * Given a Path and a key, return a new Path containing the new key.- */-function addPath(prev, key, typename) {- return {- prev: prev,- key: key,- typename: typename- };-}-/**- * Given a Path, return an Array of the path keys.- */--function pathToArray(path) {- var flattened = [];- var curr = path;-- while (curr) {- flattened.push(curr.key);- curr = curr.prev;- }-- return flattened.reverse();-}--/**- * Extracts the root type of the operation from the schema.- */-function getOperationRootType(schema, operation) {- if (operation.operation === 'query') {- var queryType = schema.getQueryType();-- if (!queryType) {- throw new GraphQLError('Schema does not define the required query root type.', operation);- }-- return queryType;- }-- if (operation.operation === 'mutation') {- var mutationType = schema.getMutationType();-- if (!mutationType) {- throw new GraphQLError('Schema is not configured for mutations.', operation);- }-- return mutationType;- }-- if (operation.operation === 'subscription') {- var subscriptionType = schema.getSubscriptionType();-- if (!subscriptionType) {- throw new GraphQLError('Schema is not configured for subscriptions.', operation);- }-- return subscriptionType;- }-- throw new GraphQLError('Can only have query, mutation and subscription operations.', operation);-}--/**- * Build a string describing the path.- */-function printPathArray(path) {- return path.map(function (key) {- return typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key;- }).join('');-}--/**- * Produces a JavaScript value given a GraphQL Value AST.- *- * A GraphQL type must be provided, which will be used to interpret different- * GraphQL Value literals.- *- * Returns `undefined` when the value could not be validly coerced according to- * the provided type.- *- * | GraphQL Value | JSON Value |- * | -------------------- | ------------- |- * | Input Object | Object |- * | List | Array |- * | Boolean | Boolean |- * | String | String |- * | Int / Float | Number |- * | Enum Value | Mixed |- * | NullValue | null |- *- */--function valueFromAST(valueNode, type, variables) {- if (!valueNode) {- // When there is no node, then there is also no value.- // Importantly, this is different from returning the value null.- return;- }-- if (valueNode.kind === Kind.VARIABLE) {- var variableName = valueNode.name.value;-- if (variables == null || variables[variableName] === undefined) {- // No valid return value.- return;- }-- var variableValue = variables[variableName];-- if (variableValue === null && isNonNullType(type)) {- return; // Invalid: intentionally return no value.- } // Note: This does no further checking that this variable is correct.- // This assumes that this query has been validated and the variable- // usage here is of the correct type.--- return variableValue;- }-- if (isNonNullType(type)) {- if (valueNode.kind === Kind.NULL) {- return; // Invalid: intentionally return no value.- }-- return valueFromAST(valueNode, type.ofType, variables);- }-- if (valueNode.kind === Kind.NULL) {- // This is explicitly returning the value null.- return null;- }-- if (isListType(type)) {- var itemType = type.ofType;-- if (valueNode.kind === Kind.LIST) {- var coercedValues = [];-- for (var _i2 = 0, _valueNode$values2 = valueNode.values; _i2 < _valueNode$values2.length; _i2++) {- var itemNode = _valueNode$values2[_i2];-- if (isMissingVariable(itemNode, variables)) {- // If an array contains a missing variable, it is either coerced to- // null or if the item type is non-null, it considered invalid.- if (isNonNullType(itemType)) {- return; // Invalid: intentionally return no value.- }-- coercedValues.push(null);- } else {- var itemValue = valueFromAST(itemNode, itemType, variables);-- if (itemValue === undefined) {- return; // Invalid: intentionally return no value.- }-- coercedValues.push(itemValue);- }- }-- return coercedValues;- }-- var coercedValue = valueFromAST(valueNode, itemType, variables);-- if (coercedValue === undefined) {- return; // Invalid: intentionally return no value.- }-- return [coercedValue];- }-- if (isInputObjectType(type)) {- if (valueNode.kind !== Kind.OBJECT) {- return; // Invalid: intentionally return no value.- }-- var coercedObj = Object.create(null);- var fieldNodes = keyMap(valueNode.fields, function (field) {- return field.name.value;- });-- for (var _i4 = 0, _objectValues2 = objectValues(type.getFields()); _i4 < _objectValues2.length; _i4++) {- var field = _objectValues2[_i4];- var fieldNode = fieldNodes[field.name];-- if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {- if (field.defaultValue !== undefined) {- coercedObj[field.name] = field.defaultValue;- } else if (isNonNullType(field.type)) {- return; // Invalid: intentionally return no value.- }-- continue;- }-- var fieldValue = valueFromAST(fieldNode.value, field.type, variables);-- if (fieldValue === undefined) {- return; // Invalid: intentionally return no value.- }-- coercedObj[field.name] = fieldValue;- }-- return coercedObj;- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isLeafType(type)) {- // Scalars and Enums fulfill parsing a literal value via parseLiteral().- // Invalid values represent a failure to parse correctly, in which case- // no value is returned.- var result;-- try {- result = type.parseLiteral(valueNode, variables);- } catch (_error) {- return; // Invalid: intentionally return no value.- }-- if (result === undefined) {- return; // Invalid: intentionally return no value.- }-- return result;- } // istanbul ignore next (Not reachable. All possible input types have been considered)--- invariant(0, 'Unexpected input type: ' + inspect(type));-} // Returns true if the provided valueNode is a variable which is not defined-// in the set of variables.--function isMissingVariable(valueNode, variables) {- return valueNode.kind === Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === undefined);-}--/**- * Coerces a JavaScript value given a GraphQL Input Type.- */-function coerceInputValue(inputValue, type) {- var onError = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultOnError;- return coerceInputValueImpl(inputValue, type, onError);-}--function defaultOnError(path, invalidValue, error) {- var errorPrefix = 'Invalid value ' + inspect(invalidValue);-- if (path.length > 0) {- errorPrefix += " at \"value".concat(printPathArray(path), "\"");- }-- error.message = errorPrefix + ': ' + error.message;- throw error;-}--function coerceInputValueImpl(inputValue, type, onError, path) {- if (isNonNullType(type)) {- if (inputValue != null) {- return coerceInputValueImpl(inputValue, type.ofType, onError, path);- }-- onError(pathToArray(path), inputValue, new GraphQLError("Expected non-nullable type \"".concat(inspect(type), "\" not to be null.")));- return;- }-- if (inputValue == null) {- // Explicitly return the value null.- return null;- }-- if (isListType(type)) {- var itemType = type.ofType;-- if (isCollection(inputValue)) {- return arrayFrom(inputValue, function (itemValue, index) {- var itemPath = addPath(path, index, undefined);- return coerceInputValueImpl(itemValue, itemType, onError, itemPath);- });- } // Lists accept a non-list value as a list of one.--- return [coerceInputValueImpl(inputValue, itemType, onError, path)];- }-- if (isInputObjectType(type)) {- if (!isObjectLike(inputValue)) {- onError(pathToArray(path), inputValue, new GraphQLError("Expected type \"".concat(type.name, "\" to be an object.")));- return;- }-- var coercedValue = {};- var fieldDefs = type.getFields();-- for (var _i2 = 0, _objectValues2 = objectValues(fieldDefs); _i2 < _objectValues2.length; _i2++) {- var field = _objectValues2[_i2];- var fieldValue = inputValue[field.name];-- if (fieldValue === undefined) {- if (field.defaultValue !== undefined) {- coercedValue[field.name] = field.defaultValue;- } else if (isNonNullType(field.type)) {- var typeStr = inspect(field.type);- onError(pathToArray(path), inputValue, new GraphQLError("Field \"".concat(field.name, "\" of required type \"").concat(typeStr, "\" was not provided.")));- }-- continue;- }-- coercedValue[field.name] = coerceInputValueImpl(fieldValue, field.type, onError, addPath(path, field.name, type.name));- } // Ensure every provided field is defined.--- for (var _i4 = 0, _Object$keys2 = Object.keys(inputValue); _i4 < _Object$keys2.length; _i4++) {- var fieldName = _Object$keys2[_i4];-- if (!fieldDefs[fieldName]) {- var suggestions = suggestionList(fieldName, Object.keys(type.getFields()));- onError(pathToArray(path), inputValue, new GraphQLError("Field \"".concat(fieldName, "\" is not defined by type \"").concat(type.name, "\".") + didYouMean(suggestions)));- }- }-- return coercedValue;- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isLeafType(type)) {- var parseResult; // Scalars and Enums determine if a input value is valid via parseValue(),- // which can throw to indicate failure. If it throws, maintain a reference- // to the original error.-- try {- parseResult = type.parseValue(inputValue);- } catch (error) {- if (error instanceof GraphQLError) {- onError(pathToArray(path), inputValue, error);- } else {- onError(pathToArray(path), inputValue, new GraphQLError("Expected type \"".concat(type.name, "\". ") + error.message, undefined, undefined, undefined, undefined, error));- }-- return;- }-- if (parseResult === undefined) {- onError(pathToArray(path), inputValue, new GraphQLError("Expected type \"".concat(type.name, "\".")));- }-- return parseResult;- } // istanbul ignore next (Not reachable. All possible input types have been considered)--- invariant(0, 'Unexpected input type: ' + inspect(type));-}--/**- * Prepares an object map of variableValues of the correct type based on the- * provided variable definitions and arbitrary input. If the input cannot be- * parsed to match the variable definitions, a GraphQLError will be thrown.- *- * Note: The returned value is a plain Object with a prototype, since it is- * exposed to user code. Care should be taken to not pull values from the- * Object prototype.- *- * @internal- */-function getVariableValues(schema, varDefNodes, inputs, options) {- var errors = [];- var maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors;-- try {- var coerced = coerceVariableValues(schema, varDefNodes, inputs, function (error) {- if (maxErrors != null && errors.length >= maxErrors) {- throw new GraphQLError('Too many errors processing variables, error limit reached. Execution aborted.');- }-- errors.push(error);- });-- if (errors.length === 0) {- return {- coerced: coerced- };- }- } catch (error) {- errors.push(error);- }-- return {- errors: errors- };-}--function coerceVariableValues(schema, varDefNodes, inputs, onError) {- var coercedValues = {};-- var _loop = function _loop(_i2) {- var varDefNode = varDefNodes[_i2];- var varName = varDefNode.variable.name.value;- var varType = typeFromAST(schema, varDefNode.type);-- if (!isInputType(varType)) {- // Must use input types for variables. This should be caught during- // validation, however is checked again here for safety.- var varTypeStr = print(varDefNode.type);- onError(new GraphQLError("Variable \"$".concat(varName, "\" expected value of type \"").concat(varTypeStr, "\" which cannot be used as an input type."), varDefNode.type));- return "continue";- }-- if (!hasOwnProperty(inputs, varName)) {- if (varDefNode.defaultValue) {- coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType);- } else if (isNonNullType(varType)) {- var _varTypeStr = inspect(varType);-- onError(new GraphQLError("Variable \"$".concat(varName, "\" of required type \"").concat(_varTypeStr, "\" was not provided."), varDefNode));- }-- return "continue";- }-- var value = inputs[varName];-- if (value === null && isNonNullType(varType)) {- var _varTypeStr2 = inspect(varType);-- onError(new GraphQLError("Variable \"$".concat(varName, "\" of non-null type \"").concat(_varTypeStr2, "\" must not be null."), varDefNode));- return "continue";- }-- coercedValues[varName] = coerceInputValue(value, varType, function (path, invalidValue, error) {- var prefix = "Variable \"$".concat(varName, "\" got invalid value ") + inspect(invalidValue);-- if (path.length > 0) {- prefix += " at \"".concat(varName).concat(printPathArray(path), "\"");- }-- onError(new GraphQLError(prefix + '; ' + error.message, varDefNode, undefined, undefined, undefined, error.originalError));- });- };-- for (var _i2 = 0; _i2 < varDefNodes.length; _i2++) {- var _ret = _loop(_i2);-- if (_ret === "continue") continue;- }-- return coercedValues;-}-/**- * Prepares an object map of argument values given a list of argument- * definitions and list of argument AST nodes.- *- * Note: The returned value is a plain Object with a prototype, since it is- * exposed to user code. Care should be taken to not pull values from the- * Object prototype.- *- * @internal- */---function getArgumentValues(def, node, variableValues) {- var _node$arguments;-- var coercedValues = {}; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')-- var argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : [];- var argNodeMap = keyMap(argumentNodes, function (arg) {- return arg.name.value;- });-- for (var _i4 = 0, _def$args2 = def.args; _i4 < _def$args2.length; _i4++) {- var argDef = _def$args2[_i4];- var name = argDef.name;- var argType = argDef.type;- var argumentNode = argNodeMap[name];-- if (!argumentNode) {- if (argDef.defaultValue !== undefined) {- coercedValues[name] = argDef.defaultValue;- } else if (isNonNullType(argType)) {- throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + 'was not provided.', node);- }-- continue;- }-- var valueNode = argumentNode.value;- var isNull = valueNode.kind === Kind.NULL;-- if (valueNode.kind === Kind.VARIABLE) {- var variableName = valueNode.name.value;-- if (variableValues == null || !hasOwnProperty(variableValues, variableName)) {- if (argDef.defaultValue !== undefined) {- coercedValues[name] = argDef.defaultValue;- } else if (isNonNullType(argType)) {- 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);- }-- continue;- }-- isNull = variableValues[variableName] == null;- }-- if (isNull && isNonNullType(argType)) {- throw new GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat(inspect(argType), "\" ") + 'must not be null.', valueNode);- }-- var coercedValue = valueFromAST(valueNode, argType, variableValues);-- if (coercedValue === undefined) {- // Note: ValuesOfCorrectTypeRule validation should catch this before- // execution. This is a runtime check to ensure execution does not- // continue with an invalid argument value.- throw new GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat(print(valueNode), "."), valueNode);- }-- coercedValues[name] = coercedValue;- }-- return coercedValues;-}-/**- * Prepares an object map of argument values given a directive definition- * and a AST node which may contain directives. Optionally also accepts a map- * of variable values.- *- * If the directive does not exist on the node, returns undefined.- *- * Note: The returned value is a plain Object with a prototype, since it is- * exposed to user code. Care should be taken to not pull values from the- * Object prototype.- */--function getDirectiveValues(directiveDef, node, variableValues) {- var directiveNode = node.directives && find(node.directives, function (directive) {- return directive.name.value === directiveDef.name;- });-- if (directiveNode) {- return getArgumentValues(directiveDef, directiveNode, variableValues);- }-}--function hasOwnProperty(obj, prop) {- return Object.prototype.hasOwnProperty.call(obj, prop);-}--/**- * Terminology- *- * "Definitions" are the generic name for top-level statements in the document.- * Examples of this include:- * 1) Operations (such as a query)- * 2) Fragments- *- * "Operations" are a generic name for requests in the document.- * Examples of this include:- * 1) query,- * 2) mutation- *- * "Selections" are the definitions that can appear legally and at- * single level of the query. These include:- * 1) field references e.g "a"- * 2) fragment "spreads" e.g. "...c"- * 3) inline fragment "spreads" e.g. "...on Type { a }"- */--/**- * Data that must be available at all points during query execution.- *- * Namely, schema of the type system that is currently executing,- * and the fragments defined in the query document- */--function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {- /* eslint-enable no-redeclare */- // Extract arguments from object args if provided.- return arguments.length === 1 ? executeImpl(argsOrSchema) : executeImpl({- schema: argsOrSchema,- document: document,- rootValue: rootValue,- contextValue: contextValue,- variableValues: variableValues,- operationName: operationName,- fieldResolver: fieldResolver,- typeResolver: typeResolver- });-}-/**- * Also implements the "Evaluating requests" section of the GraphQL specification.- * However, it guarantees to complete synchronously (or throw an error) assuming- * that all field resolvers are also synchronous.- */--function executeSync(args) {- var result = executeImpl(args); // Assert that the execution was synchronous.-- if (isPromise(result)) {- throw new Error('GraphQL execution failed to complete synchronously.');- }-- return result;-}--function executeImpl(args) {- var schema = args.schema,- document = args.document,- rootValue = args.rootValue,- contextValue = args.contextValue,- variableValues = args.variableValues,- operationName = args.operationName,- fieldResolver = args.fieldResolver,- typeResolver = args.typeResolver; // If arguments are missing or incorrect, throw an error.-- assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,- // a "Response" with only errors is returned.-- var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver); // Return early errors if execution context failed.-- if (Array.isArray(exeContext)) {- return {- errors: exeContext- };- } // Return a Promise that will eventually resolve to the data described by- // The "Response" section of the GraphQL specification.- //- // If errors are encountered while executing a GraphQL field, only that- // field and its descendants will be omitted, and sibling fields will still- // be executed. An execution which encounters errors will still result in a- // resolved Promise.--- var data = executeOperation(exeContext, exeContext.operation, rootValue);- return buildResponse(exeContext, data);-}-/**- * Given a completed execution context and data, build the { errors, data }- * response defined by the "Response" section of the GraphQL specification.- */---function buildResponse(exeContext, data) {- if (isPromise(data)) {- return data.then(function (resolved) {- return buildResponse(exeContext, resolved);- });- }-- return exeContext.errors.length === 0 ? {- data: data- } : {- errors: exeContext.errors,- data: data- };-}-/**- * Essential assertions before executing to provide developer feedback for- * improper use of the GraphQL library.- *- * @internal- */---function assertValidExecutionArguments(schema, document, rawVariableValues) {- document || devAssert(0, 'Must provide document.'); // If the schema used for execution is invalid, throw an error.-- assertValidSchema(schema); // Variables, if provided, must be an object.-- rawVariableValues == null || isObjectLike(rawVariableValues) || devAssert(0, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.');-}-/**- * Constructs a ExecutionContext object from the arguments passed to- * execute, which we will pass throughout the other execution methods.- *- * Throws a GraphQLError if a valid execution context cannot be created.- *- * @internal- */--function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver, typeResolver) {- var _definition$name, _operation$variableDe;-- var operation;- var fragments = Object.create(null);-- for (var _i2 = 0, _document$definitions2 = document.definitions; _i2 < _document$definitions2.length; _i2++) {- var definition = _document$definitions2[_i2];-- switch (definition.kind) {- case Kind.OPERATION_DEFINITION:- if (operationName == null) {- if (operation !== undefined) {- return [new GraphQLError('Must provide operation name if query contains multiple operations.')];- }-- operation = definition;- } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {- operation = definition;- }-- break;-- case Kind.FRAGMENT_DEFINITION:- fragments[definition.name.value] = definition;- break;- }- }-- if (!operation) {- if (operationName != null) {- return [new GraphQLError("Unknown operation named \"".concat(operationName, "\"."))];- }-- return [new GraphQLError('Must provide an operation.')];- } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')--- var variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : [];- var coercedVariableValues = getVariableValues(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, {- maxErrors: 50- });-- if (coercedVariableValues.errors) {- return coercedVariableValues.errors;- }-- return {- schema: schema,- fragments: fragments,- rootValue: rootValue,- contextValue: contextValue,- operation: operation,- variableValues: coercedVariableValues.coerced,- fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver,- typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver,- errors: []- };-}-/**- * Implements the "Evaluating operations" section of the spec.- */--function executeOperation(exeContext, operation, rootValue) {- var type = getOperationRootType(exeContext.schema, operation);- var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));- var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level,- // at which point we still log the error and null the parent field, which- // in this case is the entire response.- //- // Similar to completeValueCatchingError.-- try {- var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields);-- if (isPromise(result)) {- return result.then(undefined, function (error) {- exeContext.errors.push(error);- return Promise.resolve(null);- });- }-- return result;- } catch (error) {- exeContext.errors.push(error);- return null;- }-}-/**- * Implements the "Evaluating selection sets" section of the spec- * for "write" mode.- */---function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {- return promiseReduce(Object.keys(fields), function (results, responseName) {- var fieldNodes = fields[responseName];- var fieldPath = addPath(path, responseName, parentType.name);- var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);-- if (result === undefined) {- return results;- }-- if (isPromise(result)) {- return result.then(function (resolvedResult) {- results[responseName] = resolvedResult;- return results;- });- }-- results[responseName] = result;- return results;- }, Object.create(null));-}-/**- * Implements the "Evaluating selection sets" section of the spec- * for "read" mode.- */---function executeFields(exeContext, parentType, sourceValue, path, fields) {- var results = Object.create(null);- var containsPromise = false;-- for (var _i4 = 0, _Object$keys2 = Object.keys(fields); _i4 < _Object$keys2.length; _i4++) {- var responseName = _Object$keys2[_i4];- var fieldNodes = fields[responseName];- var fieldPath = addPath(path, responseName, parentType.name);- var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);-- if (result !== undefined) {- results[responseName] = result;-- if (!containsPromise && isPromise(result)) {- containsPromise = true;- }- }- } // If there are no promises, we can just return the object--- if (!containsPromise) {- return results;- } // Otherwise, results is a map from field name to the result of resolving that- // field, which is possibly a promise. Return a promise that will return this- // same map, but with any promises replaced with the values they resolved to.--- return promiseForObject(results);-}-/**- * Given a selectionSet, adds all of the fields in that selection to- * the passed in map of fields, and returns it at the end.- *- * CollectFields requires the "runtime type" of an object. For a field which- * returns an Interface or Union type, the "runtime type" will be the actual- * Object type returned by that field.- *- * @internal- */---function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {- for (var _i6 = 0, _selectionSet$selecti2 = selectionSet.selections; _i6 < _selectionSet$selecti2.length; _i6++) {- var selection = _selectionSet$selecti2[_i6];-- switch (selection.kind) {- case Kind.FIELD:- {- if (!shouldIncludeNode(exeContext, selection)) {- continue;- }-- var name = getFieldEntryKey(selection);-- if (!fields[name]) {- fields[name] = [];- }-- fields[name].push(selection);- break;- }-- case Kind.INLINE_FRAGMENT:- {- if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {- continue;- }-- collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);- break;- }-- case Kind.FRAGMENT_SPREAD:- {- var fragName = selection.name.value;-- if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) {- continue;- }-- visitedFragmentNames[fragName] = true;- var fragment = exeContext.fragments[fragName];-- if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {- continue;- }-- collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);- break;- }- }- }-- return fields;-}-/**- * Determines if a field should be included based on the @include and @skip- * directives, where @skip has higher precedence than @include.- */--function shouldIncludeNode(exeContext, node) {- var skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues);-- if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {- return false;- }-- var include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues);-- if ((include === null || include === void 0 ? void 0 : include.if) === false) {- return false;- }-- return true;-}-/**- * Determines if a fragment is applicable to the given type.- */---function doesFragmentConditionMatch(exeContext, fragment, type) {- var typeConditionNode = fragment.typeCondition;-- if (!typeConditionNode) {- return true;- }-- var conditionalType = typeFromAST(exeContext.schema, typeConditionNode);-- if (conditionalType === type) {- return true;- }-- if (isAbstractType(conditionalType)) {- return exeContext.schema.isSubType(conditionalType, type);- }-- return false;-}-/**- * Implements the logic to compute the key of a given field's entry- */---function getFieldEntryKey(node) {- return node.alias ? node.alias.value : node.name.value;-}-/**- * Resolves the field on the given source object. In particular, this- * figures out the value that the field returns by calling its resolve function,- * then calls completeValue to complete promises, serialize scalars, or execute- * the sub-selection-set for objects.- */---function resolveField(exeContext, parentType, source, fieldNodes, path) {- var _fieldDef$resolve;-- var fieldNode = fieldNodes[0];- var fieldName = fieldNode.name.value;- var fieldDef = getFieldDef$1(exeContext.schema, parentType, fieldName);-- if (!fieldDef) {- return;- }-- var resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver;- var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal- // or abrupt (error).-- var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info);- return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result);-}-/**- * @internal- */---function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {- // The resolve function's optional fourth argument is a collection of- // information about the current execution state.- return {- fieldName: fieldDef.name,- fieldNodes: fieldNodes,- returnType: fieldDef.type,- parentType: parentType,- path: path,- schema: exeContext.schema,- fragments: exeContext.fragments,- rootValue: exeContext.rootValue,- operation: exeContext.operation,- variableValues: exeContext.variableValues- };-}-/**- * Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`- * function. Returns the result of resolveFn or the abrupt-return Error object.- *- * @internal- */--function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) {- try {- // Build a JS object of arguments from the field.arguments AST, using the- // variables scope to fulfill any variable references.- // TODO: find a way to memoize, in case this field is within a List type.- var args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that- // is provided to every resolve function within an execution. It is commonly- // used to represent an authenticated user, or request-specific caches.-- var _contextValue = exeContext.contextValue;- var result = resolveFn(source, args, _contextValue, info);- return isPromise(result) ? result.then(undefined, asErrorInstance) : result;- } catch (error) {- return asErrorInstance(error);- }-} // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a-// consistent Error interface.--function asErrorInstance(error) {- if (error instanceof Error) {- return error;- }-- return new Error('Unexpected error value: ' + inspect(error));-} // This is a small wrapper around completeValue which detects and logs errors-// in the execution context.---function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) {- try {- var completed;-- if (isPromise(result)) {- completed = result.then(function (resolved) {- return completeValue(exeContext, returnType, fieldNodes, info, path, resolved);- });- } else {- completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);- }-- if (isPromise(completed)) {- // Note: we don't rely on a `catch` method, but we do expect "thenable"- // to take a second callback for the error case.- return completed.then(undefined, function (error) {- return handleFieldError(error, fieldNodes, path, returnType, exeContext);- });- }-- return completed;- } catch (error) {- return handleFieldError(error, fieldNodes, path, returnType, exeContext);- }-}--function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) {- var error = locatedError(asErrorInstance(rawError), fieldNodes, pathToArray(path)); // If the field type is non-nullable, then it is resolved without any- // protection from errors, however it still properly locates the error.-- if (isNonNullType(returnType)) {- throw error;- } // Otherwise, error protection is applied, logging the error and resolving- // a null value for this field if one is encountered.--- exeContext.errors.push(error);- return null;-}-/**- * Implements the instructions for completeValue as defined in the- * "Field entries" section of the spec.- *- * If the field type is Non-Null, then this recursively completes the value- * for the inner type. It throws a field error if that completion returns null,- * as per the "Nullability" section of the spec.- *- * If the field type is a List, then this recursively completes the value- * for the inner type on each item in the list.- *- * If the field type is a Scalar or Enum, ensures the completed value is a legal- * value of the type by calling the `serialize` method of GraphQL type- * definition.- *- * If the field is an abstract type, determine the runtime type of the value- * and then complete based on that type- *- * Otherwise, the field type expects a sub-selection set, and will complete the- * value by evaluating all sub-selections.- */---function completeValue(exeContext, returnType, fieldNodes, info, path, result) {- // If result is an Error, throw a located error.- if (result instanceof Error) {- throw result;- } // If field type is NonNull, complete for inner type, and throw field error- // if result is null.--- if (isNonNullType(returnType)) {- var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);-- if (completed === null) {- throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, "."));- }-- return completed;- } // If result value is null or undefined then return null.--- if (result == null) {- return null;- } // If field type is List, complete each item in the list with the inner type--- if (isListType(returnType)) {- return completeListValue(exeContext, returnType, fieldNodes, info, path, result);- } // If field type is a leaf type, Scalar or Enum, serialize to a valid value,- // returning null if serialization is not possible.--- if (isLeafType(returnType)) {- return completeLeafValue(returnType, result);- } // If field type is an abstract type, Interface or Union, determine the- // runtime Object type and complete for that type.--- if (isAbstractType(returnType)) {- return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);- } // If field type is Object, execute and complete all sub-selections.- // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isObjectType(returnType)) {- return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);- } // istanbul ignore next (Not reachable. All possible output types have been considered)--- invariant(0, 'Cannot complete value of unexpected output type: ' + inspect(returnType));-}-/**- * Complete a list value by completing each item in the list with the- * inner type- */---function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {- if (!isCollection(result)) {- throw new GraphQLError("Expected Iterable, but did not find one for field \"".concat(info.parentType.name, ".").concat(info.fieldName, "\"."));- } // This is specified as a simple map, however we're optimizing the path- // where the list contains no Promises by avoiding creating another Promise.--- var itemType = returnType.ofType;- var containsPromise = false;- var completedResults = arrayFrom(result, function (item, index) {- // No need to modify the info object containing the path,- // since from here on it is not ever accessed by resolver functions.- var fieldPath = addPath(path, index, undefined);- var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item);-- if (!containsPromise && isPromise(completedItem)) {- containsPromise = true;- }-- return completedItem;- });- return containsPromise ? Promise.all(completedResults) : completedResults;-}-/**- * Complete a Scalar or Enum by serializing to a valid value, returning- * null if serialization is not possible.- */---function completeLeafValue(returnType, result) {- var serializedResult = returnType.serialize(result);-- if (serializedResult === undefined) {- throw new Error("Expected a value of type \"".concat(inspect(returnType), "\" but ") + "received: ".concat(inspect(result)));- }-- return serializedResult;-}-/**- * Complete a value of an abstract type by determining the runtime object type- * of that value, then complete the value for that type.- */---function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {- var _returnType$resolveTy;-- var resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver;- var contextValue = exeContext.contextValue;- var runtimeType = resolveTypeFn(result, contextValue, info, returnType);-- if (isPromise(runtimeType)) {- return runtimeType.then(function (resolvedRuntimeType) {- return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);- });- }-- return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);-}--function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) {- var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName;-- if (!isObjectType(runtimeType)) {- throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" must resolve to an Object type at runtime for field \"").concat(info.parentType.name, ".").concat(info.fieldName, "\" with ") + "value ".concat(inspect(result), ", received \"").concat(inspect(runtimeType), "\". ") + "Either the \"".concat(returnType.name, "\" type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."), fieldNodes);- }-- if (!exeContext.schema.isSubType(returnType, runtimeType)) {- throw new GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type for \"").concat(returnType.name, "\"."), fieldNodes);- }-- return runtimeType;-}-/**- * Complete an Object value by executing all sub-selections.- */---function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {- // If there is an isTypeOf predicate function, call it with the- // current result. If isTypeOf returns false, then raise an error rather- // than continuing execution.- if (returnType.isTypeOf) {- var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);-- if (isPromise(isTypeOf)) {- return isTypeOf.then(function (resolvedIsTypeOf) {- if (!resolvedIsTypeOf) {- throw invalidReturnTypeError(returnType, result, fieldNodes);- }-- return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);- });- }-- if (!isTypeOf) {- throw invalidReturnTypeError(returnType, result, fieldNodes);- }- }-- return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);-}--function invalidReturnTypeError(returnType, result, fieldNodes) {- return new GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat(inspect(result), "."), fieldNodes);-}--function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) {- // Collect sub-fields to execute to complete this value.- var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);- return executeFields(exeContext, returnType, result, path, subFieldNodes);-}-/**- * A memoized collection of relevant subfields with regard to the return- * type. Memoizing ensures the subfields are not repeatedly calculated, which- * saves overhead when resolving lists of values.- */---var collectSubfields = memoize3(_collectSubfields);--function _collectSubfields(exeContext, returnType, fieldNodes) {- var subFieldNodes = Object.create(null);- var visitedFragmentNames = Object.create(null);-- for (var _i8 = 0; _i8 < fieldNodes.length; _i8++) {- var node = fieldNodes[_i8];-- if (node.selectionSet) {- subFieldNodes = collectFields(exeContext, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames);- }- }-- return subFieldNodes;-}-/**- * If a resolveType function is not given, then a default resolve behavior is- * used which attempts two strategies:- *- * First, See if the provided value has a `__typename` field defined, if so, use- * that value as name of the resolved type.- *- * Otherwise, test each possible type for the abstract type by calling- * isTypeOf for the object being coerced, returning the first type that matches.- */---var defaultTypeResolver = function defaultTypeResolver(value, contextValue, info, abstractType) {- // First, look for `__typename`.- if (isObjectLike(value) && typeof value.__typename === 'string') {- return value.__typename;- } // Otherwise, test each possible type.--- var possibleTypes = info.schema.getPossibleTypes(abstractType);- var promisedIsTypeOfResults = [];-- for (var i = 0; i < possibleTypes.length; i++) {- var type = possibleTypes[i];-- if (type.isTypeOf) {- var isTypeOfResult = type.isTypeOf(value, contextValue, info);-- if (isPromise(isTypeOfResult)) {- promisedIsTypeOfResults[i] = isTypeOfResult;- } else if (isTypeOfResult) {- return type;- }- }- }-- if (promisedIsTypeOfResults.length) {- return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) {- for (var _i9 = 0; _i9 < isTypeOfResults.length; _i9++) {- if (isTypeOfResults[_i9]) {- return possibleTypes[_i9];- }- }- });- }-};-/**- * If a resolve function is not given, then a default resolve behavior is used- * which takes the property of the source object of the same name as the field- * and returns it as the result, or if it's a function, returns the result- * of calling that function while passing along args and context value.- */--var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) {- // ensure source is a value for which property access is acceptable.- if (isObjectLike(source) || typeof source === 'function') {- var property = source[info.fieldName];-- if (typeof property === 'function') {- return source[info.fieldName](args, contextValue, info);- }-- return property;- }-};-/**- * This method looks up the field on the given type definition.- * It has special casing for the three introspection fields,- * __schema, __type and __typename. __typename is special because- * it can always be queried as a field, even in situations where no- * other fields are allowed, like on a Union. __schema and __type- * could get automatically added to the query type, but that would- * require mutating type definitions, which would cause issues.- *- * @internal- */--function getFieldDef$1(schema, parentType, fieldName) {- if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {- return SchemaMetaFieldDef;- } else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {- return TypeMetaFieldDef;- } else if (fieldName === TypeNameMetaFieldDef.name) {- return TypeNameMetaFieldDef;- }-- return parentType.getFields()[fieldName];-}--/**- * This is the primary entry point function for fulfilling GraphQL operations- * by parsing, validating, and executing a GraphQL document along side a- * GraphQL schema.- *- * More sophisticated GraphQL servers, such as those which persist queries,- * may wish to separate the validation and execution phases to a static time- * tooling step, and a server runtime step.- *- * Accepts either an object with named arguments, or individual arguments:- *- * schema:- * The GraphQL type system to use when validating and executing a query.- * source:- * A GraphQL language formatted string representing the requested operation.- * rootValue:- * The value provided as the first argument to resolver functions on the top- * level type (e.g. the query object type).- * contextValue:- * The context value is provided as an argument to resolver functions after- * field arguments. It is used to pass shared information useful at any point- * during executing this query, for example the currently logged in user and- * connections to databases or other services.- * variableValues:- * A mapping of variable name to runtime value to use for all variables- * defined in the requestString.- * operationName:- * The name of the operation to use if requestString contains multiple- * possible operations. Can be omitted if requestString contains only- * one operation.- * fieldResolver:- * A resolver function to use when one is not provided by the schema.- * If not provided, the default field resolver is used (which looks for a- * value or method on the source value with the field's name).- * typeResolver:- * A type resolver function to use when none is provided by the schema.- * If not provided, the default type resolver is used (which looks for a- * `__typename` field or alternatively calls the `isTypeOf` method).- */--function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {- var _arguments = arguments;-- /* eslint-enable no-redeclare */- // Always return a Promise for a consistent API.- return new Promise(function (resolve) {- return resolve( // Extract arguments from object args if provided.- _arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({- schema: argsOrSchema,- source: source,- rootValue: rootValue,- contextValue: contextValue,- variableValues: variableValues,- operationName: operationName,- fieldResolver: fieldResolver,- typeResolver: typeResolver- }));- });-}-/**- * The graphqlSync function also fulfills GraphQL operations by parsing,- * validating, and executing a GraphQL document along side a GraphQL schema.- * However, it guarantees to complete synchronously (or throw an error) assuming- * that all field resolvers are also synchronous.- */--function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {- /* eslint-enable no-redeclare */- // Extract arguments from object args if provided.- var result = arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({- schema: argsOrSchema,- source: source,- rootValue: rootValue,- contextValue: contextValue,- variableValues: variableValues,- operationName: operationName,- fieldResolver: fieldResolver,- typeResolver: typeResolver- }); // Assert that the execution was synchronous.-- if (isPromise(result)) {- throw new Error('GraphQL execution failed to complete synchronously.');- }-- return result;-}--function graphqlImpl(args) {- var schema = args.schema,- source = args.source,- rootValue = args.rootValue,- contextValue = args.contextValue,- variableValues = args.variableValues,- operationName = args.operationName,- fieldResolver = args.fieldResolver,- typeResolver = args.typeResolver; // Validate Schema-- var schemaValidationErrors = validateSchema(schema);-- if (schemaValidationErrors.length > 0) {- return {- errors: schemaValidationErrors- };- } // Parse--- var document;-- try {- document = parse(source);- } catch (syntaxError) {- return {- errors: [syntaxError]- };- } // Validate--- var validationErrors = validate(schema, document);-- if (validationErrors.length > 0) {- return {- errors: validationErrors- };- } // Execute--- return execute({- schema: schema,- document: document,- rootValue: rootValue,- contextValue: contextValue,- variableValues: variableValues,- operationName: operationName,- fieldResolver: fieldResolver,- typeResolver: typeResolver- });-}--function _defineProperty$3(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }--/**- * Given an AsyncIterable and a callback function, return an AsyncIterator- * which produces values mapped via calling the callback function.- */-function mapAsyncIterator(iterable, callback, rejectCallback) {- // $FlowFixMe- var iteratorMethod = iterable[SYMBOL_ASYNC_ITERATOR];- var iterator = iteratorMethod.call(iterable);- var $return;- var abruptClose;-- if (typeof iterator.return === 'function') {- $return = iterator.return;-- abruptClose = function abruptClose(error) {- var rethrow = function rethrow() {- return Promise.reject(error);- };-- return $return.call(iterator).then(rethrow, rethrow);- };- }-- function mapResult(result) {- return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);- }-- var mapReject;-- if (rejectCallback) {- // Capture rejectCallback to ensure it cannot be null.- var reject = rejectCallback;-- mapReject = function mapReject(error) {- return asyncMapValue(error, reject).then(iteratorResult, abruptClose);- };- }- /* TODO: Flow doesn't support symbols as keys:- https://github.com/facebook/flow/issues/3258 */--- return _defineProperty$3({- next: function next() {- return iterator.next().then(mapResult, mapReject);- },- return: function _return() {- return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({- value: undefined,- done: true- });- },- throw: function _throw(error) {- if (typeof iterator.throw === 'function') {- return iterator.throw(error).then(mapResult, mapReject);- }-- return Promise.reject(error).catch(abruptClose);- }- }, SYMBOL_ASYNC_ITERATOR, function () {- return this;- });-}--function asyncMapValue(value, callback) {- return new Promise(function (resolve) {- return resolve(callback(value));- });-}--function iteratorResult(value) {- return {- value: value,- done: false- };-}--function _typeof$4(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$4 = function _typeof(obj) { return typeof obj; }; } else { _typeof$4 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$4(obj); }-function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) {- /* eslint-enable no-redeclare */- // Extract arguments from object args if provided.- return arguments.length === 1 ? subscribeImpl(argsOrSchema) : subscribeImpl({- schema: argsOrSchema,- document: document,- rootValue: rootValue,- contextValue: contextValue,- variableValues: variableValues,- operationName: operationName,- fieldResolver: fieldResolver,- subscribeFieldResolver: subscribeFieldResolver- });-}-/**- * This function checks if the error is a GraphQLError. If it is, report it as- * an ExecutionResult, containing only errors and no data. Otherwise treat the- * error as a system-class error and re-throw it.- */--function reportGraphQLError(error) {- if (error instanceof GraphQLError) {- return {- errors: [error]- };- }-- throw error;-}--function subscribeImpl(args) {- var schema = args.schema,- document = args.document,- rootValue = args.rootValue,- contextValue = args.contextValue,- variableValues = args.variableValues,- operationName = args.operationName,- fieldResolver = args.fieldResolver,- subscribeFieldResolver = args.subscribeFieldResolver;- var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal- // GraphQL `execute` function, with `payload` as the rootValue.- // This implements the "MapSourceToResponseEvent" algorithm described in- // the GraphQL specification. The `execute` function provides the- // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the- // "ExecuteQuery" algorithm, for which `execute` is also used.-- var mapSourceToResponse = function mapSourceToResponse(payload) {- return execute({- schema: schema,- document: document,- rootValue: payload,- contextValue: contextValue,- variableValues: variableValues,- operationName: operationName,- fieldResolver: fieldResolver- });- }; // Resolve the Source Stream, then map every source value to a- // ExecutionResult value as described above.--- return sourcePromise.then(function (resultOrStream) {- return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used.- isAsyncIterable(resultOrStream) ? mapAsyncIterator(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream- );- });-}-/**- * Implements the "CreateSourceEventStream" algorithm described in the- * GraphQL specification, resolving the subscription source event stream.- *- * Returns a Promise which resolves to either an AsyncIterable (if successful)- * or an ExecutionResult (error). The promise will be rejected if the schema or- * other arguments to this function are invalid, or if the resolved event stream- * is not an async iterable.- *- * If the client-provided arguments to this function do not result in a- * compliant subscription, a GraphQL Response (ExecutionResult) with- * descriptive errors and no data will be returned.- *- * If the the source stream could not be created due to faulty subscription- * resolver logic or underlying systems, the promise will resolve to a single- * ExecutionResult containing `errors` and no `data`.- *- * If the operation succeeded, the promise resolves to the AsyncIterable for the- * event stream returned by the resolver.- *- * A Source Event Stream represents a sequence of events, each of which triggers- * a GraphQL execution for that event.- *- * This may be useful when hosting the stateful subscription service in a- * different process or machine than the stateless GraphQL execution engine,- * or otherwise separating these two steps. For more on this, see the- * "Supporting Subscriptions at Scale" information in the GraphQL specification.- */---function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {- // If arguments are missing or incorrectly typed, this is an internal- // developer mistake which should throw an early error.- assertValidExecutionArguments(schema, document, variableValues);-- try {- var _fieldDef$subscribe;-- // If a valid context cannot be created due to incorrect arguments,- // this will throw an error.- var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed.-- if (Array.isArray(exeContext)) {- return Promise.resolve({- errors: exeContext- });- }-- var type = getOperationRootType(schema, exeContext.operation);- var fields = collectFields(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null));- var responseNames = Object.keys(fields);- var responseName = responseNames[0];- var fieldNodes = fields[responseName];- var fieldNode = fieldNodes[0];- var fieldName = fieldNode.name.value;- var fieldDef = getFieldDef$1(schema, type, fieldName);-- if (!fieldDef) {- throw new GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes);- } // Call the `subscribe()` resolver or the default resolver to produce an- // AsyncIterable yielding raw payloads.--- var resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.fieldResolver;- var path = addPath(undefined, responseName, type.name);- var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream"- // algorithm from GraphQL specification. It differs from- // "ResolveFieldValue" due to providing a different `resolveFn`.-- var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type.-- return Promise.resolve(result).then(function (eventStream) {- // If eventStream is an Error, rethrow a located error.- if (eventStream instanceof Error) {- return {- errors: [locatedError(eventStream, fieldNodes, pathToArray(path))]- };- } // Assert field returned an event stream, otherwise yield an error.--- if (isAsyncIterable(eventStream)) {- // Note: isAsyncIterable above ensures this will be correct.- return eventStream;- }-- throw new Error('Subscription field must return Async Iterable. ' + "Received: ".concat(inspect(eventStream), "."));- });- } catch (error) {- // As with reportGraphQLError above, if the error is a GraphQLError, report- // it as an ExecutionResult; otherwise treat it as a system-class error and- // re-throw it.- return error instanceof GraphQLError ? Promise.resolve({- errors: [error]- }) : Promise.reject(error);- }-}-/**- * Returns true if the provided object implements the AsyncIterator protocol via- * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method.- */--function isAsyncIterable(maybeAsyncIterable) {- if (maybeAsyncIterable == null || _typeof$4(maybeAsyncIterable) !== 'object') {- return false;- }-- return typeof maybeAsyncIterable[SYMBOL_ASYNC_ITERATOR] === 'function';-}--/**- * No deprecated- *- * A GraphQL document is only valid if all selected fields and all used enum values have not been- * deprecated.- *- * Note: This rule is optional and is not part of the Validation section of the GraphQL- * Specification. The main purpose of this rule is detection of deprecated usages and not- * necessarily to forbid their use when querying a service.- */-function NoDeprecatedCustomRule(context) {- return {- Field: function Field(node) {- var fieldDef = context.getFieldDef();- var parentType = context.getParentType();-- if (parentType && (fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason) != null) {- context.reportError(new GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated. ") + fieldDef.deprecationReason, node));- }- },- EnumValue: function EnumValue(node) {- var type = getNamedType(context.getInputType());- var enumValue = context.getEnumValue();-- if (type && (enumValue === null || enumValue === void 0 ? void 0 : enumValue.deprecationReason) != null) {- context.reportError(new GraphQLError("The enum value \"".concat(type.name, ".").concat(enumValue.name, "\" is deprecated. ") + enumValue.deprecationReason, node));- }- }- };-}--/**- * Prohibit introspection queries- *- * A GraphQL document is only valid if all fields selected are not fields that- * return an introspection type.- *- * Note: This rule is optional and is not part of the Validation section of the- * GraphQL Specification. This rule effectively disables introspection, which- * does not reflect best practices and should only be done if absolutely necessary.- */-function NoSchemaIntrospectionCustomRule(context) {- return {- Field: function Field(node) {- var type = getNamedType(context.getType());-- if (type && isIntrospectionType(type)) {- context.reportError(new GraphQLError("GraphQL introspection has been disabled, but the requested query contained the field \"".concat(node.name.value, "\"."), node));- }- }- };-}--/**- * Given a GraphQLError, format it according to the rules described by the- * Response Format, Errors section of the GraphQL Specification.- */-function formatError(error) {- var _error$message;-- error || devAssert(0, 'Received null or undefined error.');- var message = (_error$message = error.message) !== null && _error$message !== void 0 ? _error$message : 'An unknown error occurred.';- var locations = error.locations;- var path = error.path;- var extensions = error.extensions;- return extensions ? {- message: message,- locations: locations,- path: path,- extensions: extensions- } : {- message: message,- locations: locations,- path: path- };-}-/**- * @see https://github.com/graphql/graphql-spec/blob/master/spec/Section%207%20--%20Response.md#errors- */--function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }--function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty$4(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }--function _defineProperty$4(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }--function getIntrospectionQuery(options) {- var optionsWithDefault = _objectSpread$2({- descriptions: true,- specifiedByUrl: false,- directiveIsRepeatable: false,- schemaDescription: false- }, options);-- var descriptions = optionsWithDefault.descriptions ? 'description' : '';- var specifiedByUrl = optionsWithDefault.specifiedByUrl ? 'specifiedByUrl' : '';- var directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? 'isRepeatable' : '';- var schemaDescription = optionsWithDefault.schemaDescription ? descriptions : '';- return "\n query IntrospectionQuery {\n __schema {\n ".concat(schemaDescription, "\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ").concat(descriptions, "\n ").concat(directiveIsRepeatable, "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions, "\n ").concat(specifiedByUrl, "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions, "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions, "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions, "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n ");-}--/**- * Returns an operation AST given a document AST and optionally an operation- * name. If a name is not provided, an operation is only returned if only one is- * provided in the document.- */--function getOperationAST(documentAST, operationName) {- var operation = null;-- for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {- var definition = _documentAST$definiti2[_i2];-- if (definition.kind === Kind.OPERATION_DEFINITION) {- var _definition$name;-- if (operationName == null) {- // If no operation name was provided, only return an Operation if there- // is one defined in the document. Upon encountering the second, return- // null.- if (operation) {- return null;- }-- operation = definition;- } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {- return definition;- }- }- }-- return operation;-}--var getOperationAST$1 = /*#__PURE__*/Object.freeze({- __proto__: null,- getOperationAST: getOperationAST-});--function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }--function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty$5(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }--function _defineProperty$5(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }-/**- * Build an IntrospectionQuery from a GraphQLSchema- *- * IntrospectionQuery is useful for utilities that care about type and field- * relationships, but do not need to traverse through those relationships.- *- * This is the inverse of buildClientSchema. The primary use case is outside- * of the server context, for instance when doing schema comparisons.- */--function introspectionFromSchema(schema, options) {- var optionsWithDefaults = _objectSpread$3({- directiveIsRepeatable: true,- schemaDescription: true- }, options);-- var document = parse(getIntrospectionQuery(optionsWithDefaults));- var result = executeSync({- schema: schema,- document: document- });- !result.errors && result.data || invariant(0);- return result.data;-}--/**- * Build a GraphQLSchema for use by client tools.- *- * Given the result of a client running the introspection query, creates and- * returns a GraphQLSchema instance which can be then used with all graphql-js- * tools, but cannot be used to execute a query, as introspection does not- * represent the "resolver", "parse" or "serialize" functions or any other- * server-internal mechanisms.- *- * This function expects a complete introspection result. Don't forget to check- * the "errors" field of a server response before calling this function.- */--function buildClientSchema(introspection, options) {- isObjectLike(introspection) && isObjectLike(introspection.__schema) || devAssert(0, "Invalid or incomplete introspection result. Ensure that you are passing \"data\" property of introspection response and no \"errors\" was returned alongside: ".concat(inspect(introspection), ".")); // Get the schema from the introspection result.-- var schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each.-- var typeMap = keyValMap(schemaIntrospection.types, function (typeIntrospection) {- return typeIntrospection.name;- }, function (typeIntrospection) {- return buildType(typeIntrospection);- }); // Include standard types only if they are used.-- for (var _i2 = 0, _ref2 = [].concat(specifiedScalarTypes, introspectionTypes); _i2 < _ref2.length; _i2++) {- var stdType = _ref2[_i2];-- if (typeMap[stdType.name]) {- typeMap[stdType.name] = stdType;- }- } // Get the root Query, Mutation, and Subscription types.--- var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null;- var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null;- var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if- // directives were not queried for.-- var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types.-- return new GraphQLSchema({- description: schemaIntrospection.description,- query: queryType,- mutation: mutationType,- subscription: subscriptionType,- types: objectValues(typeMap),- directives: directives,- assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid- }); // Given a type reference in introspection, return the GraphQLType instance.- // preferring cached instances before building new instances.-- function getType(typeRef) {- if (typeRef.kind === TypeKind.LIST) {- var itemRef = typeRef.ofType;-- if (!itemRef) {- throw new Error('Decorated type deeper than introspection query.');- }-- return GraphQLList(getType(itemRef));- }-- if (typeRef.kind === TypeKind.NON_NULL) {- var nullableRef = typeRef.ofType;-- if (!nullableRef) {- throw new Error('Decorated type deeper than introspection query.');- }-- var nullableType = getType(nullableRef);- return GraphQLNonNull(assertNullableType(nullableType));- }-- return getNamedType(typeRef);- }-- function getNamedType(typeRef) {- var typeName = typeRef.name;-- if (!typeName) {- throw new Error("Unknown type reference: ".concat(inspect(typeRef), "."));- }-- var type = typeMap[typeName];-- if (!type) {- throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure that a full introspection query is used in order to build a client schema."));- }-- return type;- }-- function getObjectType(typeRef) {- return assertObjectType(getNamedType(typeRef));- }-- function getInterfaceType(typeRef) {- return assertInterfaceType(getNamedType(typeRef));- } // Given a type's introspection result, construct the correct- // GraphQLType instance.--- function buildType(type) {- if (type != null && type.name != null && type.kind != null) {- switch (type.kind) {- case TypeKind.SCALAR:- return buildScalarDef(type);-- case TypeKind.OBJECT:- return buildObjectDef(type);-- case TypeKind.INTERFACE:- return buildInterfaceDef(type);-- case TypeKind.UNION:- return buildUnionDef(type);-- case TypeKind.ENUM:- return buildEnumDef(type);-- case TypeKind.INPUT_OBJECT:- return buildInputObjectDef(type);- }- }-- var typeStr = inspect(type);- throw new Error("Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ".concat(typeStr, "."));- }-- function buildScalarDef(scalarIntrospection) {- return new GraphQLScalarType({- name: scalarIntrospection.name,- description: scalarIntrospection.description,- specifiedByUrl: scalarIntrospection.specifiedByUrl- });- }-- function buildImplementationsList(implementingIntrospection) {- // TODO: Temporary workaround until GraphQL ecosystem will fully support- // 'interfaces' on interface types.- if (implementingIntrospection.interfaces === null && implementingIntrospection.kind === TypeKind.INTERFACE) {- return [];- }-- if (!implementingIntrospection.interfaces) {- var implementingIntrospectionStr = inspect(implementingIntrospection);- throw new Error("Introspection result missing interfaces: ".concat(implementingIntrospectionStr, "."));- }-- return implementingIntrospection.interfaces.map(getInterfaceType);- }-- function buildObjectDef(objectIntrospection) {- return new GraphQLObjectType({- name: objectIntrospection.name,- description: objectIntrospection.description,- interfaces: function interfaces() {- return buildImplementationsList(objectIntrospection);- },- fields: function fields() {- return buildFieldDefMap(objectIntrospection);- }- });- }-- function buildInterfaceDef(interfaceIntrospection) {- return new GraphQLInterfaceType({- name: interfaceIntrospection.name,- description: interfaceIntrospection.description,- interfaces: function interfaces() {- return buildImplementationsList(interfaceIntrospection);- },- fields: function fields() {- return buildFieldDefMap(interfaceIntrospection);- }- });- }-- function buildUnionDef(unionIntrospection) {- if (!unionIntrospection.possibleTypes) {- var unionIntrospectionStr = inspect(unionIntrospection);- throw new Error("Introspection result missing possibleTypes: ".concat(unionIntrospectionStr, "."));- }-- return new GraphQLUnionType({- name: unionIntrospection.name,- description: unionIntrospection.description,- types: function types() {- return unionIntrospection.possibleTypes.map(getObjectType);- }- });- }-- function buildEnumDef(enumIntrospection) {- if (!enumIntrospection.enumValues) {- var enumIntrospectionStr = inspect(enumIntrospection);- throw new Error("Introspection result missing enumValues: ".concat(enumIntrospectionStr, "."));- }-- return new GraphQLEnumType({- name: enumIntrospection.name,- description: enumIntrospection.description,- values: keyValMap(enumIntrospection.enumValues, function (valueIntrospection) {- return valueIntrospection.name;- }, function (valueIntrospection) {- return {- description: valueIntrospection.description,- deprecationReason: valueIntrospection.deprecationReason- };- })- });- }-- function buildInputObjectDef(inputObjectIntrospection) {- if (!inputObjectIntrospection.inputFields) {- var inputObjectIntrospectionStr = inspect(inputObjectIntrospection);- throw new Error("Introspection result missing inputFields: ".concat(inputObjectIntrospectionStr, "."));- }-- return new GraphQLInputObjectType({- name: inputObjectIntrospection.name,- description: inputObjectIntrospection.description,- fields: function fields() {- return buildInputValueDefMap(inputObjectIntrospection.inputFields);- }- });- }-- function buildFieldDefMap(typeIntrospection) {- if (!typeIntrospection.fields) {- throw new Error("Introspection result missing fields: ".concat(inspect(typeIntrospection), "."));- }-- return keyValMap(typeIntrospection.fields, function (fieldIntrospection) {- return fieldIntrospection.name;- }, buildField);- }-- function buildField(fieldIntrospection) {- var type = getType(fieldIntrospection.type);-- if (!isOutputType(type)) {- var typeStr = inspect(type);- throw new Error("Introspection must provide output type for fields, but received: ".concat(typeStr, "."));- }-- if (!fieldIntrospection.args) {- var fieldIntrospectionStr = inspect(fieldIntrospection);- throw new Error("Introspection result missing field args: ".concat(fieldIntrospectionStr, "."));- }-- return {- description: fieldIntrospection.description,- deprecationReason: fieldIntrospection.deprecationReason,- type: type,- args: buildInputValueDefMap(fieldIntrospection.args)- };- }-- function buildInputValueDefMap(inputValueIntrospections) {- return keyValMap(inputValueIntrospections, function (inputValue) {- return inputValue.name;- }, buildInputValue);- }-- function buildInputValue(inputValueIntrospection) {- var type = getType(inputValueIntrospection.type);-- if (!isInputType(type)) {- var typeStr = inspect(type);- throw new Error("Introspection must provide input type for arguments, but received: ".concat(typeStr, "."));- }-- var defaultValue = inputValueIntrospection.defaultValue != null ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) : undefined;- return {- description: inputValueIntrospection.description,- type: type,- defaultValue: defaultValue- };- }-- function buildDirective(directiveIntrospection) {- if (!directiveIntrospection.args) {- var directiveIntrospectionStr = inspect(directiveIntrospection);- throw new Error("Introspection result missing directive args: ".concat(directiveIntrospectionStr, "."));- }-- if (!directiveIntrospection.locations) {- var _directiveIntrospectionStr = inspect(directiveIntrospection);-- throw new Error("Introspection result missing directive locations: ".concat(_directiveIntrospectionStr, "."));- }-- return new GraphQLDirective({- name: directiveIntrospection.name,- description: directiveIntrospection.description,- isRepeatable: directiveIntrospection.isRepeatable,- locations: directiveIntrospection.locations.slice(),- args: buildInputValueDefMap(directiveIntrospection.args)- });- }-}--function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }--function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty$6(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }--function _defineProperty$6(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }--/**- * Produces a new schema given an existing schema and a document which may- * contain GraphQL type extensions and definitions. The original schema will- * remain unaltered.- *- * Because a schema represents a graph of references, a schema cannot be- * extended without effectively making an entire copy. We do not know until it's- * too late if subgraphs remain unchanged.- *- * This algorithm copies the provided schema, applying extensions while- * producing the copy. The original schema remains unaltered.- *- * Accepts options as a third argument:- *- * - commentDescriptions:- * Provide true to use preceding comments as the description.- *- */-function extendSchema(schema, documentAST, options) {- assertSchema(schema);- documentAST != null && documentAST.kind === Kind.DOCUMENT || devAssert(0, 'Must provide valid Document AST.');-- if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) {- assertValidSDLExtension(documentAST, schema);- }-- var schemaConfig = schema.toConfig();- var extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options);- return schemaConfig === extendedConfig ? schema : new GraphQLSchema(extendedConfig);-}-/**- * @internal- */--function extendSchemaImpl(schemaConfig, documentAST, options) {- var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid;-- // Collect the type definitions and extensions found in the document.- var typeDefs = [];- var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can- // have the same name. For example, a type named "skip".-- var directiveDefs = [];- var schemaDef; // Schema extensions are collected which may add additional operation types.-- var schemaExtensions = [];-- for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {- var def = _documentAST$definiti2[_i2];-- if (def.kind === Kind.SCHEMA_DEFINITION) {- schemaDef = def;- } else if (def.kind === Kind.SCHEMA_EXTENSION) {- schemaExtensions.push(def);- } else if (isTypeDefinitionNode(def)) {- typeDefs.push(def);- } else if (isTypeExtensionNode(def)) {- var extendedTypeName = def.name.value;- var existingTypeExtensions = typeExtensionsMap[extendedTypeName];- typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def];- } else if (def.kind === Kind.DIRECTIVE_DEFINITION) {- directiveDefs.push(def);- }- } // If this document contains no new types, extensions, or directives then- // return the same unmodified GraphQLSchema instance.--- if (Object.keys(typeExtensionsMap).length === 0 && typeDefs.length === 0 && directiveDefs.length === 0 && schemaExtensions.length === 0 && schemaDef == null) {- return schemaConfig;- }-- var typeMap = Object.create(null);-- for (var _i4 = 0, _schemaConfig$types2 = schemaConfig.types; _i4 < _schemaConfig$types2.length; _i4++) {- var existingType = _schemaConfig$types2[_i4];- typeMap[existingType.name] = extendNamedType(existingType);- }-- for (var _i6 = 0; _i6 < typeDefs.length; _i6++) {- var _stdTypeMap$name;-- var typeNode = typeDefs[_i6];- var name = typeNode.name.value;- typeMap[name] = (_stdTypeMap$name = stdTypeMap[name]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode);- }-- var operationTypes = _objectSpread$4(_objectSpread$4({- // Get the extended root operation types.- query: schemaConfig.query && replaceNamedType(schemaConfig.query),- mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),- subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription)- }, schemaDef && getOperationTypes([schemaDef])), getOperationTypes(schemaExtensions)); // Then produce and return a Schema config with these types.--- return _objectSpread$4(_objectSpread$4({- description: (_schemaDef = schemaDef) === null || _schemaDef === void 0 ? void 0 : (_schemaDef$descriptio = _schemaDef.description) === null || _schemaDef$descriptio === void 0 ? void 0 : _schemaDef$descriptio.value- }, operationTypes), {}, {- types: objectValues(typeMap),- directives: [].concat(schemaConfig.directives.map(replaceDirective), directiveDefs.map(buildDirective)),- extensions: undefined,- astNode: (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 ? _schemaDef2 : schemaConfig.astNode,- extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),- assumeValid: (_options$assumeValid = options === null || options === void 0 ? void 0 : options.assumeValid) !== null && _options$assumeValid !== void 0 ? _options$assumeValid : false- }); // Below are functions used for producing this schema that have closed over- // this scope and have access to the schema, cache, and newly defined types.-- function replaceType(type) {- if (isListType(type)) {- return new GraphQLList(replaceType(type.ofType));- } else if (isNonNullType(type)) {- return new GraphQLNonNull(replaceType(type.ofType));- }-- return replaceNamedType(type);- }-- function replaceNamedType(type) {- // Note: While this could make early assertions to get the correctly- // typed values, that would throw immediately while type system- // validation with validateSchema() will produce more actionable results.- return typeMap[type.name];- }-- function replaceDirective(directive) {- var config = directive.toConfig();- return new GraphQLDirective(_objectSpread$4(_objectSpread$4({}, config), {}, {- args: mapValue(config.args, extendArg)- }));- }-- function extendNamedType(type) {- if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {- // Builtin types are not extended.- return type;- }-- if (isScalarType(type)) {- return extendScalarType(type);- }-- if (isObjectType(type)) {- return extendObjectType(type);- }-- if (isInterfaceType(type)) {- return extendInterfaceType(type);- }-- if (isUnionType(type)) {- return extendUnionType(type);- }-- if (isEnumType(type)) {- return extendEnumType(type);- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isInputObjectType(type)) {- return extendInputObjectType(type);- } // istanbul ignore next (Not reachable. All possible types have been considered)--- invariant(0, 'Unexpected type: ' + inspect(type));- }-- function extendInputObjectType(type) {- var _typeExtensionsMap$co;-- var config = type.toConfig();- var extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : [];- return new GraphQLInputObjectType(_objectSpread$4(_objectSpread$4({}, config), {}, {- fields: function fields() {- return _objectSpread$4(_objectSpread$4({}, mapValue(config.fields, function (field) {- return _objectSpread$4(_objectSpread$4({}, field), {}, {- type: replaceType(field.type)- });- })), buildInputFieldMap(extensions));- },- extensionASTNodes: config.extensionASTNodes.concat(extensions)- }));- }-- function extendEnumType(type) {- var _typeExtensionsMap$ty;-- var config = type.toConfig();- var extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : [];- return new GraphQLEnumType(_objectSpread$4(_objectSpread$4({}, config), {}, {- values: _objectSpread$4(_objectSpread$4({}, config.values), buildEnumValueMap(extensions)),- extensionASTNodes: config.extensionASTNodes.concat(extensions)- }));- }-- function extendScalarType(type) {- var _typeExtensionsMap$co2;-- var config = type.toConfig();- var extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : [];- var specifiedByUrl = config.specifiedByUrl;-- for (var _i8 = 0; _i8 < extensions.length; _i8++) {- var _getSpecifiedByUrl;-- var extensionNode = extensions[_i8];- specifiedByUrl = (_getSpecifiedByUrl = getSpecifiedByUrl(extensionNode)) !== null && _getSpecifiedByUrl !== void 0 ? _getSpecifiedByUrl : specifiedByUrl;- }-- return new GraphQLScalarType(_objectSpread$4(_objectSpread$4({}, config), {}, {- specifiedByUrl: specifiedByUrl,- extensionASTNodes: config.extensionASTNodes.concat(extensions)- }));- }-- function extendObjectType(type) {- var _typeExtensionsMap$co3;-- var config = type.toConfig();- var extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : [];- return new GraphQLObjectType(_objectSpread$4(_objectSpread$4({}, config), {}, {- interfaces: function interfaces() {- return [].concat(type.getInterfaces().map(replaceNamedType), buildInterfaces(extensions));- },- fields: function fields() {- return _objectSpread$4(_objectSpread$4({}, mapValue(config.fields, extendField)), buildFieldMap(extensions));- },- extensionASTNodes: config.extensionASTNodes.concat(extensions)- }));- }-- function extendInterfaceType(type) {- var _typeExtensionsMap$co4;-- var config = type.toConfig();- var extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : [];- return new GraphQLInterfaceType(_objectSpread$4(_objectSpread$4({}, config), {}, {- interfaces: function interfaces() {- return [].concat(type.getInterfaces().map(replaceNamedType), buildInterfaces(extensions));- },- fields: function fields() {- return _objectSpread$4(_objectSpread$4({}, mapValue(config.fields, extendField)), buildFieldMap(extensions));- },- extensionASTNodes: config.extensionASTNodes.concat(extensions)- }));- }-- function extendUnionType(type) {- var _typeExtensionsMap$co5;-- var config = type.toConfig();- var extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : [];- return new GraphQLUnionType(_objectSpread$4(_objectSpread$4({}, config), {}, {- types: function types() {- return [].concat(type.getTypes().map(replaceNamedType), buildUnionTypes(extensions));- },- extensionASTNodes: config.extensionASTNodes.concat(extensions)- }));- }-- function extendField(field) {- return _objectSpread$4(_objectSpread$4({}, field), {}, {- type: replaceType(field.type),- args: mapValue(field.args, extendArg)- });- }-- function extendArg(arg) {- return _objectSpread$4(_objectSpread$4({}, arg), {}, {- type: replaceType(arg.type)- });- }-- function getOperationTypes(nodes) {- var opTypes = {};-- for (var _i10 = 0; _i10 < nodes.length; _i10++) {- var _node$operationTypes;-- var node = nodes[_i10];- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : [];-- for (var _i12 = 0; _i12 < operationTypesNodes.length; _i12++) {- var operationType = operationTypesNodes[_i12];- opTypes[operationType.operation] = getNamedType(operationType.type);- }- } // Note: While this could make early assertions to get the correctly- // typed values below, that would throw immediately while type system- // validation with validateSchema() will produce more actionable results.--- return opTypes;- }-- function getNamedType(node) {- var _stdTypeMap$name2;-- var name = node.name.value;- var type = (_stdTypeMap$name2 = stdTypeMap[name]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name];-- if (type === undefined) {- throw new Error("Unknown type: \"".concat(name, "\"."));- }-- return type;- }-- function getWrappedType(node) {- if (node.kind === Kind.LIST_TYPE) {- return new GraphQLList(getWrappedType(node.type));- }-- if (node.kind === Kind.NON_NULL_TYPE) {- return new GraphQLNonNull(getWrappedType(node.type));- }-- return getNamedType(node);- }-- function buildDirective(node) {- var locations = node.locations.map(function (_ref) {- var value = _ref.value;- return value;- });- return new GraphQLDirective({- name: node.name.value,- description: getDescription(node, options),- locations: locations,- isRepeatable: node.repeatable,- args: buildArgumentMap(node.arguments),- astNode: node- });- }-- function buildFieldMap(nodes) {- var fieldConfigMap = Object.create(null);-- for (var _i14 = 0; _i14 < nodes.length; _i14++) {- var _node$fields;-- var node = nodes[_i14];- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var nodeFields = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];-- for (var _i16 = 0; _i16 < nodeFields.length; _i16++) {- var field = nodeFields[_i16];- fieldConfigMap[field.name.value] = {- // Note: While this could make assertions to get the correctly typed- // value, that would throw immediately while type system validation- // with validateSchema() will produce more actionable results.- type: getWrappedType(field.type),- description: getDescription(field, options),- args: buildArgumentMap(field.arguments),- deprecationReason: getDeprecationReason(field),- astNode: field- };- }- }-- return fieldConfigMap;- }-- function buildArgumentMap(args) {- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var argsNodes = args !== null && args !== void 0 ? args : [];- var argConfigMap = Object.create(null);-- for (var _i18 = 0; _i18 < argsNodes.length; _i18++) {- var arg = argsNodes[_i18];- // Note: While this could make assertions to get the correctly typed- // value, that would throw immediately while type system validation- // with validateSchema() will produce more actionable results.- var type = getWrappedType(arg.type);- argConfigMap[arg.name.value] = {- type: type,- description: getDescription(arg, options),- defaultValue: valueFromAST(arg.defaultValue, type),- astNode: arg- };- }-- return argConfigMap;- }-- function buildInputFieldMap(nodes) {- var inputFieldMap = Object.create(null);-- for (var _i20 = 0; _i20 < nodes.length; _i20++) {- var _node$fields2;-- var node = nodes[_i20];- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var fieldsNodes = (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : [];-- for (var _i22 = 0; _i22 < fieldsNodes.length; _i22++) {- var field = fieldsNodes[_i22];- // Note: While this could make assertions to get the correctly typed- // value, that would throw immediately while type system validation- // with validateSchema() will produce more actionable results.- var type = getWrappedType(field.type);- inputFieldMap[field.name.value] = {- type: type,- description: getDescription(field, options),- defaultValue: valueFromAST(field.defaultValue, type),- astNode: field- };- }- }-- return inputFieldMap;- }-- function buildEnumValueMap(nodes) {- var enumValueMap = Object.create(null);-- for (var _i24 = 0; _i24 < nodes.length; _i24++) {- var _node$values;-- var node = nodes[_i24];- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var valuesNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : [];-- for (var _i26 = 0; _i26 < valuesNodes.length; _i26++) {- var value = valuesNodes[_i26];- enumValueMap[value.name.value] = {- description: getDescription(value, options),- deprecationReason: getDeprecationReason(value),- astNode: value- };- }- }-- return enumValueMap;- }-- function buildInterfaces(nodes) {- var interfaces = [];-- for (var _i28 = 0; _i28 < nodes.length; _i28++) {- var _node$interfaces;-- var node = nodes[_i28];- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var interfacesNodes = (_node$interfaces = node.interfaces) !== null && _node$interfaces !== void 0 ? _node$interfaces : [];-- for (var _i30 = 0; _i30 < interfacesNodes.length; _i30++) {- var type = interfacesNodes[_i30];- // Note: While this could make assertions to get the correctly typed- // values below, that would throw immediately while type system- // validation with validateSchema() will produce more actionable- // results.- interfaces.push(getNamedType(type));- }- }-- return interfaces;- }-- function buildUnionTypes(nodes) {- var types = [];-- for (var _i32 = 0; _i32 < nodes.length; _i32++) {- var _node$types;-- var node = nodes[_i32];- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')- var typeNodes = (_node$types = node.types) !== null && _node$types !== void 0 ? _node$types : [];-- for (var _i34 = 0; _i34 < typeNodes.length; _i34++) {- var type = typeNodes[_i34];- // Note: While this could make assertions to get the correctly typed- // values below, that would throw immediately while type system- // validation with validateSchema() will produce more actionable- // results.- types.push(getNamedType(type));- }- }-- return types;- }-- function buildType(astNode) {- var _typeExtensionsMap$na;-- var name = astNode.name.value;- var description = getDescription(astNode, options);- var extensionNodes = (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : [];-- switch (astNode.kind) {- case Kind.OBJECT_TYPE_DEFINITION:- {- var extensionASTNodes = extensionNodes;- var allNodes = [astNode].concat(extensionASTNodes);- return new GraphQLObjectType({- name: name,- description: description,- interfaces: function interfaces() {- return buildInterfaces(allNodes);- },- fields: function fields() {- return buildFieldMap(allNodes);- },- astNode: astNode,- extensionASTNodes: extensionASTNodes- });- }-- case Kind.INTERFACE_TYPE_DEFINITION:- {- var _extensionASTNodes = extensionNodes;-- var _allNodes = [astNode].concat(_extensionASTNodes);-- return new GraphQLInterfaceType({- name: name,- description: description,- interfaces: function interfaces() {- return buildInterfaces(_allNodes);- },- fields: function fields() {- return buildFieldMap(_allNodes);- },- astNode: astNode,- extensionASTNodes: _extensionASTNodes- });- }-- case Kind.ENUM_TYPE_DEFINITION:- {- var _extensionASTNodes2 = extensionNodes;-- var _allNodes2 = [astNode].concat(_extensionASTNodes2);-- return new GraphQLEnumType({- name: name,- description: description,- values: buildEnumValueMap(_allNodes2),- astNode: astNode,- extensionASTNodes: _extensionASTNodes2- });- }-- case Kind.UNION_TYPE_DEFINITION:- {- var _extensionASTNodes3 = extensionNodes;-- var _allNodes3 = [astNode].concat(_extensionASTNodes3);-- return new GraphQLUnionType({- name: name,- description: description,- types: function types() {- return buildUnionTypes(_allNodes3);- },- astNode: astNode,- extensionASTNodes: _extensionASTNodes3- });- }-- case Kind.SCALAR_TYPE_DEFINITION:- {- var _extensionASTNodes4 = extensionNodes;- return new GraphQLScalarType({- name: name,- description: description,- specifiedByUrl: getSpecifiedByUrl(astNode),- astNode: astNode,- extensionASTNodes: _extensionASTNodes4- });- }-- case Kind.INPUT_OBJECT_TYPE_DEFINITION:- {- var _extensionASTNodes5 = extensionNodes;-- var _allNodes4 = [astNode].concat(_extensionASTNodes5);-- return new GraphQLInputObjectType({- name: name,- description: description,- fields: function fields() {- return buildInputFieldMap(_allNodes4);- },- astNode: astNode,- extensionASTNodes: _extensionASTNodes5- });- }- } // istanbul ignore next (Not reachable. All possible type definition nodes have been considered)--- invariant(0, 'Unexpected type definition node: ' + inspect(astNode));- }-}-var stdTypeMap = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) {- return type.name;-});-/**- * Given a field or enum value node, returns the string value for the- * deprecation reason.- */--function getDeprecationReason(node) {- var deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node);- return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason;-}-/**- * Given a scalar node, returns the string value for the specifiedByUrl.- */---function getSpecifiedByUrl(node) {- var specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node);- return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url;-}-/**- * Given an ast node, returns its string description.- * @deprecated: provided to ease adoption and will be removed in v16.- *- * Accepts options as a second argument:- *- * - commentDescriptions:- * Provide true to use preceding comments as the description.- *- */---function getDescription(node, options) {- if (node.description) {- return node.description.value;- }-- if ((options === null || options === void 0 ? void 0 : options.commentDescriptions) === true) {- var rawValue = getLeadingCommentBlock(node);-- if (rawValue !== undefined) {- return dedentBlockStringValue('\n' + rawValue);- }- }-}--function getLeadingCommentBlock(node) {- var loc = node.loc;-- if (!loc) {- return;- }-- var comments = [];- var token = loc.startToken.prev;-- while (token != null && token.kind === TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) {- var value = String(token.value);- comments.push(value);- token = token.prev;- }-- return comments.length > 0 ? comments.reverse().join('\n') : undefined;-}--/**- * This takes the ast of a schema document produced by the parse function in- * src/language/parser.js.- *- * If no schema definition is provided, then it will look for types named Query- * and Mutation.- *- * Given that AST it constructs a GraphQLSchema. The resulting schema- * has no resolve methods, so execution will use default resolvers.- *- * Accepts options as a second argument:- *- * - commentDescriptions:- * Provide true to use preceding comments as the description.- *- */-function buildASTSchema(documentAST, options) {- documentAST != null && documentAST.kind === Kind.DOCUMENT || devAssert(0, 'Must provide valid Document AST.');-- if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) {- assertValidSDL(documentAST);- }-- var emptySchemaConfig = {- description: undefined,- types: [],- directives: [],- extensions: undefined,- extensionASTNodes: [],- assumeValid: false- };- var config = extendSchemaImpl(emptySchemaConfig, documentAST, options);-- if (config.astNode == null) {- for (var _i2 = 0, _config$types2 = config.types; _i2 < _config$types2.length; _i2++) {- var type = _config$types2[_i2];-- switch (type.name) {- // Note: While this could make early assertions to get the correctly- // typed values below, that would throw immediately while type system- // validation with validateSchema() will produce more actionable results.- case 'Query':- config.query = type;- break;-- case 'Mutation':- config.mutation = type;- break;-- case 'Subscription':- config.subscription = type;- break;- }- }- }-- var directives = config.directives; // If specified directives were not explicitly declared, add them.-- if (!directives.some(function (directive) {- return directive.name === 'skip';- })) {- directives.push(GraphQLSkipDirective);- }-- if (!directives.some(function (directive) {- return directive.name === 'include';- })) {- directives.push(GraphQLIncludeDirective);- }-- if (!directives.some(function (directive) {- return directive.name === 'deprecated';- })) {- directives.push(GraphQLDeprecatedDirective);- }-- if (!directives.some(function (directive) {- return directive.name === 'specifiedBy';- })) {- directives.push(GraphQLSpecifiedByDirective);- }-- return new GraphQLSchema(config);-}-/**- * A helper function to build a GraphQLSchema directly from a source- * document.- */--function buildSchema(source, options) {- var document = parse(source, {- noLocation: options === null || options === void 0 ? void 0 : options.noLocation,- allowLegacySDLEmptyFields: options === null || options === void 0 ? void 0 : options.allowLegacySDLEmptyFields,- allowLegacySDLImplementsInterfaces: options === null || options === void 0 ? void 0 : options.allowLegacySDLImplementsInterfaces,- experimentalFragmentVariables: options === null || options === void 0 ? void 0 : options.experimentalFragmentVariables- });- return buildASTSchema(document, {- commentDescriptions: options === null || options === void 0 ? void 0 : options.commentDescriptions,- assumeValidSDL: options === null || options === void 0 ? void 0 : options.assumeValidSDL,- assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid- });-}--function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }--function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty$7(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }--function _defineProperty$7(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }-/**- * Sort GraphQLSchema.- *- * This function returns a sorted copy of the given GraphQLSchema.- */--function lexicographicSortSchema(schema) {- var schemaConfig = schema.toConfig();- var typeMap = keyValMap(sortByName(schemaConfig.types), function (type) {- return type.name;- }, sortNamedType);- return new GraphQLSchema(_objectSpread$5(_objectSpread$5({}, schemaConfig), {}, {- types: objectValues(typeMap),- directives: sortByName(schemaConfig.directives).map(sortDirective),- query: replaceMaybeType(schemaConfig.query),- mutation: replaceMaybeType(schemaConfig.mutation),- subscription: replaceMaybeType(schemaConfig.subscription)- }));-- function replaceType(type) {- if (isListType(type)) {- return new GraphQLList(replaceType(type.ofType));- } else if (isNonNullType(type)) {- return new GraphQLNonNull(replaceType(type.ofType));- }-- return replaceNamedType(type);- }-- function replaceNamedType(type) {- return typeMap[type.name];- }-- function replaceMaybeType(maybeType) {- return maybeType && replaceNamedType(maybeType);- }-- function sortDirective(directive) {- var config = directive.toConfig();- return new GraphQLDirective(_objectSpread$5(_objectSpread$5({}, config), {}, {- locations: sortBy(config.locations, function (x) {- return x;- }),- args: sortArgs(config.args)- }));- }-- function sortArgs(args) {- return sortObjMap(args, function (arg) {- return _objectSpread$5(_objectSpread$5({}, arg), {}, {- type: replaceType(arg.type)- });- });- }-- function sortFields(fieldsMap) {- return sortObjMap(fieldsMap, function (field) {- return _objectSpread$5(_objectSpread$5({}, field), {}, {- type: replaceType(field.type),- args: sortArgs(field.args)- });- });- }-- function sortInputFields(fieldsMap) {- return sortObjMap(fieldsMap, function (field) {- return _objectSpread$5(_objectSpread$5({}, field), {}, {- type: replaceType(field.type)- });- });- }-- function sortTypes(arr) {- return sortByName(arr).map(replaceNamedType);- }-- function sortNamedType(type) {- if (isScalarType(type) || isIntrospectionType(type)) {- return type;- }-- if (isObjectType(type)) {- var config = type.toConfig();- return new GraphQLObjectType(_objectSpread$5(_objectSpread$5({}, config), {}, {- interfaces: function interfaces() {- return sortTypes(config.interfaces);- },- fields: function fields() {- return sortFields(config.fields);- }- }));- }-- if (isInterfaceType(type)) {- var _config = type.toConfig();-- return new GraphQLInterfaceType(_objectSpread$5(_objectSpread$5({}, _config), {}, {- interfaces: function interfaces() {- return sortTypes(_config.interfaces);- },- fields: function fields() {- return sortFields(_config.fields);- }- }));- }-- if (isUnionType(type)) {- var _config2 = type.toConfig();-- return new GraphQLUnionType(_objectSpread$5(_objectSpread$5({}, _config2), {}, {- types: function types() {- return sortTypes(_config2.types);- }- }));- }-- if (isEnumType(type)) {- var _config3 = type.toConfig();-- return new GraphQLEnumType(_objectSpread$5(_objectSpread$5({}, _config3), {}, {- values: sortObjMap(_config3.values)- }));- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isInputObjectType(type)) {- var _config4 = type.toConfig();-- return new GraphQLInputObjectType(_objectSpread$5(_objectSpread$5({}, _config4), {}, {- fields: function fields() {- return sortInputFields(_config4.fields);- }- }));- } // istanbul ignore next (Not reachable. All possible types have been considered)--- invariant(0, 'Unexpected type: ' + inspect(type));- }-}--function sortObjMap(map, sortValueFn) {- var sortedMap = Object.create(null);- var sortedKeys = sortBy(Object.keys(map), function (x) {- return x;- });-- for (var _i2 = 0; _i2 < sortedKeys.length; _i2++) {- var key = sortedKeys[_i2];- var value = map[key];- sortedMap[key] = sortValueFn ? sortValueFn(value) : value;- }-- return sortedMap;-}--function sortByName(array) {- return sortBy(array, function (obj) {- return obj.name;- });-}--function sortBy(array, mapToKey) {- return array.slice().sort(function (obj1, obj2) {- var key1 = mapToKey(obj1);- var key2 = mapToKey(obj2);- return key1.localeCompare(key2);- });-}--/**- * Accepts options as a second argument:- *- * - commentDescriptions:- * Provide true to use preceding comments as the description.- *- */-function printSchema(schema, options) {- return printFilteredSchema(schema, function (n) {- return !isSpecifiedDirective(n);- }, isDefinedType, options);-}-function printIntrospectionSchema(schema, options) {- return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType, options);-}--function isDefinedType(type) {- return !isSpecifiedScalarType(type) && !isIntrospectionType(type);-}--function printFilteredSchema(schema, directiveFilter, typeFilter, options) {- var directives = schema.getDirectives().filter(directiveFilter);- var types = objectValues(schema.getTypeMap()).filter(typeFilter);- return [printSchemaDefinition(schema)].concat(directives.map(function (directive) {- return printDirective(directive, options);- }), types.map(function (type) {- return printType(type, options);- })).filter(Boolean).join('\n\n') + '\n';-}--function printSchemaDefinition(schema) {- if (schema.description == null && isSchemaOfCommonNames(schema)) {- return;- }-- var operationTypes = [];- var queryType = schema.getQueryType();-- if (queryType) {- operationTypes.push(" query: ".concat(queryType.name));- }-- var mutationType = schema.getMutationType();-- if (mutationType) {- operationTypes.push(" mutation: ".concat(mutationType.name));- }-- var subscriptionType = schema.getSubscriptionType();-- if (subscriptionType) {- operationTypes.push(" subscription: ".concat(subscriptionType.name));- }-- return printDescription({}, schema) + "schema {\n".concat(operationTypes.join('\n'), "\n}");-}-/**- * GraphQL schema define root types for each type of operation. These types are- * the same as any other type and can be named in any manner, however there is- * a common naming convention:- *- * schema {- * query: Query- * mutation: Mutation- * }- *- * When using this naming convention, the schema description can be omitted.- */---function isSchemaOfCommonNames(schema) {- var queryType = schema.getQueryType();-- if (queryType && queryType.name !== 'Query') {- return false;- }-- var mutationType = schema.getMutationType();-- if (mutationType && mutationType.name !== 'Mutation') {- return false;- }-- var subscriptionType = schema.getSubscriptionType();-- if (subscriptionType && subscriptionType.name !== 'Subscription') {- return false;- }-- return true;-}--function printType(type, options) {- if (isScalarType(type)) {- return printScalar(type, options);- }-- if (isObjectType(type)) {- return printObject(type, options);- }-- if (isInterfaceType(type)) {- return printInterface(type, options);- }-- if (isUnionType(type)) {- return printUnion(type, options);- }-- if (isEnumType(type)) {- return printEnum(type, options);- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isInputObjectType(type)) {- return printInputObject(type, options);- } // istanbul ignore next (Not reachable. All possible types have been considered)--- invariant(0, 'Unexpected type: ' + inspect(type));-}--function printScalar(type, options) {- return printDescription(options, type) + "scalar ".concat(type.name) + printSpecifiedByUrl(type);-}--function printImplementedInterfaces(type) {- var interfaces = type.getInterfaces();- return interfaces.length ? ' implements ' + interfaces.map(function (i) {- return i.name;- }).join(' & ') : '';-}--function printObject(type, options) {- return printDescription(options, type) + "type ".concat(type.name) + printImplementedInterfaces(type) + printFields(options, type);-}--function printInterface(type, options) {- return printDescription(options, type) + "interface ".concat(type.name) + printImplementedInterfaces(type) + printFields(options, type);-}--function printUnion(type, options) {- var types = type.getTypes();- var possibleTypes = types.length ? ' = ' + types.join(' | ') : '';- return printDescription(options, type) + 'union ' + type.name + possibleTypes;-}--function printEnum(type, options) {- var values = type.getValues().map(function (value, i) {- return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value);- });- return printDescription(options, type) + "enum ".concat(type.name) + printBlock(values);-}--function printInputObject(type, options) {- var fields = objectValues(type.getFields()).map(function (f, i) {- return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f);- });- return printDescription(options, type) + "input ".concat(type.name) + printBlock(fields);-}--function printFields(options, type) {- var fields = objectValues(type.getFields()).map(function (f, i) {- return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f);- });- return printBlock(fields);-}--function printBlock(items) {- return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : '';-}--function printArgs(options, args) {- var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';-- if (args.length === 0) {- return '';- } // If every arg does not have a description, print them on one line.--- if (args.every(function (arg) {- return !arg.description;- })) {- return '(' + args.map(printInputValue).join(', ') + ')';- }-- return '(\n' + args.map(function (arg, i) {- return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg);- }).join('\n') + '\n' + indentation + ')';-}--function printInputValue(arg) {- var defaultAST = astFromValue(arg.defaultValue, arg.type);- var argDecl = arg.name + ': ' + String(arg.type);-- if (defaultAST) {- argDecl += " = ".concat(print(defaultAST));- }-- return argDecl;-}--function printDirective(directive, options) {- return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | ');-}--function printDeprecated(fieldOrEnumVal) {- if (!fieldOrEnumVal.isDeprecated) {- return '';- }-- var reason = fieldOrEnumVal.deprecationReason;- var reasonAST = astFromValue(reason, GraphQLString);-- if (reasonAST && reason !== DEFAULT_DEPRECATION_REASON) {- return ' @deprecated(reason: ' + print(reasonAST) + ')';- }-- return ' @deprecated';-}--function printSpecifiedByUrl(scalar) {- if (scalar.specifiedByUrl == null) {- return '';- }-- var url = scalar.specifiedByUrl;- var urlAST = astFromValue(url, GraphQLString);- urlAST || invariant(0, 'Unexpected null value returned from `astFromValue` for specifiedByUrl');- return ' @specifiedBy(url: ' + print(urlAST) + ')';-}--function printDescription(options, def) {- var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';- var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;- var description = def.description;-- if (description == null) {- return '';- }-- if ((options === null || options === void 0 ? void 0 : options.commentDescriptions) === true) {- return printDescriptionWithComments(description, indentation, firstInBlock);- }-- var preferMultipleLines = description.length > 70;- var blockString = printBlockString(description, '', preferMultipleLines);- var prefix = indentation && !firstInBlock ? '\n' + indentation : indentation;- return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n';-}--function printDescriptionWithComments(description, indentation, firstInBlock) {- var prefix = indentation && !firstInBlock ? '\n' : '';- var comment = description.split('\n').map(function (line) {- return indentation + (line !== '' ? '# ' + line : '#');- }).join('\n');- return prefix + comment + '\n';-}--/**- * Provided a collection of ASTs, presumably each from different files,- * concatenate the ASTs together into batched AST, useful for validating many- * GraphQL source files which together represent one conceptual application.- */-function concatAST(asts) {- return {- kind: 'Document',- definitions: flatMap(asts, function (ast) {- return ast.definitions;- })- };-}--/**- * separateOperations accepts a single AST document which may contain many- * operations and fragments and returns a collection of AST documents each of- * which contains a single operation as well the fragment definitions it- * refers to.- */--function separateOperations(documentAST) {- var operations = [];- var depGraph = Object.create(null);- var fromName; // Populate metadata and build a dependency graph.-- visit(documentAST, {- OperationDefinition: function OperationDefinition(node) {- fromName = opName(node);- operations.push(node);- },- FragmentDefinition: function FragmentDefinition(node) {- fromName = node.name.value;- },- FragmentSpread: function FragmentSpread(node) {- var toName = node.name.value;- var dependents = depGraph[fromName];-- if (dependents === undefined) {- dependents = depGraph[fromName] = Object.create(null);- }-- dependents[toName] = true;- }- }); // For each operation, produce a new synthesized AST which includes only what- // is necessary for completing that operation.-- var separatedDocumentASTs = Object.create(null);-- var _loop = function _loop(_i2) {- var operation = operations[_i2];- var operationName = opName(operation);- var dependencies = Object.create(null);- collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted- // to retain the same order as the original document.-- separatedDocumentASTs[operationName] = {- kind: Kind.DOCUMENT,- definitions: documentAST.definitions.filter(function (node) {- return node === operation || node.kind === Kind.FRAGMENT_DEFINITION && dependencies[node.name.value];- })- };- };-- for (var _i2 = 0; _i2 < operations.length; _i2++) {- _loop(_i2);- }-- return separatedDocumentASTs;-}--// Provides the empty string for anonymous operations.-function opName(operation) {- return operation.name ? operation.name.value : '';-} // From a dependency graph, collects a list of transitive dependencies by-// recursing through a dependency graph.---function collectTransitiveDependencies(collected, depGraph, fromName) {- var immediateDeps = depGraph[fromName];-- if (immediateDeps) {- for (var _i4 = 0, _Object$keys2 = Object.keys(immediateDeps); _i4 < _Object$keys2.length; _i4++) {- var toName = _Object$keys2[_i4];-- if (!collected[toName]) {- collected[toName] = true;- collectTransitiveDependencies(collected, depGraph, toName);- }- }- }-}--/**- * Strips characters that are not significant to the validity or execution- * of a GraphQL document:- * - UnicodeBOM- * - WhiteSpace- * - LineTerminator- * - Comment- * - Comma- * - BlockString indentation- *- * Note: It is required to have a delimiter character between neighboring- * non-punctuator tokens and this function always uses single space as delimiter.- *- * It is guaranteed that both input and output documents if parsed would result- * in the exact same AST except for nodes location.- *- * Warning: It is guaranteed that this function will always produce stable results.- * However, it's not guaranteed that it will stay the same between different- * releases due to bugfixes or changes in the GraphQL specification.- *- * Query example:- *- * query SomeQuery($foo: String!, $bar: String) {- * someField(foo: $foo, bar: $bar) {- * a- * b {- * c- * d- * }- * }- * }- *- * Becomes:- *- * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}- *- * SDL example:- *- * """- * Type description- * """- * type Foo {- * """- * Field description- * """- * bar: String- * }- *- * Becomes:- *- * """Type description""" type Foo{"""Field description""" bar:String}- */--function stripIgnoredCharacters(source) {- var sourceObj = typeof source === 'string' ? new Source(source) : source;-- if (!(sourceObj instanceof Source)) {- throw new TypeError("Must provide string or Source. Received: ".concat(inspect(sourceObj), "."));- }-- var body = sourceObj.body;- var lexer = new Lexer(sourceObj);- var strippedBody = '';- var wasLastAddedTokenNonPunctuator = false;-- while (lexer.advance().kind !== TokenKind.EOF) {- var currentToken = lexer.token;- var tokenKind = currentToken.kind;- /**- * Every two non-punctuator tokens should have space between them.- * Also prevent case of non-punctuator token following by spread resulting- * in invalid token (e.g. `1...` is invalid Float token).- */-- var isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind);-- if (wasLastAddedTokenNonPunctuator) {- if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) {- strippedBody += ' ';- }- }-- var tokenBody = body.slice(currentToken.start, currentToken.end);-- if (tokenKind === TokenKind.BLOCK_STRING) {- strippedBody += dedentBlockString(tokenBody);- } else {- strippedBody += tokenBody;- }-- wasLastAddedTokenNonPunctuator = isNonPunctuator;- }-- return strippedBody;-}--function dedentBlockString(blockStr) {- // skip leading and trailing triple quotations- var rawStr = blockStr.slice(3, -3);- var body = dedentBlockStringValue(rawStr);- var lines = body.split(/\r\n|[\n\r]/g);-- if (getBlockStringIndentation(lines) > 0) {- body = '\n' + body;- }-- var lastChar = body[body.length - 1];- var hasTrailingQuote = lastChar === '"' && body.slice(-4) !== '\\"""';-- if (hasTrailingQuote || lastChar === '\\') {- body += '\n';- }-- return '"""' + body + '"""';-}--function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }--function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty$8(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }--function _defineProperty$8(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }-var BreakingChangeType = Object.freeze({- TYPE_REMOVED: 'TYPE_REMOVED',- TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND',- TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION',- VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM',- REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED',- IMPLEMENTED_INTERFACE_REMOVED: 'IMPLEMENTED_INTERFACE_REMOVED',- FIELD_REMOVED: 'FIELD_REMOVED',- FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND',- REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED',- ARG_REMOVED: 'ARG_REMOVED',- ARG_CHANGED_KIND: 'ARG_CHANGED_KIND',- DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED',- DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED',- REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED',- DIRECTIVE_REPEATABLE_REMOVED: 'DIRECTIVE_REPEATABLE_REMOVED',- DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED'-});-var DangerousChangeType = Object.freeze({- VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM',- TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION',- OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED',- OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED',- IMPLEMENTED_INTERFACE_ADDED: 'IMPLEMENTED_INTERFACE_ADDED',- ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE'-});--/**- * Given two schemas, returns an Array containing descriptions of all the types- * of breaking changes covered by the other functions down below.- */-function findBreakingChanges(oldSchema, newSchema) {- var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {- return change.type in BreakingChangeType;- });- return breakingChanges;-}-/**- * Given two schemas, returns an Array containing descriptions of all the types- * of potentially dangerous changes covered by the other functions down below.- */--function findDangerousChanges(oldSchema, newSchema) {- var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {- return change.type in DangerousChangeType;- });- return dangerousChanges;-}--function findSchemaChanges(oldSchema, newSchema) {- return [].concat(findTypeChanges(oldSchema, newSchema), findDirectiveChanges(oldSchema, newSchema));-}--function findDirectiveChanges(oldSchema, newSchema) {- var schemaChanges = [];- var directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives());-- for (var _i2 = 0, _directivesDiff$remov2 = directivesDiff.removed; _i2 < _directivesDiff$remov2.length; _i2++) {- var oldDirective = _directivesDiff$remov2[_i2];- schemaChanges.push({- type: BreakingChangeType.DIRECTIVE_REMOVED,- description: "".concat(oldDirective.name, " was removed.")- });- }-- for (var _i4 = 0, _directivesDiff$persi2 = directivesDiff.persisted; _i4 < _directivesDiff$persi2.length; _i4++) {- var _ref2 = _directivesDiff$persi2[_i4];- var _oldDirective = _ref2[0];- var newDirective = _ref2[1];- var argsDiff = diff(_oldDirective.args, newDirective.args);-- for (var _i6 = 0, _argsDiff$added2 = argsDiff.added; _i6 < _argsDiff$added2.length; _i6++) {- var newArg = _argsDiff$added2[_i6];-- if (isRequiredArgument(newArg)) {- schemaChanges.push({- type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED,- description: "A required arg ".concat(newArg.name, " on directive ").concat(_oldDirective.name, " was added.")- });- }- }-- for (var _i8 = 0, _argsDiff$removed2 = argsDiff.removed; _i8 < _argsDiff$removed2.length; _i8++) {- var oldArg = _argsDiff$removed2[_i8];- schemaChanges.push({- type: BreakingChangeType.DIRECTIVE_ARG_REMOVED,- description: "".concat(oldArg.name, " was removed from ").concat(_oldDirective.name, ".")- });- }-- if (_oldDirective.isRepeatable && !newDirective.isRepeatable) {- schemaChanges.push({- type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED,- description: "Repeatable flag was removed from ".concat(_oldDirective.name, ".")- });- }-- for (var _i10 = 0, _oldDirective$locatio2 = _oldDirective.locations; _i10 < _oldDirective$locatio2.length; _i10++) {- var location = _oldDirective$locatio2[_i10];-- if (newDirective.locations.indexOf(location) === -1) {- schemaChanges.push({- type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED,- description: "".concat(location, " was removed from ").concat(_oldDirective.name, ".")- });- }- }- }-- return schemaChanges;-}--function findTypeChanges(oldSchema, newSchema) {- var schemaChanges = [];- var typesDiff = diff(objectValues(oldSchema.getTypeMap()), objectValues(newSchema.getTypeMap()));-- for (var _i12 = 0, _typesDiff$removed2 = typesDiff.removed; _i12 < _typesDiff$removed2.length; _i12++) {- var oldType = _typesDiff$removed2[_i12];- schemaChanges.push({- type: BreakingChangeType.TYPE_REMOVED,- description: isSpecifiedScalarType(oldType) ? "Standard scalar ".concat(oldType.name, " was removed because it is not referenced anymore.") : "".concat(oldType.name, " was removed.")- });- }-- for (var _i14 = 0, _typesDiff$persisted2 = typesDiff.persisted; _i14 < _typesDiff$persisted2.length; _i14++) {- var _ref4 = _typesDiff$persisted2[_i14];- var _oldType = _ref4[0];- var newType = _ref4[1];-- if (isEnumType(_oldType) && isEnumType(newType)) {- schemaChanges.push.apply(schemaChanges, findEnumTypeChanges(_oldType, newType));- } else if (isUnionType(_oldType) && isUnionType(newType)) {- schemaChanges.push.apply(schemaChanges, findUnionTypeChanges(_oldType, newType));- } else if (isInputObjectType(_oldType) && isInputObjectType(newType)) {- schemaChanges.push.apply(schemaChanges, findInputObjectTypeChanges(_oldType, newType));- } else if (isObjectType(_oldType) && isObjectType(newType)) {- schemaChanges.push.apply(schemaChanges, findFieldChanges(_oldType, newType).concat(findImplementedInterfacesChanges(_oldType, newType)));- } else if (isInterfaceType(_oldType) && isInterfaceType(newType)) {- schemaChanges.push.apply(schemaChanges, findFieldChanges(_oldType, newType).concat(findImplementedInterfacesChanges(_oldType, newType)));- } else if (_oldType.constructor !== newType.constructor) {- schemaChanges.push({- type: BreakingChangeType.TYPE_CHANGED_KIND,- description: "".concat(_oldType.name, " changed from ") + "".concat(typeKindName(_oldType), " to ").concat(typeKindName(newType), ".")- });- }- }-- return schemaChanges;-}--function findInputObjectTypeChanges(oldType, newType) {- var schemaChanges = [];- var fieldsDiff = diff(objectValues(oldType.getFields()), objectValues(newType.getFields()));-- for (var _i16 = 0, _fieldsDiff$added2 = fieldsDiff.added; _i16 < _fieldsDiff$added2.length; _i16++) {- var newField = _fieldsDiff$added2[_i16];-- if (isRequiredInputField(newField)) {- schemaChanges.push({- type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED,- description: "A required field ".concat(newField.name, " on input type ").concat(oldType.name, " was added.")- });- } else {- schemaChanges.push({- type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED,- description: "An optional field ".concat(newField.name, " on input type ").concat(oldType.name, " was added.")- });- }- }-- for (var _i18 = 0, _fieldsDiff$removed2 = fieldsDiff.removed; _i18 < _fieldsDiff$removed2.length; _i18++) {- var oldField = _fieldsDiff$removed2[_i18];- schemaChanges.push({- type: BreakingChangeType.FIELD_REMOVED,- description: "".concat(oldType.name, ".").concat(oldField.name, " was removed.")- });- }-- for (var _i20 = 0, _fieldsDiff$persisted2 = fieldsDiff.persisted; _i20 < _fieldsDiff$persisted2.length; _i20++) {- var _ref6 = _fieldsDiff$persisted2[_i20];- var _oldField = _ref6[0];- var _newField = _ref6[1];- var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(_oldField.type, _newField.type);-- if (!isSafe) {- schemaChanges.push({- type: BreakingChangeType.FIELD_CHANGED_KIND,- description: "".concat(oldType.name, ".").concat(_oldField.name, " changed type from ") + "".concat(String(_oldField.type), " to ").concat(String(_newField.type), ".")- });- }- }-- return schemaChanges;-}--function findUnionTypeChanges(oldType, newType) {- var schemaChanges = [];- var possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes());-- for (var _i22 = 0, _possibleTypesDiff$ad2 = possibleTypesDiff.added; _i22 < _possibleTypesDiff$ad2.length; _i22++) {- var newPossibleType = _possibleTypesDiff$ad2[_i22];- schemaChanges.push({- type: DangerousChangeType.TYPE_ADDED_TO_UNION,- description: "".concat(newPossibleType.name, " was added to union type ").concat(oldType.name, ".")- });- }-- for (var _i24 = 0, _possibleTypesDiff$re2 = possibleTypesDiff.removed; _i24 < _possibleTypesDiff$re2.length; _i24++) {- var oldPossibleType = _possibleTypesDiff$re2[_i24];- schemaChanges.push({- type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,- description: "".concat(oldPossibleType.name, " was removed from union type ").concat(oldType.name, ".")- });- }-- return schemaChanges;-}--function findEnumTypeChanges(oldType, newType) {- var schemaChanges = [];- var valuesDiff = diff(oldType.getValues(), newType.getValues());-- for (var _i26 = 0, _valuesDiff$added2 = valuesDiff.added; _i26 < _valuesDiff$added2.length; _i26++) {- var newValue = _valuesDiff$added2[_i26];- schemaChanges.push({- type: DangerousChangeType.VALUE_ADDED_TO_ENUM,- description: "".concat(newValue.name, " was added to enum type ").concat(oldType.name, ".")- });- }-- for (var _i28 = 0, _valuesDiff$removed2 = valuesDiff.removed; _i28 < _valuesDiff$removed2.length; _i28++) {- var oldValue = _valuesDiff$removed2[_i28];- schemaChanges.push({- type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,- description: "".concat(oldValue.name, " was removed from enum type ").concat(oldType.name, ".")- });- }-- return schemaChanges;-}--function findImplementedInterfacesChanges(oldType, newType) {- var schemaChanges = [];- var interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces());-- for (var _i30 = 0, _interfacesDiff$added2 = interfacesDiff.added; _i30 < _interfacesDiff$added2.length; _i30++) {- var newInterface = _interfacesDiff$added2[_i30];- schemaChanges.push({- type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED,- description: "".concat(newInterface.name, " added to interfaces implemented by ").concat(oldType.name, ".")- });- }-- for (var _i32 = 0, _interfacesDiff$remov2 = interfacesDiff.removed; _i32 < _interfacesDiff$remov2.length; _i32++) {- var oldInterface = _interfacesDiff$remov2[_i32];- schemaChanges.push({- type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED,- description: "".concat(oldType.name, " no longer implements interface ").concat(oldInterface.name, ".")- });- }-- return schemaChanges;-}--function findFieldChanges(oldType, newType) {- var schemaChanges = [];- var fieldsDiff = diff(objectValues(oldType.getFields()), objectValues(newType.getFields()));-- for (var _i34 = 0, _fieldsDiff$removed4 = fieldsDiff.removed; _i34 < _fieldsDiff$removed4.length; _i34++) {- var oldField = _fieldsDiff$removed4[_i34];- schemaChanges.push({- type: BreakingChangeType.FIELD_REMOVED,- description: "".concat(oldType.name, ".").concat(oldField.name, " was removed.")- });- }-- for (var _i36 = 0, _fieldsDiff$persisted4 = fieldsDiff.persisted; _i36 < _fieldsDiff$persisted4.length; _i36++) {- var _ref8 = _fieldsDiff$persisted4[_i36];- var _oldField2 = _ref8[0];- var newField = _ref8[1];- schemaChanges.push.apply(schemaChanges, findArgChanges(oldType, _oldField2, newField));- var isSafe = isChangeSafeForObjectOrInterfaceField(_oldField2.type, newField.type);-- if (!isSafe) {- schemaChanges.push({- type: BreakingChangeType.FIELD_CHANGED_KIND,- description: "".concat(oldType.name, ".").concat(_oldField2.name, " changed type from ") + "".concat(String(_oldField2.type), " to ").concat(String(newField.type), ".")- });- }- }-- return schemaChanges;-}--function findArgChanges(oldType, oldField, newField) {- var schemaChanges = [];- var argsDiff = diff(oldField.args, newField.args);-- for (var _i38 = 0, _argsDiff$removed4 = argsDiff.removed; _i38 < _argsDiff$removed4.length; _i38++) {- var oldArg = _argsDiff$removed4[_i38];- schemaChanges.push({- type: BreakingChangeType.ARG_REMOVED,- description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(oldArg.name, " was removed.")- });- }-- for (var _i40 = 0, _argsDiff$persisted2 = argsDiff.persisted; _i40 < _argsDiff$persisted2.length; _i40++) {- var _ref10 = _argsDiff$persisted2[_i40];- var _oldArg = _ref10[0];- var newArg = _ref10[1];- var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(_oldArg.type, newArg.type);-- if (!isSafe) {- schemaChanges.push({- type: BreakingChangeType.ARG_CHANGED_KIND,- description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " has changed type from ") + "".concat(String(_oldArg.type), " to ").concat(String(newArg.type), ".")- });- } else if (_oldArg.defaultValue !== undefined) {- if (newArg.defaultValue === undefined) {- schemaChanges.push({- type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,- description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " defaultValue was removed.")- });- } else {- // Since we looking only for client's observable changes we should- // compare default values in the same representation as they are- // represented inside introspection.- var oldValueStr = stringifyValue(_oldArg.defaultValue, _oldArg.type);- var newValueStr = stringifyValue(newArg.defaultValue, newArg.type);-- if (oldValueStr !== newValueStr) {- schemaChanges.push({- type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,- description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " has changed defaultValue from ").concat(oldValueStr, " to ").concat(newValueStr, ".")- });- }- }- }- }-- for (var _i42 = 0, _argsDiff$added4 = argsDiff.added; _i42 < _argsDiff$added4.length; _i42++) {- var _newArg = _argsDiff$added4[_i42];-- if (isRequiredArgument(_newArg)) {- schemaChanges.push({- type: BreakingChangeType.REQUIRED_ARG_ADDED,- description: "A required arg ".concat(_newArg.name, " on ").concat(oldType.name, ".").concat(oldField.name, " was added.")- });- } else {- schemaChanges.push({- type: DangerousChangeType.OPTIONAL_ARG_ADDED,- description: "An optional arg ".concat(_newArg.name, " on ").concat(oldType.name, ".").concat(oldField.name, " was added.")- });- }- }-- return schemaChanges;-}--function isChangeSafeForObjectOrInterfaceField(oldType, newType) {- if (isListType(oldType)) {- return (// if they're both lists, make sure the underlying types are compatible- isListType(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || // moving from nullable to non-null of the same underlying type is safe- isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)- );- }-- if (isNonNullType(oldType)) {- // if they're both non-null, make sure the underlying types are compatible- return isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType);- }-- return (// if they're both named types, see if their names are equivalent- isNamedType(newType) && oldType.name === newType.name || // moving from nullable to non-null of the same underlying type is safe- isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)- );-}--function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) {- if (isListType(oldType)) {- // if they're both lists, make sure the underlying types are compatible- return isListType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType);- }-- if (isNonNullType(oldType)) {- return (// if they're both non-null, make sure the underlying types are- // compatible- isNonNullType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || // moving from non-null to nullable of the same underlying type is safe- !isNonNullType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)- );- } // if they're both named types, see if their names are equivalent--- return isNamedType(newType) && oldType.name === newType.name;-}--function typeKindName(type) {- if (isScalarType(type)) {- return 'a Scalar type';- }-- if (isObjectType(type)) {- return 'an Object type';- }-- if (isInterfaceType(type)) {- return 'an Interface type';- }-- if (isUnionType(type)) {- return 'a Union type';- }-- if (isEnumType(type)) {- return 'an Enum type';- } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')--- if (isInputObjectType(type)) {- return 'an Input type';- } // istanbul ignore next (Not reachable. All possible named types have been considered)--- invariant(0, 'Unexpected type: ' + inspect(type));-}--function stringifyValue(value, type) {- var ast = astFromValue(value, type);- ast != null || invariant(0);- var sortedAST = visit(ast, {- ObjectValue: function ObjectValue(objectNode) {- var fields = [].concat(objectNode.fields).sort(function (fieldA, fieldB) {- return fieldA.name.value.localeCompare(fieldB.name.value);- });- return _objectSpread$6(_objectSpread$6({}, objectNode), {}, {- fields: fields- });- }- });- return print(sortedAST);-}--function diff(oldArray, newArray) {- var added = [];- var removed = [];- var persisted = [];- var oldMap = keyMap(oldArray, function (_ref11) {- var name = _ref11.name;- return name;- });- var newMap = keyMap(newArray, function (_ref12) {- var name = _ref12.name;- return name;- });-- for (var _i44 = 0; _i44 < oldArray.length; _i44++) {- var oldItem = oldArray[_i44];- var newItem = newMap[oldItem.name];-- if (newItem === undefined) {- removed.push(oldItem);- } else {- persisted.push([oldItem, newItem]);- }- }-- for (var _i46 = 0; _i46 < newArray.length; _i46++) {- var _newItem = newArray[_i46];-- if (oldMap[_newItem.name] === undefined) {- added.push(_newItem);- }- }-- return {- added: added,- persisted: persisted,- removed: removed- };-}--/**- * A validation rule which reports deprecated usages.- *- * Returns a list of GraphQLError instances describing each deprecated use.- *- * @deprecated Please use `validate` with `NoDeprecatedCustomRule` instead:- *- * ```- * import { validate, NoDeprecatedCustomRule } from 'graphql'- *- * const errors = validate(schema, document, [NoDeprecatedCustomRule])- * ```- */--function findDeprecatedUsages(schema, ast) {- return validate(schema, ast, [NoDeprecatedCustomRule]);-}--/**- * GraphQL.js provides a reference implementation for the GraphQL specification- * but is also a useful utility for operating on GraphQL files and building- * sophisticated tools.- *- * This primary module exports a general purpose function for fulfilling all- * steps of the GraphQL specification in a single operation, but also includes- * utilities for every part of the GraphQL specification:- *- * - Parsing the GraphQL language.- * - Building a GraphQL type schema.- * - Validating a GraphQL request against a type schema.- * - Executing a GraphQL request against a type schema.- *- * This also includes utility functions for operating on GraphQL types and- * GraphQL documents to facilitate building tools.- *- * You may also import from each sub-directory directly. For example, the- * following two import statements are equivalent:- *- * import { parse } from 'graphql';- * import { parse } from 'graphql/language';- */--var graphql$1 = /*#__PURE__*/Object.freeze({- __proto__: null,- version: version,- versionInfo: versionInfo,- graphql: graphql,- graphqlSync: graphqlSync,- GraphQLSchema: GraphQLSchema,- GraphQLDirective: GraphQLDirective,- GraphQLScalarType: GraphQLScalarType,- GraphQLObjectType: GraphQLObjectType,- GraphQLInterfaceType: GraphQLInterfaceType,- GraphQLUnionType: GraphQLUnionType,- GraphQLEnumType: GraphQLEnumType,- GraphQLInputObjectType: GraphQLInputObjectType,- GraphQLList: GraphQLList,- GraphQLNonNull: GraphQLNonNull,- specifiedScalarTypes: specifiedScalarTypes,- GraphQLInt: GraphQLInt,- GraphQLFloat: GraphQLFloat,- GraphQLString: GraphQLString,- GraphQLBoolean: GraphQLBoolean,- GraphQLID: GraphQLID,- specifiedDirectives: specifiedDirectives,- GraphQLIncludeDirective: GraphQLIncludeDirective,- GraphQLSkipDirective: GraphQLSkipDirective,- GraphQLDeprecatedDirective: GraphQLDeprecatedDirective,- GraphQLSpecifiedByDirective: GraphQLSpecifiedByDirective,- TypeKind: TypeKind,- DEFAULT_DEPRECATION_REASON: DEFAULT_DEPRECATION_REASON,- introspectionTypes: introspectionTypes,- __Schema: __Schema,- __Directive: __Directive,- __DirectiveLocation: __DirectiveLocation,- __Type: __Type,- __Field: __Field,- __InputValue: __InputValue,- __EnumValue: __EnumValue,- __TypeKind: __TypeKind,- SchemaMetaFieldDef: SchemaMetaFieldDef,- TypeMetaFieldDef: TypeMetaFieldDef,- TypeNameMetaFieldDef: TypeNameMetaFieldDef,- isSchema: isSchema,- isDirective: isDirective,- isType: isType,- isScalarType: isScalarType,- isObjectType: isObjectType,- isInterfaceType: isInterfaceType,- isUnionType: isUnionType,- isEnumType: isEnumType,- isInputObjectType: isInputObjectType,- isListType: isListType,- isNonNullType: isNonNullType,- isInputType: isInputType,- isOutputType: isOutputType,- isLeafType: isLeafType,- isCompositeType: isCompositeType,- isAbstractType: isAbstractType,- isWrappingType: isWrappingType,- isNullableType: isNullableType,- isNamedType: isNamedType,- isRequiredArgument: isRequiredArgument,- isRequiredInputField: isRequiredInputField,- isSpecifiedScalarType: isSpecifiedScalarType,- isIntrospectionType: isIntrospectionType,- isSpecifiedDirective: isSpecifiedDirective,- assertSchema: assertSchema,- assertDirective: assertDirective,- assertType: assertType,- assertScalarType: assertScalarType,- assertObjectType: assertObjectType,- assertInterfaceType: assertInterfaceType,- assertUnionType: assertUnionType,- assertEnumType: assertEnumType,- assertInputObjectType: assertInputObjectType,- assertListType: assertListType,- assertNonNullType: assertNonNullType,- assertInputType: assertInputType,- assertOutputType: assertOutputType,- assertLeafType: assertLeafType,- assertCompositeType: assertCompositeType,- assertAbstractType: assertAbstractType,- assertWrappingType: assertWrappingType,- assertNullableType: assertNullableType,- assertNamedType: assertNamedType,- getNullableType: getNullableType,- getNamedType: getNamedType,- validateSchema: validateSchema,- assertValidSchema: assertValidSchema,- Token: Token,- Source: Source,- Location: Location,- getLocation: getLocation,- printLocation: printLocation,- printSourceLocation: printSourceLocation,- Lexer: Lexer,- TokenKind: TokenKind,- parse: parse,- parseValue: parseValue,- parseType: parseType,- print: print,- visit: visit,- visitInParallel: visitInParallel,- getVisitFn: getVisitFn,- BREAK: BREAK,- Kind: Kind,- DirectiveLocation: DirectiveLocation,- isDefinitionNode: isDefinitionNode,- isExecutableDefinitionNode: isExecutableDefinitionNode,- isSelectionNode: isSelectionNode,- isValueNode: isValueNode,- isTypeNode: isTypeNode,- isTypeSystemDefinitionNode: isTypeSystemDefinitionNode,- isTypeDefinitionNode: isTypeDefinitionNode,- isTypeSystemExtensionNode: isTypeSystemExtensionNode,- isTypeExtensionNode: isTypeExtensionNode,- execute: execute,- executeSync: executeSync,- defaultFieldResolver: defaultFieldResolver,- defaultTypeResolver: defaultTypeResolver,- responsePathAsArray: pathToArray,- getDirectiveValues: getDirectiveValues,- subscribe: subscribe,- createSourceEventStream: createSourceEventStream,- validate: validate,- ValidationContext: ValidationContext,- specifiedRules: specifiedRules,- ExecutableDefinitionsRule: ExecutableDefinitionsRule,- FieldsOnCorrectTypeRule: FieldsOnCorrectTypeRule,- FragmentsOnCompositeTypesRule: FragmentsOnCompositeTypesRule,- KnownArgumentNamesRule: KnownArgumentNamesRule,- KnownDirectivesRule: KnownDirectivesRule,- KnownFragmentNamesRule: KnownFragmentNamesRule,- KnownTypeNamesRule: KnownTypeNamesRule,- LoneAnonymousOperationRule: LoneAnonymousOperationRule,- NoFragmentCyclesRule: NoFragmentCyclesRule,- NoUndefinedVariablesRule: NoUndefinedVariablesRule,- NoUnusedFragmentsRule: NoUnusedFragmentsRule,- NoUnusedVariablesRule: NoUnusedVariablesRule,- OverlappingFieldsCanBeMergedRule: OverlappingFieldsCanBeMergedRule,- PossibleFragmentSpreadsRule: PossibleFragmentSpreadsRule,- ProvidedRequiredArgumentsRule: ProvidedRequiredArgumentsRule,- ScalarLeafsRule: ScalarLeafsRule,- SingleFieldSubscriptionsRule: SingleFieldSubscriptionsRule,- UniqueArgumentNamesRule: UniqueArgumentNamesRule,- UniqueDirectivesPerLocationRule: UniqueDirectivesPerLocationRule,- UniqueFragmentNamesRule: UniqueFragmentNamesRule,- UniqueInputFieldNamesRule: UniqueInputFieldNamesRule,- UniqueOperationNamesRule: UniqueOperationNamesRule,- UniqueVariableNamesRule: UniqueVariableNamesRule,- ValuesOfCorrectTypeRule: ValuesOfCorrectTypeRule,- VariablesAreInputTypesRule: VariablesAreInputTypesRule,- VariablesInAllowedPositionRule: VariablesInAllowedPositionRule,- LoneSchemaDefinitionRule: LoneSchemaDefinitionRule,- UniqueOperationTypesRule: UniqueOperationTypesRule,- UniqueTypeNamesRule: UniqueTypeNamesRule,- UniqueEnumValueNamesRule: UniqueEnumValueNamesRule,- UniqueFieldDefinitionNamesRule: UniqueFieldDefinitionNamesRule,- UniqueDirectiveNamesRule: UniqueDirectiveNamesRule,- PossibleTypeExtensionsRule: PossibleTypeExtensionsRule,- NoDeprecatedCustomRule: NoDeprecatedCustomRule,- NoSchemaIntrospectionCustomRule: NoSchemaIntrospectionCustomRule,- GraphQLError: GraphQLError,- syntaxError: syntaxError,- locatedError: locatedError,- printError: printError,- formatError: formatError,- getIntrospectionQuery: getIntrospectionQuery,- getOperationAST: getOperationAST,- getOperationRootType: getOperationRootType,- introspectionFromSchema: introspectionFromSchema,- buildClientSchema: buildClientSchema,- buildASTSchema: buildASTSchema,- buildSchema: buildSchema,- getDescription: getDescription,- extendSchema: extendSchema,- lexicographicSortSchema: lexicographicSortSchema,- printSchema: printSchema,- printType: printType,- printIntrospectionSchema: printIntrospectionSchema,- typeFromAST: typeFromAST,- valueFromAST: valueFromAST,- valueFromASTUntyped: valueFromASTUntyped,- astFromValue: astFromValue,- TypeInfo: TypeInfo,- visitWithTypeInfo: visitWithTypeInfo,- coerceInputValue: coerceInputValue,- concatAST: concatAST,- separateOperations: separateOperations,- stripIgnoredCharacters: stripIgnoredCharacters,- isEqualType: isEqualType,- isTypeSubTypeOf: isTypeSubTypeOf,- doTypesOverlap: doTypesOverlap,- assertValidName: assertValidName,- isValidNameError: isValidNameError,- BreakingChangeType: BreakingChangeType,- DangerousChangeType: DangerousChangeType,- findBreakingChanges: findBreakingChanges,- findDangerousChanges: findDangerousChanges,- findDeprecatedUsages: findDeprecatedUsages-});--/** -Escape RegExp special characters. -You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class. -@example -``` -import escapeStringRegexp = require('escape-string-regexp'); -const escapedString = escapeStringRegexp('How much $ for a 🦄?'); -//=> 'How much \\$ for a 🦄\\?' -new RegExp(escapedString); -``` -*/ -const escapeStringRegexp = (string) => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } - // Escape characters with special meaning either inside or outside character sets. - // Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. - return string - .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') - .replace(/-/g, '\\x2d'); -};--const extractPathRegex = /\s+at.*[(\s](.*)\)?/; -const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -/** -Clean up error stack traces. Removes the mostly unhelpful internal Node.js entries. -@param stack - The `stack` property of an `Error`. -@example -``` -import cleanStack = require('clean-stack'); -const error = new Error('Missing unicorn'); -console.log(error.stack); -// Error: Missing unicorn -// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15) -// at Module._compile (module.js:409:26) -// at Object.Module._extensions..js (module.js:416:10) -// at Module.load (module.js:343:32) -// at Function.Module._load (module.js:300:12) -// at Function.Module.runMain (module.js:441:10) -// at startup (node.js:139:18) -console.log(cleanStack(error.stack)); -// Error: Missing unicorn -// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15) -``` -*/ -const cleanStack = (stack, basePath) => { - const basePathRegex = basePath && new RegExp(`(at | \\()${escapeStringRegexp(basePath)}`, 'g'); - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } - const match = pathMatches[1]; - // Electron - if (match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar')) { - return false; - } - return !pathRegex.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (basePathRegex) { - line = line.replace(basePathRegex, '$1'); - } - return line; - }) - .join('\n'); -};--const cleanInternalStack = (stack) => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, '');--/** -Indent each line in a string. -@param string - The string to indent. -@param count - How many times you want `options.indent` repeated. Default: `1`. -@example -``` -import indentString = require('indent-string'); -indentString('Unicorns\nRainbows', 4); -//=> ' Unicorns\n Rainbows' -indentString('Unicorns\nRainbows', 4, {indent: '♥'}); -//=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows' -``` -*/ -const indentString = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; - if (typeof string !== 'string') { - throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``); - } - if (typeof count !== 'number') { - throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``); - } - if (count < 0) { - throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``); - } - if (typeof options.indent !== 'string') { - throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\``); - } - if (count === 0) { - return string; - } - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - return string.replace(regex, options.indent.repeat(count)); -};--class AggregateError extends Error { - /** - @param errors - If a string, a new `Error` is created with the string as the error message. If a non-Error object, a new `Error` is created with all properties from the object copied over. - @returns An Error that is also an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables) for the individual errors. - @example - ``` - import AggregateError = require('aggregate-error'); - const error = new AggregateError([new Error('foo'), 'bar', {message: 'baz'}]); - throw error; - // AggregateError: - // Error: foo - // at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:33) - // Error: bar - // at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13) - // Error: baz - // at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13) - // at AggregateError (/Users/sindresorhus/dev/aggregate-error/index.js:19:3) - // at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13) - // at Module._compile (module.js:556:32) - // at Object.Module._extensions..js (module.js:565:10) - // at Module.load (module.js:473:32) - // at tryModuleLoad (module.js:432:12) - // at Function.Module._load (module.js:424:3) - // at Module.runMain (module.js:590:10) - // at run (bootstrap_node.js:394:7) - // at startup (bootstrap_node.js:149:9) - for (const individualError of error) { - console.log(individualError); - } - //=> [Error: foo] - //=> [Error: bar] - //=> [Error: baz] - ``` - */ - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } - const normalizedErrors = errors.map(error => { - if (error instanceof Error) { - return error; - } - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } - return new Error(error); - }); - let message = normalizedErrors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString(message, 4); - super(message); - this.name = 'AggregateError'; - Object.defineProperty(this, '_errors', { value: normalizedErrors }); - } - *[Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } -}--const asArray = (fns) => (Array.isArray(fns) ? fns : fns ? [fns] : []);-function isEqual(a, b) {- if (Array.isArray(a) && Array.isArray(b)) {- if (a.length !== b.length) {- return false;- }- for (let index = 0; index < a.length; index++) {- if (a[index] !== b[index]) {- return false;- }- }- return true;- }- return a === b || (!a && !b);-}-function isNotEqual(a, b) {- return !isEqual(a, b);-}-function isDocumentString(str) {- // XXX: is-valid-path or is-glob treat SDL as a valid path- // (`scalar Date` for example)- // this why checking the extension is fast enough- // and prevent from parsing the string in order to find out- // if the string is a SDL- if (/\.[a-z0-9]+$/i.test(str)) {- return false;- }- try {- parse(str);- return true;- }- catch (e) { }- return false;-}-const invalidPathRegex = /[‘“!$%&^<=>`]/;-function isValidPath(str) {- return typeof str === 'string' && !invalidPathRegex.test(str);-}-function compareStrings(a, b) {- if (a.toString() < b.toString()) {- return -1;- }- if (a.toString() > b.toString()) {- return 1;- }- return 0;-}-function nodeToString(a) {- if ('alias' in a) {- return a.alias.value;- }- if ('name' in a) {- return a.name.value;- }- return a.kind;-}-function compareNodes(a, b, customFn) {- const aStr = nodeToString(a);- const bStr = nodeToString(b);- if (typeof customFn === 'function') {- return customFn(aStr, bStr);- }- return compareStrings(aStr, bStr);-}--function debugLog(...args) {- if (process && process.env && process.env.DEBUG && !process.env.GQL_tools_NODEBUG) {- // tslint:disable-next-line: no-console- console.log(...args);- }-}--const MAX_ARRAY_LENGTH$1 = 10;-const MAX_RECURSIVE_DEPTH$1 = 2;-/**- * Used to print values in error messages.- */-function inspect$1(value) {- return formatValue$1(value, []);-}-function formatValue$1(value, seenValues) {- switch (typeof value) {- case 'string':- return JSON.stringify(value);- case 'function':- return value.name ? `[function ${value.name}]` : '[function]';- case 'object':- if (value === null) {- return 'null';- }- return formatObjectValue$1(value, seenValues);- default:- return String(value);- }-}-function formatObjectValue$1(value, previouslySeenValues) {- if (previouslySeenValues.indexOf(value) !== -1) {- return '[Circular]';- }- const seenValues = [...previouslySeenValues, value];- const customInspectFn = getCustomFn$1(value);- if (customInspectFn !== undefined) {- const customValue = customInspectFn.call(value);- // check for infinite recursion- if (customValue !== value) {- return typeof customValue === 'string' ? customValue : formatValue$1(customValue, seenValues);- }- }- else if (Array.isArray(value)) {- return formatArray$1(value, seenValues);- }- return formatObject$1(value, seenValues);-}-function formatObject$1(object, seenValues) {- const keys = Object.keys(object);- if (keys.length === 0) {- return '{}';- }- if (seenValues.length > MAX_RECURSIVE_DEPTH$1) {- return '[' + getObjectTag$1(object) + ']';- }- const properties = keys.map(key => {- const value = formatValue$1(object[key], seenValues);- return key + ': ' + value;- });- return '{ ' + properties.join(', ') + ' }';-}-function formatArray$1(array, seenValues) {- if (array.length === 0) {- return '[]';- }- if (seenValues.length > MAX_RECURSIVE_DEPTH$1) {- return '[Array]';- }- const len = Math.min(MAX_ARRAY_LENGTH$1, array.length);- const remaining = array.length - len;- const items = [];- for (let i = 0; i < len; ++i) {- items.push(formatValue$1(array[i], seenValues));- }- if (remaining === 1) {- items.push('... 1 more item');- }- else if (remaining > 1) {- items.push(`... ${remaining.toString(10)} more items`);- }- return '[' + items.join(', ') + ']';-}-function getCustomFn$1(obj) {- if (typeof obj.inspect === 'function') {- return obj.inspect;- }-}-function getObjectTag$1(obj) {- const tag = Object.prototype.toString- .call(obj)- .replace(/^\[object /, '')- .replace(/]$/, '');- if (tag === 'Object' && typeof obj.constructor === 'function') {- const name = obj.constructor.name;- if (typeof name === 'string' && name !== '') {- return name;- }- }- return tag;-}--/**- * Prepares an object map of argument values given a list of argument- * definitions and list of argument AST nodes.- *- * Note: The returned value is a plain Object with a prototype, since it is- * exposed to user code. Care should be taken to not pull values from the- * Object prototype.- */-function getArgumentValues$1(def, node, variableValues = {}) {- var _a;- const variableMap = Object.entries(variableValues).reduce((prev, [key, value]) => ({- ...prev,- [key]: value,- }), {});- const coercedValues = {};- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition- const argumentNodes = (_a = node.arguments) !== null && _a !== void 0 ? _a : [];- const argNodeMap = argumentNodes.reduce((prev, arg) => ({- ...prev,- [arg.name.value]: arg,- }), {});- for (const argDef of def.args) {- const name = argDef.name;- const argType = argDef.type;- const argumentNode = argNodeMap[name];- if (!argumentNode) {- if (argDef.defaultValue !== undefined) {- coercedValues[name] = argDef.defaultValue;- }- else if (isNonNullType(argType)) {- throw new GraphQLError(`Argument "${name}" of required type "${inspect$1(argType)}" ` + 'was not provided.', node);- }- continue;- }- const valueNode = argumentNode.value;- let isNull = valueNode.kind === Kind.NULL;- if (valueNode.kind === Kind.VARIABLE) {- const variableName = valueNode.name.value;- if (variableValues == null || !(variableName in variableMap)) {- if (argDef.defaultValue !== undefined) {- coercedValues[name] = argDef.defaultValue;- }- else if (isNonNullType(argType)) {- throw new GraphQLError(`Argument "${name}" of required type "${inspect$1(argType)}" ` +- `was provided the variable "$${variableName}" which was not provided a runtime value.`, valueNode);- }- continue;- }- isNull = variableValues[variableName] == null;- }- if (isNull && isNonNullType(argType)) {- throw new GraphQLError(`Argument "${name}" of non-null type "${inspect$1(argType)}" ` + 'must not be null.', valueNode);- }- const coercedValue = valueFromAST(valueNode, argType, variableValues);- if (coercedValue === undefined) {- // Note: ValuesOfCorrectTypeRule validation should catch this before- // execution. This is a runtime check to ensure execution does not- // continue with an invalid argument value.- throw new GraphQLError(`Argument "${name}" has invalid value ${print(valueNode)}.`, valueNode);- }- coercedValues[name] = coercedValue;- }- return coercedValues;-}--function createSchemaDefinition(def, config) {- const schemaRoot = {};- if (def.query) {- schemaRoot.query = def.query.toString();- }- if (def.mutation) {- schemaRoot.mutation = def.mutation.toString();- }- if (def.subscription) {- schemaRoot.subscription = def.subscription.toString();- }- const fields = Object.keys(schemaRoot)- .map(rootType => (schemaRoot[rootType] ? `${rootType}: ${schemaRoot[rootType]}` : null))- .filter(a => a);- if (fields.length) {- return `schema { ${fields.join('\n')} }`;- }- if (config && config.force) {- return ` schema { query: Query } `;- }- return undefined;-}--function printSchemaWithDirectives(schema, _options = {}) {- var _a;- const typesMap = schema.getTypeMap();- const result = [getSchemaDefinition(schema)];- for (const typeName in typesMap) {- const type = typesMap[typeName];- const isPredefinedScalar = isScalarType(type) && isSpecifiedScalarType(type);- const isIntrospection = isIntrospectionType(type);- if (isPredefinedScalar || isIntrospection) {- continue;- }- // KAMIL: we might want to turn on descriptions in future- result.push(print((_a = correctType(typeName, typesMap)) === null || _a === void 0 ? void 0 : _a.astNode));- }- const directives = schema.getDirectives();- for (const directive of directives) {- if (directive.astNode) {- result.push(print(directive.astNode));- }- }- return result.join('\n');-}-function extendDefinition(type) {- switch (type.astNode.kind) {- case Kind.OBJECT_TYPE_DEFINITION:- return {- ...type.astNode,- fields: type.astNode.fields.concat(type.extensionASTNodes.reduce((fields, node) => fields.concat(node.fields), [])),- };- case Kind.INPUT_OBJECT_TYPE_DEFINITION:- return {- ...type.astNode,- fields: type.astNode.fields.concat(type.extensionASTNodes.reduce((fields, node) => fields.concat(node.fields), [])),- };- default:- return type.astNode;- }-}-function correctType(typeName, typesMap) {- var _a;- const type = typesMap[typeName];- type.name = typeName.toString();- if (type.astNode && type.extensionASTNodes) {- type.astNode = type.extensionASTNodes ? extendDefinition(type) : type.astNode;- }- const doc = parse(printType(type));- const fixedAstNode = doc.definitions[0];- const originalAstNode = type === null || type === void 0 ? void 0 : type.astNode;- if (originalAstNode) {- fixedAstNode.directives = originalAstNode === null || originalAstNode === void 0 ? void 0 : originalAstNode.directives;- if (fixedAstNode && 'fields' in fixedAstNode && originalAstNode && 'fields' in originalAstNode) {- for (const fieldDefinitionNode of fixedAstNode.fields) {- const originalFieldDefinitionNode = originalAstNode.fields.find(field => field.name.value === fieldDefinitionNode.name.value);- fieldDefinitionNode.directives = originalFieldDefinitionNode === null || originalFieldDefinitionNode === void 0 ? void 0 : originalFieldDefinitionNode.directives;- if (fieldDefinitionNode &&- 'arguments' in fieldDefinitionNode &&- originalFieldDefinitionNode &&- 'arguments' in originalFieldDefinitionNode) {- for (const argument of fieldDefinitionNode.arguments) {- const originalArgumentNode = (_a = originalFieldDefinitionNode.arguments) === null || _a === void 0 ? void 0 : _a.find(arg => arg.name.value === argument.name.value);- argument.directives = originalArgumentNode.directives;- }- }- }- }- else if (fixedAstNode && 'values' in fixedAstNode && originalAstNode && 'values' in originalAstNode) {- for (const valueDefinitionNode of fixedAstNode.values) {- const originalValueDefinitionNode = originalAstNode.values.find(valueNode => valueNode.name.value === valueDefinitionNode.name.value);- valueDefinitionNode.directives = originalValueDefinitionNode === null || originalValueDefinitionNode === void 0 ? void 0 : originalValueDefinitionNode.directives;- }- }- }- type.astNode = fixedAstNode;- return type;-}-function getSchemaDefinition(schema) {- if (!Object.getOwnPropertyDescriptor(schema, 'astNode').get && schema.astNode) {- return print(schema.astNode);- }- else {- return createSchemaDefinition({- query: schema.getQueryType(),- mutation: schema.getMutationType(),- subscription: schema.getSubscriptionType(),- });- }-}--function buildFixedSchema(schema, options) {- return buildSchema(printSchemaWithDirectives(schema, options), {- noLocation: true,- ...(options || {}),- });-}-function fixSchemaAst(schema, options) {- let schemaWithValidAst;- if (!schema.astNode) {- Object.defineProperty(schema, 'astNode', {- get() {- if (!schemaWithValidAst) {- schemaWithValidAst = buildFixedSchema(schema, options);- }- return schemaWithValidAst.astNode;- },- });- }- if (!schema.extensionASTNodes) {- Object.defineProperty(schema, 'extensionASTNodes', {- get() {- if (!schemaWithValidAst) {- schemaWithValidAst = buildFixedSchema(schema, options);- }- return schemaWithValidAst.extensionASTNodes;- },- });- }- return schema;-}--/**- * Produces the value of a block string from its parsed raw value, similar to- * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.- *- * This implements the GraphQL spec's BlockStringValue() static algorithm.- *- * @internal- */-function dedentBlockStringValue$1(rawString) {- // Expand a block string's raw value into independent lines.- var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.-- var commonIndent = getBlockStringIndentation$1(lines);-- if (commonIndent !== 0) {- for (var i = 1; i < lines.length; i++) {- lines[i] = lines[i].slice(commonIndent);- }- } // Remove leading and trailing blank lines.--- while (lines.length > 0 && isBlank$1(lines[0])) {- lines.shift();- }-- while (lines.length > 0 && isBlank$1(lines[lines.length - 1])) {- lines.pop();- } // Return a string of the lines joined with U+000A.--- return lines.join('\n');-}-/**- * @internal- */--function getBlockStringIndentation$1(lines) {- var commonIndent = null;-- for (var i = 1; i < lines.length; i++) {- var line = lines[i];- var indent = leadingWhitespace$1(line);-- if (indent === line.length) {- continue; // skip empty lines- }-- if (commonIndent === null || indent < commonIndent) {- commonIndent = indent;-- if (commonIndent === 0) {- break;- }- }- }-- return commonIndent === null ? 0 : commonIndent;-}--function leadingWhitespace$1(str) {- var i = 0;-- while (i < str.length && (str[i] === ' ' || str[i] === '\t')) {- i++;- }-- return i;-}--function isBlank$1(str) {- return leadingWhitespace$1(str) === str.length;-}--function parseGraphQLSDL(location, rawSDL, options = {}) {- let document;- const sdl = rawSDL;- let sdlModified = false;- try {- if (options.commentDescriptions && sdl.includes('#')) {- sdlModified = true;- document = transformCommentsToDescriptions(rawSDL, options);- // If noLocation=true, we need to make sure to print and parse it again, to remove locations,- // since `transformCommentsToDescriptions` must have locations set in order to transform the comments- // into descriptions.- if (options.noLocation) {- document = parse(print(document), options);- }- }- else {- document = parse(new Source(sdl, location), options);- }- }- catch (e) {- if (e.message.includes('EOF')) {- document = {- kind: Kind.DOCUMENT,- definitions: [],- };- }- else {- throw e;- }- }- return {- location,- document,- rawSDL: sdlModified ? print(document) : sdl,- };-}-function getLeadingCommentBlock$1(node) {- const loc = node.loc;- if (!loc) {- return;- }- const comments = [];- let token = loc.startToken.prev;- while (token != null &&- token.kind === TokenKind.COMMENT &&- token.next &&- token.prev &&- token.line + 1 === token.next.line &&- token.line !== token.prev.line) {- const value = String(token.value);- comments.push(value);- token = token.prev;- }- return comments.length > 0 ? comments.reverse().join('\n') : undefined;-}-function transformCommentsToDescriptions(sourceSdl, options = {}) {- const parsedDoc = parse(sourceSdl, {- ...options,- noLocation: false,- });- const modifiedDoc = visit(parsedDoc, {- leave: (node) => {- if (isDescribable(node)) {- const rawValue = getLeadingCommentBlock$1(node);- if (rawValue !== undefined) {- const commentsBlock = dedentBlockStringValue$1('\n' + rawValue);- const isBlock = commentsBlock.includes('\n');- if (!node.description) {- return {- ...node,- description: {- kind: Kind.STRING,- value: commentsBlock,- block: isBlock,- },- };- }- else {- return {- ...node,- description: {- ...node.description,- value: node.description.value + '\n' + commentsBlock,- block: true,- },- };- }- }- }- },- });- return modifiedDoc;-}-function isDescribable(node) {- return (isTypeSystemDefinitionNode(node) ||- node.kind === Kind.FIELD_DEFINITION ||- node.kind === Kind.INPUT_VALUE_DEFINITION ||- node.kind === Kind.ENUM_VALUE_DEFINITION);-}--function stripBOM(content) {- content = content.toString();- // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)- // because the buffer-to-string conversion in `fs.readFileSync()`- // translates it to FEFF, the UTF-16 BOM.- if (content.charCodeAt(0) === 0xfeff) {- content = content.slice(1);- }- return content;-}-function parseBOM(content) {- return JSON.parse(stripBOM(content));-}-function parseGraphQLJSON(location, jsonContent, options) {- let parsedJson = parseBOM(jsonContent);- if (parsedJson.data) {- parsedJson = parsedJson.data;- }- if (parsedJson.kind === 'Document') {- const document = parsedJson;- return {- location,- document,- };- }- else if (parsedJson.__schema) {- const schema = buildClientSchema(parsedJson, options);- const rawSDL = printSchemaWithDirectives(schema, options);- return {- location,- document: parseGraphQLSDL(location, rawSDL, options).document,- rawSDL,- schema,- };- }- throw new Error(`Not valid JSON content`);-}--var VisitSchemaKind;-(function (VisitSchemaKind) {- VisitSchemaKind["TYPE"] = "VisitSchemaKind.TYPE";- VisitSchemaKind["SCALAR_TYPE"] = "VisitSchemaKind.SCALAR_TYPE";- VisitSchemaKind["ENUM_TYPE"] = "VisitSchemaKind.ENUM_TYPE";- VisitSchemaKind["COMPOSITE_TYPE"] = "VisitSchemaKind.COMPOSITE_TYPE";- VisitSchemaKind["OBJECT_TYPE"] = "VisitSchemaKind.OBJECT_TYPE";- VisitSchemaKind["INPUT_OBJECT_TYPE"] = "VisitSchemaKind.INPUT_OBJECT_TYPE";- VisitSchemaKind["ABSTRACT_TYPE"] = "VisitSchemaKind.ABSTRACT_TYPE";- VisitSchemaKind["UNION_TYPE"] = "VisitSchemaKind.UNION_TYPE";- VisitSchemaKind["INTERFACE_TYPE"] = "VisitSchemaKind.INTERFACE_TYPE";- VisitSchemaKind["ROOT_OBJECT"] = "VisitSchemaKind.ROOT_OBJECT";- VisitSchemaKind["QUERY"] = "VisitSchemaKind.QUERY";- VisitSchemaKind["MUTATION"] = "VisitSchemaKind.MUTATION";- VisitSchemaKind["SUBSCRIPTION"] = "VisitSchemaKind.SUBSCRIPTION";-})(VisitSchemaKind || (VisitSchemaKind = {}));-var MapperKind;-(function (MapperKind) {- MapperKind["TYPE"] = "MapperKind.TYPE";- MapperKind["SCALAR_TYPE"] = "MapperKind.SCALAR_TYPE";- MapperKind["ENUM_TYPE"] = "MapperKind.ENUM_TYPE";- MapperKind["COMPOSITE_TYPE"] = "MapperKind.COMPOSITE_TYPE";- MapperKind["OBJECT_TYPE"] = "MapperKind.OBJECT_TYPE";- MapperKind["INPUT_OBJECT_TYPE"] = "MapperKind.INPUT_OBJECT_TYPE";- MapperKind["ABSTRACT_TYPE"] = "MapperKind.ABSTRACT_TYPE";- MapperKind["UNION_TYPE"] = "MapperKind.UNION_TYPE";- MapperKind["INTERFACE_TYPE"] = "MapperKind.INTERFACE_TYPE";- MapperKind["ROOT_OBJECT"] = "MapperKind.ROOT_OBJECT";- MapperKind["QUERY"] = "MapperKind.QUERY";- MapperKind["MUTATION"] = "MapperKind.MUTATION";- MapperKind["SUBSCRIPTION"] = "MapperKind.SUBSCRIPTION";- MapperKind["DIRECTIVE"] = "MapperKind.DIRECTIVE";- MapperKind["FIELD"] = "MapperKind.FIELD";- MapperKind["COMPOSITE_FIELD"] = "MapperKind.COMPOSITE_FIELD";- MapperKind["OBJECT_FIELD"] = "MapperKind.OBJECT_FIELD";- MapperKind["ROOT_FIELD"] = "MapperKind.ROOT_FIELD";- MapperKind["QUERY_ROOT_FIELD"] = "MapperKind.QUERY_ROOT_FIELD";- MapperKind["MUTATION_ROOT_FIELD"] = "MapperKind.MUTATION_ROOT_FIELD";- MapperKind["SUBSCRIPTION_ROOT_FIELD"] = "MapperKind.SUBSCRIPTION_ROOT_FIELD";- MapperKind["INTERFACE_FIELD"] = "MapperKind.INTERFACE_FIELD";- MapperKind["INPUT_OBJECT_FIELD"] = "MapperKind.INPUT_OBJECT_FIELD";- MapperKind["ARGUMENT"] = "MapperKind.ARGUMENT";- MapperKind["ENUM_VALUE"] = "MapperKind.ENUM_VALUE";-})(MapperKind || (MapperKind = {}));-function isNamedStub(type) {- if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {- const fields = type.getFields();- const fieldNames = Object.keys(fields);- return fieldNames.length === 1 && fields[fieldNames[0]].name === '__fake';- }- return false;-}-function getBuiltInForStub(type) {- switch (type.name) {- case GraphQLInt.name:- return GraphQLInt;- case GraphQLFloat.name:- return GraphQLFloat;- case GraphQLString.name:- return GraphQLString;- case GraphQLBoolean.name:- return GraphQLBoolean;- case GraphQLID.name:- return GraphQLID;- default:- return type;- }-}--function rewireTypes(originalTypeMap, directives, options = {- skipPruning: false,-}) {- const referenceTypeMap = Object.create(null);- Object.keys(originalTypeMap).forEach(typeName => {- referenceTypeMap[typeName] = originalTypeMap[typeName];- });- const newTypeMap = Object.create(null);- Object.keys(referenceTypeMap).forEach(typeName => {- const namedType = referenceTypeMap[typeName];- if (namedType == null || typeName.startsWith('__')) {- return;- }- const newName = namedType.name;- if (newName.startsWith('__')) {- return;- }- if (newTypeMap[newName] != null) {- throw new Error(`Duplicate schema type name ${newName}`);- }- newTypeMap[newName] = namedType;- });- Object.keys(newTypeMap).forEach(typeName => {- newTypeMap[typeName] = rewireNamedType(newTypeMap[typeName]);- });- const newDirectives = directives.map(directive => rewireDirective(directive));- // TODO:- // consider removing the default level of pruning in v7,- // see comments below on the pruneTypes function.- return options.skipPruning- ? {- typeMap: newTypeMap,- directives: newDirectives,- }- : pruneTypes(newTypeMap, newDirectives);- function rewireDirective(directive) {- if (isSpecifiedDirective(directive)) {- return directive;- }- const directiveConfig = directive.toConfig();- directiveConfig.args = rewireArgs(directiveConfig.args);- return new GraphQLDirective(directiveConfig);- }- function rewireArgs(args) {- const rewiredArgs = {};- Object.keys(args).forEach(argName => {- const arg = args[argName];- const rewiredArgType = rewireType(arg.type);- if (rewiredArgType != null) {- arg.type = rewiredArgType;- rewiredArgs[argName] = arg;- }- });- return rewiredArgs;- }- function rewireNamedType(type) {- if (isObjectType(type)) {- const config = type.toConfig();- const newConfig = {- ...config,- fields: () => rewireFields(config.fields),- interfaces: () => rewireNamedTypes(config.interfaces),- };- return new GraphQLObjectType(newConfig);- }- else if (isInterfaceType(type)) {- const config = type.toConfig();- const newConfig = {- ...config,- fields: () => rewireFields(config.fields),- };- if ('interfaces' in newConfig) {- newConfig.interfaces = () => rewireNamedTypes(config.interfaces);- }- return new GraphQLInterfaceType(newConfig);- }- else if (isUnionType(type)) {- const config = type.toConfig();- const newConfig = {- ...config,- types: () => rewireNamedTypes(config.types),- };- return new GraphQLUnionType(newConfig);- }- else if (isInputObjectType(type)) {- const config = type.toConfig();- const newConfig = {- ...config,- fields: () => rewireInputFields(config.fields),- };- return new GraphQLInputObjectType(newConfig);- }- else if (isEnumType(type)) {- const enumConfig = type.toConfig();- return new GraphQLEnumType(enumConfig);- }- else if (isScalarType(type)) {- if (isSpecifiedScalarType(type)) {- return type;- }- const scalarConfig = type.toConfig();- return new GraphQLScalarType(scalarConfig);- }- throw new Error(`Unexpected schema type: ${type}`);- }- function rewireFields(fields) {- const rewiredFields = {};- Object.keys(fields).forEach(fieldName => {- const field = fields[fieldName];- const rewiredFieldType = rewireType(field.type);- if (rewiredFieldType != null) {- field.type = rewiredFieldType;- field.args = rewireArgs(field.args);- rewiredFields[fieldName] = field;- }- });- return rewiredFields;- }- function rewireInputFields(fields) {- const rewiredFields = {};- Object.keys(fields).forEach(fieldName => {- const field = fields[fieldName];- const rewiredFieldType = rewireType(field.type);- if (rewiredFieldType != null) {- field.type = rewiredFieldType;- rewiredFields[fieldName] = field;- }- });- return rewiredFields;- }- function rewireNamedTypes(namedTypes) {- const rewiredTypes = [];- namedTypes.forEach(namedType => {- const rewiredType = rewireType(namedType);- if (rewiredType != null) {- rewiredTypes.push(rewiredType);- }- });- return rewiredTypes;- }- function rewireType(type) {- if (isListType(type)) {- const rewiredType = rewireType(type.ofType);- return rewiredType != null ? new GraphQLList(rewiredType) : null;- }- else if (isNonNullType(type)) {- const rewiredType = rewireType(type.ofType);- return rewiredType != null ? new GraphQLNonNull(rewiredType) : null;- }- else if (isNamedType(type)) {- let rewiredType = referenceTypeMap[type.name];- if (rewiredType === undefined) {- rewiredType = isNamedStub(type) ? getBuiltInForStub(type) : rewireNamedType(type);- newTypeMap[rewiredType.name] = referenceTypeMap[type.name] = rewiredType;- }- return rewiredType != null ? newTypeMap[rewiredType.name] : null;- }- return null;- }-}-// TODO:-// consider removing the default level of pruning in v7-//-// Pruning during mapSchema limits the ability to create an unpruned schema, which may be of use-// to some library users. pruning is now recommended via the dedicated pruneSchema function-// which does not force pruning on library users and gives granular control in terms of pruning-// types.-function pruneTypes(typeMap, directives) {- const newTypeMap = {};- const implementedInterfaces = {};- Object.keys(typeMap).forEach(typeName => {- const namedType = typeMap[typeName];- if ('getInterfaces' in namedType) {- namedType.getInterfaces().forEach(iface => {- implementedInterfaces[iface.name] = true;- });- }- });- let prunedTypeMap = false;- const typeNames = Object.keys(typeMap);- for (let i = 0; i < typeNames.length; i++) {- const typeName = typeNames[i];- const type = typeMap[typeName];- if (isObjectType(type) || isInputObjectType(type)) {- // prune types with no fields- if (Object.keys(type.getFields()).length) {- newTypeMap[typeName] = type;- }- else {- prunedTypeMap = true;- }- }- else if (isUnionType(type)) {- // prune unions without underlying types- if (type.getTypes().length) {- newTypeMap[typeName] = type;- }- else {- prunedTypeMap = true;- }- }- else if (isInterfaceType(type)) {- // prune interfaces without fields or without implementations- if (Object.keys(type.getFields()).length && implementedInterfaces[type.name]) {- newTypeMap[typeName] = type;- }- else {- prunedTypeMap = true;- }- }- else {- newTypeMap[typeName] = type;- }- }- // every prune requires another round of healing- return prunedTypeMap ? rewireTypes(newTypeMap, directives) : { typeMap, directives };-}--function transformInputValue(type, value, transformer) {- if (value == null) {- return value;- }- const nullableType = getNullableType(type);- if (isLeafType(nullableType)) {- return transformer(nullableType, value);- }- else if (isListType(nullableType)) {- return value.map((listMember) => transformInputValue(nullableType.ofType, listMember, transformer));- }- else if (isInputObjectType(nullableType)) {- const fields = nullableType.getFields();- const newValue = {};- Object.keys(value).forEach(key => {- newValue[key] = transformInputValue(fields[key].type, value[key], transformer);- });- return newValue;- }- // unreachable, no other possible return value-}-function serializeInputValue(type, value) {- return transformInputValue(type, value, (t, v) => t.serialize(v));-}-function parseInputValue(type, value) {- return transformInputValue(type, value, (t, v) => t.parseValue(v));-}--function mapSchema(schema, schemaMapper = {}) {- const originalTypeMap = schema.getTypeMap();- let newTypeMap = mapDefaultValues(originalTypeMap, schema, serializeInputValue);- newTypeMap = mapTypes(newTypeMap, schema, schemaMapper, type => isLeafType(type));- newTypeMap = mapEnumValues(newTypeMap, schema, schemaMapper);- newTypeMap = mapDefaultValues(newTypeMap, schema, parseInputValue);- newTypeMap = mapTypes(newTypeMap, schema, schemaMapper, type => !isLeafType(type));- newTypeMap = mapFields(newTypeMap, schema, schemaMapper);- newTypeMap = mapArguments(newTypeMap, schema, schemaMapper);- const originalDirectives = schema.getDirectives();- const newDirectives = mapDirectives(originalDirectives, schema, schemaMapper);- const queryType = schema.getQueryType();- const mutationType = schema.getMutationType();- const subscriptionType = schema.getSubscriptionType();- const newQueryTypeName = queryType != null ? (newTypeMap[queryType.name] != null ? newTypeMap[queryType.name].name : undefined) : undefined;- const newMutationTypeName = mutationType != null- ? newTypeMap[mutationType.name] != null- ? newTypeMap[mutationType.name].name- : undefined- : undefined;- const newSubscriptionTypeName = subscriptionType != null- ? newTypeMap[subscriptionType.name] != null- ? newTypeMap[subscriptionType.name].name- : undefined- : undefined;- const { typeMap, directives } = rewireTypes(newTypeMap, newDirectives);- return new GraphQLSchema({- ...schema.toConfig(),- query: newQueryTypeName ? typeMap[newQueryTypeName] : undefined,- mutation: newMutationTypeName ? typeMap[newMutationTypeName] : undefined,- subscription: newSubscriptionTypeName != null ? typeMap[newSubscriptionTypeName] : undefined,- types: Object.keys(typeMap).map(typeName => typeMap[typeName]),- directives,- });-}-function mapTypes(originalTypeMap, schema, schemaMapper, testFn = () => true) {- const newTypeMap = {};- Object.keys(originalTypeMap).forEach(typeName => {- if (!typeName.startsWith('__')) {- const originalType = originalTypeMap[typeName];- if (originalType == null || !testFn(originalType)) {- newTypeMap[typeName] = originalType;- return;- }- const typeMapper = getTypeMapper(schema, schemaMapper, typeName);- if (typeMapper == null) {- newTypeMap[typeName] = originalType;- return;- }- const maybeNewType = typeMapper(originalType, schema);- if (maybeNewType === undefined) {- newTypeMap[typeName] = originalType;- return;- }- newTypeMap[typeName] = maybeNewType;- }- });- return newTypeMap;-}-function mapEnumValues(originalTypeMap, schema, schemaMapper) {- const enumValueMapper = getEnumValueMapper(schemaMapper);- if (!enumValueMapper) {- return originalTypeMap;- }- return mapTypes(originalTypeMap, schema, {- [MapperKind.ENUM_TYPE]: type => {- const config = type.toConfig();- const originalEnumValueConfigMap = config.values;- const newEnumValueConfigMap = {};- Object.keys(originalEnumValueConfigMap).forEach(externalValue => {- const originalEnumValueConfig = originalEnumValueConfigMap[externalValue];- const mappedEnumValue = enumValueMapper(originalEnumValueConfig, type.name, schema, externalValue);- if (mappedEnumValue === undefined) {- newEnumValueConfigMap[externalValue] = originalEnumValueConfig;- }- else if (Array.isArray(mappedEnumValue)) {- const [newExternalValue, newEnumValueConfig] = mappedEnumValue;- newEnumValueConfigMap[newExternalValue] =- newEnumValueConfig === undefined ? originalEnumValueConfig : newEnumValueConfig;- }- else if (mappedEnumValue !== null) {- newEnumValueConfigMap[externalValue] = mappedEnumValue;- }- });- return correctASTNodes(new GraphQLEnumType({- ...config,- values: newEnumValueConfigMap,- }));- },- }, type => isEnumType(type));-}-function mapDefaultValues(originalTypeMap, schema, fn) {- const newTypeMap = mapArguments(originalTypeMap, schema, {- [MapperKind.ARGUMENT]: argumentConfig => {- if (argumentConfig.defaultValue === undefined) {- return argumentConfig;- }- const maybeNewType = getNewType(originalTypeMap, argumentConfig.type);- if (maybeNewType != null) {- return {- ...argumentConfig,- defaultValue: fn(maybeNewType, argumentConfig.defaultValue),- };- }- },- });- return mapFields(newTypeMap, schema, {- [MapperKind.INPUT_OBJECT_FIELD]: inputFieldConfig => {- if (inputFieldConfig.defaultValue === undefined) {- return inputFieldConfig;- }- const maybeNewType = getNewType(newTypeMap, inputFieldConfig.type);- if (maybeNewType != null) {- return {- ...inputFieldConfig,- defaultValue: fn(maybeNewType, inputFieldConfig.defaultValue),- };- }- },- });-}-function getNewType(newTypeMap, type) {- if (isListType(type)) {- const newType = getNewType(newTypeMap, type.ofType);- return newType != null ? new GraphQLList(newType) : null;- }- else if (isNonNullType(type)) {- const newType = getNewType(newTypeMap, type.ofType);- return newType != null ? new GraphQLNonNull(newType) : null;- }- else if (isNamedType(type)) {- const newType = newTypeMap[type.name];- return newType != null ? newType : null;- }- return null;-}-function mapFields(originalTypeMap, schema, schemaMapper) {- const newTypeMap = {};- Object.keys(originalTypeMap).forEach(typeName => {- if (!typeName.startsWith('__')) {- const originalType = originalTypeMap[typeName];- if (!isObjectType(originalType) && !isInterfaceType(originalType) && !isInputObjectType(originalType)) {- newTypeMap[typeName] = originalType;- return;- }- const fieldMapper = getFieldMapper(schema, schemaMapper, typeName);- if (fieldMapper == null) {- newTypeMap[typeName] = originalType;- return;- }- const config = originalType.toConfig();- const originalFieldConfigMap = config.fields;- const newFieldConfigMap = {};- Object.keys(originalFieldConfigMap).forEach(fieldName => {- const originalFieldConfig = originalFieldConfigMap[fieldName];- const mappedField = fieldMapper(originalFieldConfig, fieldName, typeName, schema);- if (mappedField === undefined) {- newFieldConfigMap[fieldName] = originalFieldConfig;- }- else if (Array.isArray(mappedField)) {- const [newFieldName, newFieldConfig] = mappedField;- if (newFieldConfig.astNode != null) {- newFieldConfig.astNode = {- ...newFieldConfig.astNode,- name: {- ...newFieldConfig.astNode.name,- value: newFieldName,- },- };- }- newFieldConfigMap[newFieldName] = newFieldConfig === undefined ? originalFieldConfig : newFieldConfig;- }- else if (mappedField !== null) {- newFieldConfigMap[fieldName] = mappedField;- }- });- if (isObjectType(originalType)) {- newTypeMap[typeName] = correctASTNodes(new GraphQLObjectType({- ...config,- fields: newFieldConfigMap,- }));- }- else if (isInterfaceType(originalType)) {- newTypeMap[typeName] = correctASTNodes(new GraphQLInterfaceType({- ...config,- fields: newFieldConfigMap,- }));- }- else {- newTypeMap[typeName] = correctASTNodes(new GraphQLInputObjectType({- ...config,- fields: newFieldConfigMap,- }));- }- }- });- return newTypeMap;-}-function mapArguments(originalTypeMap, schema, schemaMapper) {- const newTypeMap = {};- Object.keys(originalTypeMap).forEach(typeName => {- if (!typeName.startsWith('__')) {- const originalType = originalTypeMap[typeName];- if (!isObjectType(originalType) && !isInterfaceType(originalType)) {- newTypeMap[typeName] = originalType;- return;- }- const argumentMapper = getArgumentMapper(schemaMapper);- if (argumentMapper == null) {- newTypeMap[typeName] = originalType;- return;- }- const config = originalType.toConfig();- const originalFieldConfigMap = config.fields;- const newFieldConfigMap = {};- Object.keys(originalFieldConfigMap).forEach(fieldName => {- const originalFieldConfig = originalFieldConfigMap[fieldName];- const originalArgumentConfigMap = originalFieldConfig.args;- if (originalArgumentConfigMap == null) {- newFieldConfigMap[fieldName] = originalFieldConfig;- return;- }- const argumentNames = Object.keys(originalArgumentConfigMap);- if (!argumentNames.length) {- newFieldConfigMap[fieldName] = originalFieldConfig;- return;- }- const newArgumentConfigMap = {};- argumentNames.forEach(argumentName => {- const originalArgumentConfig = originalArgumentConfigMap[argumentName];- const mappedArgument = argumentMapper(originalArgumentConfig, fieldName, typeName, schema);- if (mappedArgument === undefined) {- newArgumentConfigMap[argumentName] = originalArgumentConfig;- }- else if (Array.isArray(mappedArgument)) {- const [newArgumentName, newArgumentConfig] = mappedArgument;- newArgumentConfigMap[newArgumentName] = newArgumentConfig;- }- else if (mappedArgument !== null) {- newArgumentConfigMap[argumentName] = mappedArgument;- }- });- newFieldConfigMap[fieldName] = {- ...originalFieldConfig,- args: newArgumentConfigMap,- };- });- if (isObjectType(originalType)) {- newTypeMap[typeName] = new GraphQLObjectType({- ...config,- fields: newFieldConfigMap,- });- }- else if (isInterfaceType(originalType)) {- newTypeMap[typeName] = new GraphQLInterfaceType({- ...config,- fields: newFieldConfigMap,- });- }- else {- newTypeMap[typeName] = new GraphQLInputObjectType({- ...config,- fields: newFieldConfigMap,- });- }- }- });- return newTypeMap;-}-function mapDirectives(originalDirectives, schema, schemaMapper) {- const directiveMapper = getDirectiveMapper(schemaMapper);- if (directiveMapper == null) {- return originalDirectives.slice();- }- const newDirectives = [];- originalDirectives.forEach(directive => {- const mappedDirective = directiveMapper(directive, schema);- if (mappedDirective === undefined) {- newDirectives.push(directive);- }- else if (mappedDirective !== null) {- newDirectives.push(mappedDirective);- }- });- return newDirectives;-}-function getTypeSpecifiers(schema, typeName) {- const type = schema.getType(typeName);- const specifiers = [MapperKind.TYPE];- if (isObjectType(type)) {- specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.OBJECT_TYPE);- const query = schema.getQueryType();- const mutation = schema.getMutationType();- const subscription = schema.getSubscriptionType();- if (query != null && typeName === query.name) {- specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.QUERY);- }- else if (mutation != null && typeName === mutation.name) {- specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.MUTATION);- }- else if (subscription != null && typeName === subscription.name) {- specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.SUBSCRIPTION);- }- }- else if (isInputObjectType(type)) {- specifiers.push(MapperKind.INPUT_OBJECT_TYPE);- }- else if (isInterfaceType(type)) {- specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.ABSTRACT_TYPE, MapperKind.INTERFACE_TYPE);- }- else if (isUnionType(type)) {- specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.ABSTRACT_TYPE, MapperKind.UNION_TYPE);- }- else if (isEnumType(type)) {- specifiers.push(MapperKind.ENUM_TYPE);- }- else if (isScalarType(type)) {- specifiers.push(MapperKind.SCALAR_TYPE);- }- return specifiers;-}-function getTypeMapper(schema, schemaMapper, typeName) {- const specifiers = getTypeSpecifiers(schema, typeName);- let typeMapper;- const stack = [...specifiers];- while (!typeMapper && stack.length > 0) {- const next = stack.pop();- typeMapper = schemaMapper[next];- }- return typeMapper != null ? typeMapper : null;-}-function getFieldSpecifiers(schema, typeName) {- const type = schema.getType(typeName);- const specifiers = [MapperKind.FIELD];- if (isObjectType(type)) {- specifiers.push(MapperKind.COMPOSITE_FIELD, MapperKind.OBJECT_FIELD);- const query = schema.getQueryType();- const mutation = schema.getMutationType();- const subscription = schema.getSubscriptionType();- if (query != null && typeName === query.name) {- specifiers.push(MapperKind.ROOT_FIELD, MapperKind.QUERY_ROOT_FIELD);- }- else if (mutation != null && typeName === mutation.name) {- specifiers.push(MapperKind.ROOT_FIELD, MapperKind.MUTATION_ROOT_FIELD);- }- else if (subscription != null && typeName === subscription.name) {- specifiers.push(MapperKind.ROOT_FIELD, MapperKind.SUBSCRIPTION_ROOT_FIELD);- }- }- else if (isInterfaceType(type)) {- specifiers.push(MapperKind.COMPOSITE_FIELD, MapperKind.INTERFACE_FIELD);- }- else if (isInputObjectType(type)) {- specifiers.push(MapperKind.INPUT_OBJECT_FIELD);- }- return specifiers;-}-function getFieldMapper(schema, schemaMapper, typeName) {- const specifiers = getFieldSpecifiers(schema, typeName);- let fieldMapper;- const stack = [...specifiers];- while (!fieldMapper && stack.length > 0) {- const next = stack.pop();- fieldMapper = schemaMapper[next];- }- return fieldMapper != null ? fieldMapper : null;-}-function getArgumentMapper(schemaMapper) {- const argumentMapper = schemaMapper[MapperKind.ARGUMENT];- return argumentMapper != null ? argumentMapper : null;-}-function getDirectiveMapper(schemaMapper) {- const directiveMapper = schemaMapper[MapperKind.DIRECTIVE];- return directiveMapper != null ? directiveMapper : null;-}-function getEnumValueMapper(schemaMapper) {- const enumValueMapper = schemaMapper[MapperKind.ENUM_VALUE];- return enumValueMapper != null ? enumValueMapper : null;-}-function correctASTNodes(type) {- if (isObjectType(type)) {- const config = type.toConfig();- if (config.astNode != null) {- const fields = [];- Object.values(config.fields).forEach(fieldConfig => {- if (fieldConfig.astNode != null) {- fields.push(fieldConfig.astNode);- }- });- config.astNode = {- ...config.astNode,- kind: Kind.OBJECT_TYPE_DEFINITION,- fields,- };- }- if (config.extensionASTNodes != null) {- config.extensionASTNodes = config.extensionASTNodes.map(node => ({- ...node,- kind: Kind.OBJECT_TYPE_EXTENSION,- fields: undefined,- }));- }- return new GraphQLObjectType(config);- }- else if (isInterfaceType(type)) {- const config = type.toConfig();- if (config.astNode != null) {- const fields = [];- Object.values(config.fields).forEach(fieldConfig => {- if (fieldConfig.astNode != null) {- fields.push(fieldConfig.astNode);- }- });- config.astNode = {- ...config.astNode,- kind: Kind.INTERFACE_TYPE_DEFINITION,- fields,- };- }- if (config.extensionASTNodes != null) {- config.extensionASTNodes = config.extensionASTNodes.map(node => ({- ...node,- kind: Kind.INTERFACE_TYPE_EXTENSION,- fields: undefined,- }));- }- return new GraphQLInterfaceType(config);- }- else if (isInputObjectType(type)) {- const config = type.toConfig();- if (config.astNode != null) {- const fields = [];- Object.values(config.fields).forEach(fieldConfig => {- if (fieldConfig.astNode != null) {- fields.push(fieldConfig.astNode);- }- });- config.astNode = {- ...config.astNode,- kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,- fields,- };- }- if (config.extensionASTNodes != null) {- config.extensionASTNodes = config.extensionASTNodes.map(node => ({- ...node,- kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,- fields: undefined,- }));- }- return new GraphQLInputObjectType(config);- }- else if (isEnumType(type)) {- const config = type.toConfig();- if (config.astNode != null) {- const values = [];- Object.values(config.values).forEach(enumValueConfig => {- if (enumValueConfig.astNode != null) {- values.push(enumValueConfig.astNode);- }- });- config.astNode = {- ...config.astNode,- values,- };- }- if (config.extensionASTNodes != null) {- config.extensionASTNodes = config.extensionASTNodes.map(node => ({- ...node,- values: undefined,- }));- }- return new GraphQLEnumType(config);- }- else {- return type;- }-}-function cloneType(type) {- if (isObjectType(type)) {- const config = type.toConfig();- return new GraphQLObjectType({- ...config,- interfaces: typeof config.interfaces === 'function' ? config.interfaces : config.interfaces.slice(),- });- }- else if (isInterfaceType(type)) {- const config = type.toConfig();- const newConfig = {- ...config,- interfaces: [...((typeof config.interfaces === 'function' ? config.interfaces() : config.interfaces) || [])],- };- return new GraphQLInterfaceType(newConfig);- }- else if (isUnionType(type)) {- const config = type.toConfig();- return new GraphQLUnionType({- ...config,- types: config.types.slice(),- });- }- else if (isInputObjectType(type)) {- return new GraphQLInputObjectType(type.toConfig());- }- else if (isEnumType(type)) {- return new GraphQLEnumType(type.toConfig());- }- else if (isScalarType(type)) {- return isSpecifiedScalarType(type) ? type : new GraphQLScalarType(type.toConfig());- }- throw new Error(`Invalid type ${type}`);-}-function cloneSchema(schema) {- return mapSchema(schema);-}--// Update any references to named schema types that disagree with the named-// types found in schema.getTypeMap().-//-// healSchema and its callers (visitSchema/visitSchemaDirectives) all modify the schema in place.-// Therefore, private variables (such as the stored implementation map and the proper root types)-// are not updated.-//-// If this causes issues, the schema could be more aggressively healed as follows:-//-// healSchema(schema);-// const config = schema.toConfig()-// const healedSchema = new GraphQLSchema({-// ...config,-// query: schema.getType('<desired new root query type name>'),-// mutation: schema.getType('<desired new root mutation type name>'),-// subscription: schema.getType('<desired new root subscription type name>'),-// });-//-// One can then also -- if necessary -- assign the correct private variables to the initial schema-// as follows:-// Object.assign(schema, healedSchema);-//-// These steps are not taken automatically to preserve backwards compatibility with graphql-tools v4.-// See https://github.com/ardatan/graphql-tools/issues/1462-//-// They were briefly taken in v5, but can now be phased out as they were only required when other-// areas of the codebase were using healSchema and visitSchema more extensively.-//-function healSchema(schema) {- healTypes(schema.getTypeMap(), schema.getDirectives());- return schema;-}-function healTypes(originalTypeMap, directives, config = {- skipPruning: false,-}) {- const actualNamedTypeMap = Object.create(null);- // If any of the .name properties of the GraphQLNamedType objects in- // schema.getTypeMap() have changed, the keys of the type map need to- // be updated accordingly.- Object.entries(originalTypeMap).forEach(([typeName, namedType]) => {- if (namedType == null || typeName.startsWith('__')) {- return;- }- const actualName = namedType.name;- if (actualName.startsWith('__')) {- return;- }- if (actualName in actualNamedTypeMap) {- throw new Error(`Duplicate schema type name ${actualName}`);- }- actualNamedTypeMap[actualName] = namedType;- // Note: we are deliberately leaving namedType in the schema by its- // original name (which might be different from actualName), so that- // references by that name can be healed.- });- // Now add back every named type by its actual name.- Object.entries(actualNamedTypeMap).forEach(([typeName, namedType]) => {- originalTypeMap[typeName] = namedType;- });- // Directive declaration argument types can refer to named types.- directives.forEach((decl) => {- decl.args = decl.args.filter(arg => {- arg.type = healType(arg.type);- return arg.type !== null;- });- });- Object.entries(originalTypeMap).forEach(([typeName, namedType]) => {- // Heal all named types, except for dangling references, kept only to redirect.- if (!typeName.startsWith('__') && typeName in actualNamedTypeMap) {- if (namedType != null) {- healNamedType(namedType);- }- }- });- for (const typeName of Object.keys(originalTypeMap)) {- if (!typeName.startsWith('__') && !(typeName in actualNamedTypeMap)) {- delete originalTypeMap[typeName];- }- }- if (!config.skipPruning) {- // TODO:- // consider removing the default level of pruning in v7,- // see comments below on the pruneTypes function.- pruneTypes$1(originalTypeMap, directives);- }- function healNamedType(type) {- if (isObjectType(type)) {- healFields(type);- healInterfaces(type);- return;- }- else if (isInterfaceType(type)) {- healFields(type);- if ('getInterfaces' in type) {- healInterfaces(type);- }- return;- }- else if (isUnionType(type)) {- healUnderlyingTypes(type);- return;- }- else if (isInputObjectType(type)) {- healInputFields(type);- return;- }- else if (isLeafType(type)) {- return;- }- throw new Error(`Unexpected schema type: ${type}`);- }- function healFields(type) {- const fieldMap = type.getFields();- for (const [key, field] of Object.entries(fieldMap)) {- field.args- .map(arg => {- arg.type = healType(arg.type);- return arg.type === null ? null : arg;- })- .filter(Boolean);- field.type = healType(field.type);- if (field.type === null) {- delete fieldMap[key];- }- }- }- function healInterfaces(type) {- if ('getInterfaces' in type) {- const interfaces = type.getInterfaces();- interfaces.push(...interfaces- .splice(0)- .map(iface => healType(iface))- .filter(Boolean));- }- }- function healInputFields(type) {- const fieldMap = type.getFields();- for (const [key, field] of Object.entries(fieldMap)) {- field.type = healType(field.type);- if (field.type === null) {- delete fieldMap[key];- }- }- }- function healUnderlyingTypes(type) {- const types = type.getTypes();- types.push(...types- .splice(0)- .map(t => healType(t))- .filter(Boolean));- }- function healType(type) {- // Unwrap the two known wrapper types- if (isListType(type)) {- const healedType = healType(type.ofType);- return healedType != null ? new GraphQLList(healedType) : null;- }- else if (isNonNullType(type)) {- const healedType = healType(type.ofType);- return healedType != null ? new GraphQLNonNull(healedType) : null;- }- else if (isNamedType(type)) {- // If a type annotation on a field or an argument or a union member is- // any `GraphQLNamedType` with a `name`, then it must end up identical- // to `schema.getType(name)`, since `schema.getTypeMap()` is the source- // of truth for all named schema types.- // Note that new types can still be simply added by adding a field, as- // the official type will be undefined, not null.- const officialType = originalTypeMap[type.name];- if (officialType && type !== officialType) {- return officialType;- }- }- return type;- }-}-// TODO:-// consider removing the default level of pruning in v7-//-// Pruning was introduced into healSchema in v5, so legacy schema directives relying on pruning-// during healing are likely to be rare. pruning is now recommended via the dedicated pruneSchema-// function which does not force pruning on library users and gives granular control in terms of-// pruning types. pruneSchema does recreate the schema -- a parallel version that prunes in place-// could be considered.-function pruneTypes$1(typeMap, directives) {- const implementedInterfaces = {};- Object.values(typeMap).forEach(namedType => {- if ('getInterfaces' in namedType) {- namedType.getInterfaces().forEach(iface => {- implementedInterfaces[iface.name] = true;- });- }- });- let prunedTypeMap = false;- const typeNames = Object.keys(typeMap);- for (let i = 0; i < typeNames.length; i++) {- const typeName = typeNames[i];- const type = typeMap[typeName];- if (isObjectType(type) || isInputObjectType(type)) {- // prune types with no fields- if (!Object.keys(type.getFields()).length) {- typeMap[typeName] = null;- prunedTypeMap = true;- }- }- else if (isUnionType(type)) {- // prune unions without underlying types- if (!type.getTypes().length) {- typeMap[typeName] = null;- prunedTypeMap = true;- }- }- else if (isInterfaceType(type)) {- // prune interfaces without fields or without implementations- if (!Object.keys(type.getFields()).length || !(type.name in implementedInterfaces)) {- typeMap[typeName] = null;- prunedTypeMap = true;- }- }- }- // every prune requires another round of healing- if (prunedTypeMap) {- healTypes(typeMap, directives);- }-}--// Abstract base class of any visitor implementation, defining the available-// visitor methods along with their parameter types, and providing a static-// helper function for determining whether a subclass implements a given-// visitor method, as opposed to inheriting one of the stubs defined here.-class SchemaVisitor {- // Determine if this SchemaVisitor (sub)class implements a particular- // visitor method.- static implementsVisitorMethod(methodName) {- if (!methodName.startsWith('visit')) {- return false;- }- const method = this.prototype[methodName];- if (typeof method !== 'function') {- return false;- }- if (this.name === 'SchemaVisitor') {- // The SchemaVisitor class implements every visitor method.- return true;- }- const stub = SchemaVisitor.prototype[methodName];- if (method === stub) {- // If this.prototype[methodName] was just inherited from SchemaVisitor,- // then this class does not really implement the method.- return false;- }- return true;- }- // Concrete subclasses of SchemaVisitor should override one or more of these- // visitor methods, in order to express their interest in handling certain- // schema types/locations. Each method may return null to remove the given- // type from the schema, a non-null value of the same type to update the- // type in the schema, or nothing to leave the type as it was.- // eslint-disable-next-line @typescript-eslint/no-empty-function- visitSchema(_schema) { }- visitScalar(_scalar- // eslint-disable-next-line @typescript-eslint/no-empty-function- ) { }- visitObject(_object- // eslint-disable-next-line @typescript-eslint/no-empty-function- ) { }- visitFieldDefinition(_field, _details- // eslint-disable-next-line @typescript-eslint/no-empty-function- ) { }- visitArgumentDefinition(_argument, _details- // eslint-disable-next-line @typescript-eslint/no-empty-function- ) { }- visitInterface(_iface- // eslint-disable-next-line @typescript-eslint/no-empty-function- ) { }- // eslint-disable-next-line @typescript-eslint/no-empty-function- visitUnion(_union) { }- // eslint-disable-next-line @typescript-eslint/no-empty-function- visitEnum(_type) { }- visitEnumValue(_value, _details- // eslint-disable-next-line @typescript-eslint/no-empty-function- ) { }- visitInputObject(_object- // eslint-disable-next-line @typescript-eslint/no-empty-function- ) { }- visitInputFieldDefinition(_field, _details- // eslint-disable-next-line @typescript-eslint/no-empty-function- ) { }-}--function isSchemaVisitor(obj) {- if ('schema' in obj && isSchema(obj.schema)) {- if ('visitSchema' in obj && typeof obj.visitSchema === 'function') {- return true;- }- }- return false;-}-// Generic function for visiting GraphQLSchema objects.-function visitSchema(schema, -// To accommodate as many different visitor patterns as possible, the-// visitSchema function does not simply accept a single instance of the-// SchemaVisitor class, but instead accepts a function that takes the-// current VisitableSchemaType object and the name of a visitor method and-// returns an array of SchemaVisitor instances that implement the visitor-// method and have an interest in handling the given VisitableSchemaType-// object. In the simplest case, this function can always return an array-// containing a single visitor object, without even looking at the type or-// methodName parameters. In other cases, this function might sometimes-// return an empty array to indicate there are no visitors that should be-// applied to the given VisitableSchemaType object. For an example of a-// visitor pattern that benefits from this abstraction, see the-// SchemaDirectiveVisitor class below.-visitorOrVisitorSelector) {- const visitorSelector = typeof visitorOrVisitorSelector === 'function' ? visitorOrVisitorSelector : () => visitorOrVisitorSelector;- // Helper function that calls visitorSelector and applies the resulting- // visitors to the given type, with arguments [type, ...args].- function callMethod(methodName, type, ...args) {- let visitors = visitorSelector(type, methodName);- visitors = Array.isArray(visitors) ? visitors : [visitors];- let finalType = type;- visitors.every(visitorOrVisitorDef => {- let newType;- if (isSchemaVisitor(visitorOrVisitorDef)) {- newType = visitorOrVisitorDef[methodName](finalType, ...args);- }- else if (isNamedType(finalType) &&- (methodName === 'visitScalar' ||- methodName === 'visitEnum' ||- methodName === 'visitObject' ||- methodName === 'visitInputObject' ||- methodName === 'visitUnion' ||- methodName === 'visitInterface')) {- const specifiers = getTypeSpecifiers$1(finalType, schema);- const typeVisitor = getVisitor(visitorOrVisitorDef, specifiers);- newType = typeVisitor != null ? typeVisitor(finalType, schema) : undefined;- }- if (typeof newType === 'undefined') {- // Keep going without modifying type.- return true;- }- if (methodName === 'visitSchema' || isSchema(finalType)) {- throw new Error(`Method ${methodName} cannot replace schema with ${newType}`);- }- if (newType === null) {- // Stop the loop and return null form callMethod, which will cause- // the type to be removed from the schema.- finalType = null;- return false;- }- // Update type to the new type returned by the visitor method, so that- // later directives will see the new type, and callMethod will return- // the final type.- finalType = newType;- return true;- });- // If there were no directives for this type object, or if all visitor- // methods returned nothing, type will be returned unmodified.- return finalType;- }- // Recursive helper function that calls any appropriate visitor methods for- // each object in the schema, then traverses the object's children (if any).- function visit(type) {- if (isSchema(type)) {- // Unlike the other types, the root GraphQLSchema object cannot be- // replaced by visitor methods, because that would make life very hard- // for SchemaVisitor subclasses that rely on the original schema object.- callMethod('visitSchema', type);- const typeMap = type.getTypeMap();- Object.entries(typeMap).forEach(([typeName, namedType]) => {- if (!typeName.startsWith('__') && namedType != null) {- // Call visit recursively to let it determine which concrete- // subclass of GraphQLNamedType we found in the type map.- // We do not use updateEachKey because we want to preserve- // deleted types in the typeMap so that other types that reference- // the deleted types can be healed.- typeMap[typeName] = visit(namedType);- }- });- return type;- }- if (isObjectType(type)) {- // Note that callMethod('visitObject', type) may not actually call any- // methods, if there are no @directive annotations associated with this- // type, or if this SchemaDirectiveVisitor subclass does not override- // the visitObject method.- const newObject = callMethod('visitObject', type);- if (newObject != null) {- visitFields(newObject);- }- return newObject;- }- if (isInterfaceType(type)) {- const newInterface = callMethod('visitInterface', type);- if (newInterface != null) {- visitFields(newInterface);- }- return newInterface;- }- if (isInputObjectType(type)) {- const newInputObject = callMethod('visitInputObject', type);- if (newInputObject != null) {- const fieldMap = newInputObject.getFields();- for (const key of Object.keys(fieldMap)) {- fieldMap[key] = callMethod('visitInputFieldDefinition', fieldMap[key], {- // Since we call a different method for input object fields, we- // can't reuse the visitFields function here.- objectType: newInputObject,- });- if (!fieldMap[key]) {- delete fieldMap[key];- }- }- }- return newInputObject;- }- if (isScalarType(type)) {- return callMethod('visitScalar', type);- }- if (isUnionType(type)) {- return callMethod('visitUnion', type);- }- if (isEnumType(type)) {- let newEnum = callMethod('visitEnum', type);- if (newEnum != null) {- const newValues = newEnum- .getValues()- .map(value => callMethod('visitEnumValue', value, {- enumType: newEnum,- }))- .filter(Boolean);- // Recreate the enum type if any of the values changed- const valuesUpdated = newValues.some((value, index) => value !== newEnum.getValues()[index]);- if (valuesUpdated) {- newEnum = new GraphQLEnumType({- ...newEnum.toConfig(),- values: newValues.reduce((prev, value) => ({- ...prev,- [value.name]: {- value: value.value,- deprecationReason: value.deprecationReason,- description: value.description,- astNode: value.astNode,- },- }), {}),- });- }- }- return newEnum;- }- throw new Error(`Unexpected schema type: ${type}`);- }- function visitFields(type) {- const fieldMap = type.getFields();- for (const [key, field] of Object.entries(fieldMap)) {- // It would be nice if we could call visit(field) recursively here, but- // GraphQLField is merely a type, not a value that can be detected using- // an instanceof check, so we have to visit the fields in this lexical- // context, so that TypeScript can validate the call to- // visitFieldDefinition.- const newField = callMethod('visitFieldDefinition', field, {- // While any field visitor needs a reference to the field object, some- // field visitors may also need to know the enclosing (parent) type,- // perhaps to determine if the parent is a GraphQLObjectType or a- // GraphQLInterfaceType. To obtain a reference to the parent, a- // visitor method can have a second parameter, which will be an object- // with an .objectType property referring to the parent.- objectType: type,- });- if (newField.args != null) {- newField.args = newField.args- .map(arg => callMethod('visitArgumentDefinition', arg, {- // Like visitFieldDefinition, visitArgumentDefinition takes a- // second parameter that provides additional context, namely the- // parent .field and grandparent .objectType. Remember that the- // current GraphQLSchema is always available via this.schema.- field: newField,- objectType: type,- }))- .filter(Boolean);- }- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition- if (newField) {- fieldMap[key] = newField;- }- else {- delete fieldMap[key];- }- }- }- visit(schema);- // Automatically update any references to named schema types replaced- // during the traversal, so implementors don't have to worry about that.- healSchema(schema);- // Return schema for convenience, even though schema parameter has all updated types.- return schema;-}-function getTypeSpecifiers$1(type, schema) {- const specifiers = [VisitSchemaKind.TYPE];- if (isObjectType(type)) {- specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.OBJECT_TYPE);- const query = schema.getQueryType();- const mutation = schema.getMutationType();- const subscription = schema.getSubscriptionType();- if (type === query) {- specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.QUERY);- }- else if (type === mutation) {- specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.MUTATION);- }- else if (type === subscription) {- specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.SUBSCRIPTION);- }- }- else if (isInputType(type)) {- specifiers.push(VisitSchemaKind.INPUT_OBJECT_TYPE);- }- else if (isInterfaceType(type)) {- specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.ABSTRACT_TYPE, VisitSchemaKind.INTERFACE_TYPE);- }- else if (isUnionType(type)) {- specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.ABSTRACT_TYPE, VisitSchemaKind.UNION_TYPE);- }- else if (isEnumType(type)) {- specifiers.push(VisitSchemaKind.ENUM_TYPE);- }- else if (isScalarType(type)) {- specifiers.push(VisitSchemaKind.SCALAR_TYPE);- }- return specifiers;-}-function getVisitor(visitorDef, specifiers) {- let typeVisitor;- const stack = [...specifiers];- while (!typeVisitor && stack.length > 0) {- const next = stack.pop();- typeVisitor = visitorDef[next];- }- return typeVisitor != null ? typeVisitor : null;-}--// This class represents a reusable implementation of a @directive that may-// appear in a GraphQL schema written in Schema Definition Language.-//-// By overriding one or more visit{Object,Union,...} methods, a subclass-// registers interest in certain schema types, such as GraphQLObjectType,-// GraphQLUnionType, etc. When SchemaDirectiveVisitor.visitSchemaDirectives is-// called with a GraphQLSchema object and a map of visitor subclasses, the-// overidden methods of those subclasses allow the visitors to obtain-// references to any type objects that have @directives attached to them,-// enabling visitors to inspect or modify the schema as appropriate.-//-// For example, if a directive called @rest(url: "...") appears after a field-// definition, a SchemaDirectiveVisitor subclass could provide meaning to that-// directive by overriding the visitFieldDefinition method (which receives a-// GraphQLField parameter), and then the body of that visitor method could-// manipulate the field's resolver function to fetch data from a REST endpoint-// described by the url argument passed to the @rest directive:-//-// const typeDefs = `-// type Query {-// people: [Person] @rest(url: "/api/v1/people")-// }`;-//-// const schema = makeExecutableSchema({ typeDefs });-//-// SchemaDirectiveVisitor.visitSchemaDirectives(schema, {-// rest: class extends SchemaDirectiveVisitor {-// public visitFieldDefinition(field: GraphQLField<any, any>) {-// const { url } = this.args;-// field.resolve = () => fetch(url);-// }-// }-// });-//-// The subclass in this example is defined as an anonymous class expression,-// for brevity. A truly reusable SchemaDirectiveVisitor would most likely be-// defined in a library using a named class declaration, and then exported for-// consumption by other modules and packages.-//-// See below for a complete list of overridable visitor methods, their-// parameter types, and more details about the properties exposed by instances-// of the SchemaDirectiveVisitor class.-class SchemaDirectiveVisitor extends SchemaVisitor {- // Mark the constructor protected to enforce passing SchemaDirectiveVisitor- // subclasses (not instances) to visitSchemaDirectives.- constructor(config) {- super();- this.name = config.name;- this.args = config.args;- this.visitedType = config.visitedType;- this.schema = config.schema;- this.context = config.context;- }- // Override this method to return a custom GraphQLDirective (or modify one- // already present in the schema) to enforce argument types, provide default- // argument values, or specify schema locations where this @directive may- // appear. By default, any declaration found in the schema will be returned.- static getDirectiveDeclaration(directiveName, schema) {- return schema.getDirective(directiveName);- }- // Call SchemaDirectiveVisitor.visitSchemaDirectives to visit every- // @directive in the schema and create an appropriate SchemaDirectiveVisitor- // instance to visit the object decorated by the @directive.- static visitSchemaDirectives(schema, - // The keys of this object correspond to directive names as they appear- // in the schema, and the values should be subclasses (not instances!)- // of the SchemaDirectiveVisitor class. This distinction is important- // because a new SchemaDirectiveVisitor instance will be created each- // time a matching directive is found in the schema AST, with arguments- // and other metadata specific to that occurrence. To help prevent the- // mistake of passing instances, the SchemaDirectiveVisitor constructor- // method is marked as protected.- directiveVisitors, - // Optional context object that will be available to all visitor instances- // via this.context. Defaults to an empty null-prototype object.- context = Object.create(null)- // The visitSchemaDirectives method returns a map from directive names to- // lists of SchemaDirectiveVisitors created while visiting the schema.- ) {- // If the schema declares any directives for public consumption, record- // them here so that we can properly coerce arguments when/if we encounter- // an occurrence of the directive while walking the schema below.- const declaredDirectives = this.getDeclaredDirectives(schema, directiveVisitors);- // Map from directive names to lists of SchemaDirectiveVisitor instances- // created while visiting the schema.- const createdVisitors = Object.keys(directiveVisitors).reduce((prev, item) => ({- ...prev,- [item]: [],- }), {});- const directiveVisitorMap = Object.entries(directiveVisitors).reduce((prev, [key, value]) => ({- ...prev,- [key]: value,- }), {});- function visitorSelector(type, methodName) {- var _a, _b;- let directiveNodes = (_b = (_a = type === null || type === void 0 ? void 0 : type.astNode) === null || _a === void 0 ? void 0 : _a.directives) !== null && _b !== void 0 ? _b : [];- const extensionASTNodes = type.extensionASTNodes;- if (extensionASTNodes != null) {- extensionASTNodes.forEach(extensionASTNode => {- if (extensionASTNode.directives != null) {- directiveNodes = directiveNodes.concat(extensionASTNode.directives);- }- });- }- const visitors = [];- directiveNodes.forEach(directiveNode => {- const directiveName = directiveNode.name.value;- if (!(directiveName in directiveVisitorMap)) {- return;- }- const VisitorClass = directiveVisitorMap[directiveName];- // Avoid creating visitor objects if visitorClass does not override- // the visitor method named by methodName.- if (!VisitorClass.implementsVisitorMethod(methodName)) {- return;- }- const decl = declaredDirectives[directiveName];- let args;- if (decl != null) {- // If this directive was explicitly declared, use the declared- // argument types (and any default values) to check, coerce, and/or- // supply default values for the given arguments.- args = getArgumentValues$1(decl, directiveNode);- }- else {- // If this directive was not explicitly declared, just convert the- // argument nodes to their corresponding JavaScript values.- args = Object.create(null);- if (directiveNode.arguments != null) {- directiveNode.arguments.forEach(arg => {- args[arg.name.value] = valueFromASTUntyped(arg.value);- });- }- }- // As foretold in comments near the top of the visitSchemaDirectives- // method, this is where instances of the SchemaDirectiveVisitor class- // get created and assigned names. While subclasses could override the- // constructor method, the constructor is marked as protected, so- // these are the only arguments that will ever be passed.- visitors.push(new VisitorClass({- name: directiveName,- args,- visitedType: type,- schema,- context,- }));- });- if (visitors.length > 0) {- visitors.forEach(visitor => {- createdVisitors[visitor.name].push(visitor);- });- }- return visitors;- }- visitSchema(schema, visitorSelector);- return createdVisitors;- }- static getDeclaredDirectives(schema, directiveVisitors) {- const declaredDirectives = schema.getDirectives().reduce((prev, curr) => ({- ...prev,- [curr.name]: curr,- }), {});- // If the visitor subclass overrides getDirectiveDeclaration, and it- // returns a non-null GraphQLDirective, use that instead of any directive- // declared in the schema itself. Reasoning: if a SchemaDirectiveVisitor- // goes to the trouble of implementing getDirectiveDeclaration, it should- // be able to rely on that implementation.- Object.entries(directiveVisitors).forEach(([directiveName, visitorClass]) => {- const decl = visitorClass.getDirectiveDeclaration(directiveName, schema);- if (decl != null) {- declaredDirectives[directiveName] = decl;- }- });- Object.entries(declaredDirectives).forEach(([name, decl]) => {- if (!(name in directiveVisitors)) {- // SchemaDirectiveVisitors.visitSchemaDirectives might be called- // multiple times with partial directiveVisitors maps, so it's not- // necessarily an error for directiveVisitors to be missing an- // implementation of a directive that was declared in the schema.- return;- }- const visitorClass = directiveVisitors[name];- decl.locations.forEach(loc => {- const visitorMethodName = directiveLocationToVisitorMethodName(loc);- if (SchemaVisitor.implementsVisitorMethod(visitorMethodName) &&- !visitorClass.implementsVisitorMethod(visitorMethodName)) {- // While visitor subclasses may implement extra visitor methods,- // it's definitely a mistake if the GraphQLDirective declares itself- // applicable to certain schema locations, and the visitor subclass- // does not implement all the corresponding methods.- throw new Error(`SchemaDirectiveVisitor for @${name} must implement ${visitorMethodName} method`);- }- });- });- return declaredDirectives;- }-}-// Convert a string like "FIELD_DEFINITION" to "visitFieldDefinition".-function directiveLocationToVisitorMethodName(loc) {- return ('visit' +- loc.replace(/([^_]*)_?/g, (_wholeMatch, part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()));-}--function getResolversFromSchema(schema) {- const resolvers = Object.create({});- const typeMap = schema.getTypeMap();- Object.keys(typeMap).forEach(typeName => {- const type = typeMap[typeName];- if (isScalarType(type)) {- if (!isSpecifiedScalarType(type)) {- resolvers[typeName] = cloneType(type);- }- }- else if (isEnumType(type)) {- resolvers[typeName] = {};- const values = type.getValues();- values.forEach(value => {- resolvers[typeName][value.name] = value.value;- });- }- else if (isInterfaceType(type)) {- if (type.resolveType != null) {- resolvers[typeName] = {- __resolveType: type.resolveType,- };- }- }- else if (isUnionType(type)) {- if (type.resolveType != null) {- resolvers[typeName] = {- __resolveType: type.resolveType,- };- }- }- else if (isObjectType(type)) {- resolvers[typeName] = {};- if (type.isTypeOf != null) {- resolvers[typeName].__isTypeOf = type.isTypeOf;- }- const fields = type.getFields();- Object.keys(fields).forEach(fieldName => {- const field = fields[fieldName];- resolvers[typeName][fieldName] = {- resolve: field.resolve,- subscribe: field.subscribe,- };- });- }- });- return resolvers;-}--function forEachField(schema, fn) {- const typeMap = schema.getTypeMap();- Object.keys(typeMap).forEach(typeName => {- const type = typeMap[typeName];- // TODO: maybe have an option to include these?- if (!getNamedType(type).name.startsWith('__') && isObjectType(type)) {- const fields = type.getFields();- Object.keys(fields).forEach(fieldName => {- const field = fields[fieldName];- fn(field, typeName, fieldName);- });- }- });-}--function forEachDefaultValue(schema, fn) {- const typeMap = schema.getTypeMap();- Object.keys(typeMap).forEach(typeName => {- const type = typeMap[typeName];- if (!getNamedType(type).name.startsWith('__')) {- if (isObjectType(type)) {- const fields = type.getFields();- Object.keys(fields).forEach(fieldName => {- const field = fields[fieldName];- field.args.forEach(arg => {- arg.defaultValue = fn(arg.type, arg.defaultValue);- });- });- }- else if (isInputObjectType(type)) {- const fields = type.getFields();- Object.keys(fields).forEach(fieldName => {- const field = fields[fieldName];- field.defaultValue = fn(field.type, field.defaultValue);- });- }- }- });-}--/* eslint-disable @typescript-eslint/explicit-module-boundary-types */-function mergeDeep(target, ...sources) {- if (isScalarType(target)) {- return target;- }- const output = {- ...target,- };- for (const source of sources) {- if (isObject(target) && isObject(source)) {- for (const key in source) {- if (isObject(source[key])) {- if (!(key in target)) {- Object.assign(output, { [key]: source[key] });- }- else {- output[key] = mergeDeep(target[key], source[key]);- }- }- else {- Object.assign(output, { [key]: source[key] });- }- }- }- }- return output;-}-function isObject(item) {- return item && typeof item === 'object' && !Array.isArray(item);-}-function typesContainSelectionSet(types, selectionSet) {- const fieldMaps = types.map(type => type.getFields());- for (const selection of selectionSet.selections) {- if (selection.kind === Kind.FIELD) {- const fields = fieldMaps.map(fieldMap => fieldMap[selection.name.value]).filter(field => field != null);- if (!fields.length) {- return false;- }- if (selection.selectionSet != null) {- return typesContainSelectionSet(fields.map(field => getNamedType(field.type)), selection.selectionSet);- }- }- else if (selection.kind === Kind.INLINE_FRAGMENT && selection.typeCondition.name.value === types[0].name) {- return typesContainSelectionSet(types, selection.selectionSet);- }- }- return true;-}--/**- * Get the key under which the result of this resolver will be placed in the response JSON. Basically, just- * resolves aliases.- * @param info The info argument to the resolver.- */-function getResponseKeyFromInfo(info) {- return info.fieldNodes[0].alias != null ? info.fieldNodes[0].alias.value : info.fieldName;-}--function applySchemaTransforms(originalSchema, transforms) {- return transforms.reduce((schema, transform) => transform.transformSchema != null ? transform.transformSchema(cloneSchema(schema)) : schema, originalSchema);-}--/**- * Given a selectionSet, adds all of the fields in that selection to- * the passed in map of fields, and returns it at the end.- *- * CollectFields requires the "runtime type" of an object. For a field which- * returns an Interface or Union type, the "runtime type" will be the actual- * Object type returned by that field.- *- * @internal- */-function collectFields$1(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {- for (const selection of selectionSet.selections) {- switch (selection.kind) {- case Kind.FIELD: {- if (!shouldIncludeNode$1(exeContext, selection)) {- continue;- }- const name = getFieldEntryKey$1(selection);- if (!(name in fields)) {- fields[name] = [];- }- fields[name].push(selection);- break;- }- case Kind.INLINE_FRAGMENT: {- if (!shouldIncludeNode$1(exeContext, selection) ||- !doesFragmentConditionMatch$1(exeContext, selection, runtimeType)) {- continue;- }- collectFields$1(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);- break;- }- case Kind.FRAGMENT_SPREAD: {- const fragName = selection.name.value;- if (visitedFragmentNames[fragName] || !shouldIncludeNode$1(exeContext, selection)) {- continue;- }- visitedFragmentNames[fragName] = true;- const fragment = exeContext.fragments[fragName];- if (!fragment || !doesFragmentConditionMatch$1(exeContext, fragment, runtimeType)) {- continue;- }- collectFields$1(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);- break;- }- }- }- return fields;-}-/**- * Determines if a field should be included based on the @include and @skip- * directives, where @skip has higher precedence than @include.- */-function shouldIncludeNode$1(exeContext, node) {- const skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues);- if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {- return false;- }- const include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues);- if ((include === null || include === void 0 ? void 0 : include.if) === false) {- return false;- }- return true;-}-/**- * Determines if a fragment is applicable to the given type.- */-function doesFragmentConditionMatch$1(exeContext, fragment, type) {- const typeConditionNode = fragment.typeCondition;- if (!typeConditionNode) {- return true;- }- const conditionalType = typeFromAST(exeContext.schema, typeConditionNode);- if (conditionalType === type) {- return true;- }- if (isAbstractType(conditionalType)) {- return exeContext.schema.isPossibleType(conditionalType, type);- }- return false;-}-/**- * Implements the logic to compute the key of a given field's entry- */-function getFieldEntryKey$1(node) {- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition- return node.alias ? node.alias.value : node.name.value;-}--/**- * Given an AsyncIterable and a callback function, return an AsyncIterator- * which produces values mapped via calling the callback function.- */-function mapAsyncIterator$1(iterator, callback, rejectCallback) {- let $return;- let abruptClose;- if (typeof iterator.return === 'function') {- $return = iterator.return;- abruptClose = (error) => {- const rethrow = () => Promise.reject(error);- return $return.call(iterator).then(rethrow, rethrow);- };- }- function mapResult(result) {- return result.done ? result : asyncMapValue$1(result.value, callback).then(iteratorResult$1, abruptClose);- }- let mapReject;- if (rejectCallback) {- // Capture rejectCallback to ensure it cannot be null.- const reject = rejectCallback;- mapReject = (error) => asyncMapValue$1(error, reject).then(iteratorResult$1, abruptClose);- }- return {- next() {- return iterator.next().then(mapResult, mapReject);- },- return() {- return $return- ? $return.call(iterator).then(mapResult, mapReject)- : Promise.resolve({ value: undefined, done: true });- },- throw(error) {- if (typeof iterator.throw === 'function') {- return iterator.throw(error).then(mapResult, mapReject);- }- return Promise.reject(error).catch(abruptClose);- },- [Symbol.asyncIterator]() {- return this;- },- };-}-function asyncMapValue$1(value, callback) {- return new Promise(resolve => resolve(callback(value)));-}-function iteratorResult$1(value) {- return { value, done: false };-}--function astFromType(type) {- if (isNonNullType(type)) {- const innerType = astFromType(type.ofType);- if (innerType.kind === Kind.NON_NULL_TYPE) {- throw new Error(`Invalid type node ${JSON.stringify(type)}. Inner type of non-null type cannot be a non-null type.`);- }- return {- kind: Kind.NON_NULL_TYPE,- type: innerType,- };- }- else if (isListType(type)) {- return {- kind: Kind.LIST_TYPE,- type: astFromType(type.ofType),- };- }- return {- kind: Kind.NAMED_TYPE,- name: {- kind: Kind.NAME,- value: type.name,- },- };-}--function updateArgument(argName, argType, argumentNodes, variableDefinitionsMap, variableValues, newArg) {- let varName;- let numGeneratedVariables = 0;- do {- varName = `_v${(numGeneratedVariables++).toString()}_${argName}`;- } while (varName in variableDefinitionsMap);- argumentNodes[argName] = {- kind: Kind.ARGUMENT,- name: {- kind: Kind.NAME,- value: argName,- },- value: {- kind: Kind.VARIABLE,- name: {- kind: Kind.NAME,- value: varName,- },- },- };- variableDefinitionsMap[varName] = {- kind: Kind.VARIABLE_DEFINITION,- variable: {- kind: Kind.VARIABLE,- name: {- kind: Kind.NAME,- value: varName,- },- },- type: astFromType(argType),- };- if (newArg === undefined) {- delete variableValues[varName];- }- else {- variableValues[varName] = newArg;- }-}--function implementsAbstractType(schema, typeA, typeB) {- if (typeA === typeB) {- return true;- }- else if (isCompositeType(typeA) && isCompositeType(typeB)) {- return doTypesOverlap(schema, typeA, typeB);- }- return false;-}--const ERROR_SYMBOL = Symbol('subschemaErrors');-function relocatedError(originalError, path) {- return new GraphQLError(originalError.message, originalError.nodes, originalError.source, originalError.positions, path === null ? undefined : path === undefined ? originalError.path : path, originalError.originalError, originalError.extensions);-}-function slicedError(originalError) {- return relocatedError(originalError, originalError.path != null ? originalError.path.slice(1) : undefined);-}-function getErrorsByPathSegment(errors) {- const record = Object.create(null);- errors.forEach(error => {- if (!error.path || error.path.length < 2) {- return;- }- const pathSegment = error.path[1];- const current = pathSegment in record ? record[pathSegment] : [];- current.push(slicedError(error));- record[pathSegment] = current;- });- return record;-}-function setErrors(result, errors) {- result[ERROR_SYMBOL] = errors;-}-function getErrors(result, pathSegment) {- const errors = result != null ? result[ERROR_SYMBOL] : result;- if (!Array.isArray(errors)) {- return null;- }- const fieldErrors = [];- for (const error of errors) {- if (!error.path || error.path[0] === pathSegment) {- fieldErrors.push(error);- }- }- return fieldErrors;-}--function observableToAsyncIterable(observable) {- const pullQueue = [];- const pushQueue = [];- let listening = true;- const pushValue = (value) => {- if (pullQueue.length !== 0) {- pullQueue.shift()({ value, done: false });- }- else {- pushQueue.push({ value });- }- };- const pushError = (error) => {- if (pullQueue.length !== 0) {- pullQueue.shift()({ value: { errors: [error] }, done: false });- }- else {- pushQueue.push({ value: { errors: [error] } });- }- };- const pullValue = () => new Promise(resolve => {- if (pushQueue.length !== 0) {- const element = pushQueue.shift();- // either {value: {errors: [...]}} or {value: ...}- resolve({- ...element,- done: false,- });- }- else {- pullQueue.push(resolve);- }- });- const subscription = observable.subscribe({- next(value) {- pushValue(value);- },- error(err) {- pushError(err);- },- });- const emptyQueue = () => {- if (listening) {- listening = false;- subscription.unsubscribe();- pullQueue.forEach(resolve => resolve({ value: undefined, done: true }));- pullQueue.length = 0;- pushQueue.length = 0;- }- };- return {- next() {- return listening ? pullValue() : this.return();- },- return() {- emptyQueue();- return Promise.resolve({ value: undefined, done: true });- },- throw(error) {- emptyQueue();- return Promise.reject(error);- },- [Symbol.asyncIterator]() {- return this;- },- };-}--var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};--function createCommonjsModule(fn, basedir, module) {- return module = {- path: basedir,- exports: {},- require: function (path, base) {- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);- }- }, fn(module, module.exports), module.exports;-}--function commonjsRequire () {- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');-}--var fromCallback = function (fn) {- return Object.defineProperty(function (...args) {- if (typeof args[args.length - 1] === 'function') fn.apply(this, args);- else {- return new Promise((resolve, reject) => {- fn.apply(- this,- args.concat([(err, res) => err ? reject(err) : resolve(res)])- );- })- }- }, 'name', { value: fn.name })-};--var fromPromise = function (fn) {- return Object.defineProperty(function (...args) {- const cb = args[args.length - 1];- if (typeof cb !== 'function') return fn.apply(this, args)- else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb);- }, 'name', { value: fn.name })-};--var universalify = {- fromCallback: fromCallback,- fromPromise: fromPromise-};--var origCwd = process.cwd;-var cwd = null;--var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;--process.cwd = function() {- if (!cwd)- cwd = origCwd.call(process);- return cwd-};-try {- process.cwd();-} catch (er) {}--var chdir = process.chdir;-process.chdir = function(d) {- cwd = null;- chdir.call(process, d);-};--var polyfills = patch;--function patch (fs) {- // (re-)implement some things that are known busted or missing.-- // lchmod, broken prior to 0.6.2- // back-port the fix here.- if (constants$4.hasOwnProperty('O_SYMLINK') &&- process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {- patchLchmod(fs);- }-- // lutimes implementation, or no-op- if (!fs.lutimes) {- patchLutimes(fs);- }-- // https://github.com/isaacs/node-graceful-fs/issues/4- // Chown should not fail on einval or eperm if non-root.- // It should not fail on enosys ever, as this just indicates- // that a fs doesn't support the intended operation.-- fs.chown = chownFix(fs.chown);- fs.fchown = chownFix(fs.fchown);- fs.lchown = chownFix(fs.lchown);-- fs.chmod = chmodFix(fs.chmod);- fs.fchmod = chmodFix(fs.fchmod);- fs.lchmod = chmodFix(fs.lchmod);-- fs.chownSync = chownFixSync(fs.chownSync);- fs.fchownSync = chownFixSync(fs.fchownSync);- fs.lchownSync = chownFixSync(fs.lchownSync);-- fs.chmodSync = chmodFixSync(fs.chmodSync);- fs.fchmodSync = chmodFixSync(fs.fchmodSync);- fs.lchmodSync = chmodFixSync(fs.lchmodSync);-- fs.stat = statFix(fs.stat);- fs.fstat = statFix(fs.fstat);- fs.lstat = statFix(fs.lstat);-- fs.statSync = statFixSync(fs.statSync);- fs.fstatSync = statFixSync(fs.fstatSync);- fs.lstatSync = statFixSync(fs.lstatSync);-- // if lchmod/lchown do not exist, then make them no-ops- if (!fs.lchmod) {- fs.lchmod = function (path, mode, cb) {- if (cb) process.nextTick(cb);- };- fs.lchmodSync = function () {};- }- if (!fs.lchown) {- fs.lchown = function (path, uid, gid, cb) {- if (cb) process.nextTick(cb);- };- fs.lchownSync = function () {};- }-- // on Windows, A/V software can lock the directory, causing this- // to fail with an EACCES or EPERM if the directory contains newly- // created files. Try again on failure, for up to 60 seconds.-- // Set the timeout this long because some Windows Anti-Virus, such as Parity- // bit9, may lock files for up to a minute, causing npm package install- // failures. Also, take care to yield the scheduler. Windows scheduling gives- // CPU to a busy looping process, which can cause the program causing the lock- // contention to be starved of CPU by node, so the contention doesn't resolve.- if (platform === "win32") {- fs.rename = (function (fs$rename) { return function (from, to, cb) {- var start = Date.now();- var backoff = 0;- fs$rename(from, to, function CB (er) {- if (er- && (er.code === "EACCES" || er.code === "EPERM")- && Date.now() - start < 60000) {- setTimeout(function() {- fs.stat(to, function (stater, st) {- if (stater && stater.code === "ENOENT")- fs$rename(from, to, CB);- else- cb(er);- });- }, backoff);- if (backoff < 100)- backoff += 10;- return;- }- if (cb) cb(er);- });- }})(fs.rename);- }-- // if read() returns EAGAIN, then just try it again.- fs.read = (function (fs$read) {- function read (fd, buffer, offset, length, position, callback_) {- var callback;- if (callback_ && typeof callback_ === 'function') {- var eagCounter = 0;- callback = function (er, _, __) {- if (er && er.code === 'EAGAIN' && eagCounter < 10) {- eagCounter ++;- return fs$read.call(fs, fd, buffer, offset, length, position, callback)- }- callback_.apply(this, arguments);- };- }- return fs$read.call(fs, fd, buffer, offset, length, position, callback)- }-- // This ensures `util.promisify` works as it does for native `fs.read`.- read.__proto__ = fs$read;- return read- })(fs.read);-- fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {- var eagCounter = 0;- while (true) {- try {- return fs$readSync.call(fs, fd, buffer, offset, length, position)- } catch (er) {- if (er.code === 'EAGAIN' && eagCounter < 10) {- eagCounter ++;- continue- }- throw er- }- }- }})(fs.readSync);-- function patchLchmod (fs) {- fs.lchmod = function (path, mode, callback) {- fs.open( path- , constants$4.O_WRONLY | constants$4.O_SYMLINK- , mode- , function (err, fd) {- if (err) {- if (callback) callback(err);- return- }- // prefer to return the chmod error, if one occurs,- // but still try to close, and report closing errors if they occur.- fs.fchmod(fd, mode, function (err) {- fs.close(fd, function(err2) {- if (callback) callback(err || err2);- });- });- });- };-- fs.lchmodSync = function (path, mode) {- var fd = fs.openSync(path, constants$4.O_WRONLY | constants$4.O_SYMLINK, mode);-- // prefer to return the chmod error, if one occurs,- // but still try to close, and report closing errors if they occur.- var threw = true;- var ret;- try {- ret = fs.fchmodSync(fd, mode);- threw = false;- } finally {- if (threw) {- try {- fs.closeSync(fd);- } catch (er) {}- } else {- fs.closeSync(fd);- }- }- return ret- };- }-- function patchLutimes (fs) {- if (constants$4.hasOwnProperty("O_SYMLINK")) {- fs.lutimes = function (path, at, mt, cb) {- fs.open(path, constants$4.O_SYMLINK, function (er, fd) {- if (er) {- if (cb) cb(er);- return- }- fs.futimes(fd, at, mt, function (er) {- fs.close(fd, function (er2) {- if (cb) cb(er || er2);- });- });- });- };-- fs.lutimesSync = function (path, at, mt) {- var fd = fs.openSync(path, constants$4.O_SYMLINK);- var ret;- var threw = true;- try {- ret = fs.futimesSync(fd, at, mt);- threw = false;- } finally {- if (threw) {- try {- fs.closeSync(fd);- } catch (er) {}- } else {- fs.closeSync(fd);- }- }- return ret- };-- } else {- fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };- fs.lutimesSync = function () {};- }- }-- function chmodFix (orig) {- if (!orig) return orig- return function (target, mode, cb) {- return orig.call(fs, target, mode, function (er) {- if (chownErOk(er)) er = null;- if (cb) cb.apply(this, arguments);- })- }- }-- function chmodFixSync (orig) {- if (!orig) return orig- return function (target, mode) {- try {- return orig.call(fs, target, mode)- } catch (er) {- if (!chownErOk(er)) throw er- }- }- }--- function chownFix (orig) {- if (!orig) return orig- return function (target, uid, gid, cb) {- return orig.call(fs, target, uid, gid, function (er) {- if (chownErOk(er)) er = null;- if (cb) cb.apply(this, arguments);- })- }- }-- function chownFixSync (orig) {- if (!orig) return orig- return function (target, uid, gid) {- try {- return orig.call(fs, target, uid, gid)- } catch (er) {- if (!chownErOk(er)) throw er- }- }- }-- function statFix (orig) {- if (!orig) return orig- // Older versions of Node erroneously returned signed integers for- // uid + gid.- return function (target, options, cb) {- if (typeof options === 'function') {- cb = options;- options = null;- }- function callback (er, stats) {- if (stats) {- if (stats.uid < 0) stats.uid += 0x100000000;- if (stats.gid < 0) stats.gid += 0x100000000;- }- if (cb) cb.apply(this, arguments);- }- return options ? orig.call(fs, target, options, callback)- : orig.call(fs, target, callback)- }- }-- function statFixSync (orig) {- if (!orig) return orig- // Older versions of Node erroneously returned signed integers for- // uid + gid.- return function (target, options) {- var stats = options ? orig.call(fs, target, options)- : orig.call(fs, target);- if (stats.uid < 0) stats.uid += 0x100000000;- if (stats.gid < 0) stats.gid += 0x100000000;- return stats;- }- }-- // ENOSYS means that the fs doesn't support the op. Just ignore- // that, because it doesn't matter.- //- // if there's no getuid, or if getuid() is something other- // than 0, and the error is EINVAL or EPERM, then just ignore- // it.- //- // This specific case is a silent failure in cp, install, tar,- // and most other unix tools that manage permissions.- //- // When running as root, or if other types of errors are- // encountered, then it's strict.- function chownErOk (er) {- if (!er)- return true-- if (er.code === "ENOSYS")- return true-- var nonroot = !process.getuid || process.getuid() !== 0;- if (nonroot) {- if (er.code === "EINVAL" || er.code === "EPERM")- return true- }-- return false- }-}--var Stream = Stream$2.Stream;--var legacyStreams = legacy;--function legacy (fs) {- return {- ReadStream: ReadStream,- WriteStream: WriteStream- }-- function ReadStream (path, options) {- if (!(this instanceof ReadStream)) return new ReadStream(path, options);-- Stream.call(this);-- var self = this;-- this.path = path;- this.fd = null;- this.readable = true;- this.paused = false;-- this.flags = 'r';- this.mode = 438; /*=0666*/- this.bufferSize = 64 * 1024;-- options = options || {};-- // Mixin options into this- var keys = Object.keys(options);- for (var index = 0, length = keys.length; index < length; index++) {- var key = keys[index];- this[key] = options[key];- }-- if (this.encoding) this.setEncoding(this.encoding);-- if (this.start !== undefined) {- if ('number' !== typeof this.start) {- throw TypeError('start must be a Number');- }- if (this.end === undefined) {- this.end = Infinity;- } else if ('number' !== typeof this.end) {- throw TypeError('end must be a Number');- }-- if (this.start > this.end) {- throw new Error('start must be <= end');- }-- this.pos = this.start;- }-- if (this.fd !== null) {- process.nextTick(function() {- self._read();- });- return;- }-- fs.open(this.path, this.flags, this.mode, function (err, fd) {- if (err) {- self.emit('error', err);- self.readable = false;- return;- }-- self.fd = fd;- self.emit('open', fd);- self._read();- });- }-- function WriteStream (path, options) {- if (!(this instanceof WriteStream)) return new WriteStream(path, options);-- Stream.call(this);-- this.path = path;- this.fd = null;- this.writable = true;-- this.flags = 'w';- this.encoding = 'binary';- this.mode = 438; /*=0666*/- this.bytesWritten = 0;-- options = options || {};-- // Mixin options into this- var keys = Object.keys(options);- for (var index = 0, length = keys.length; index < length; index++) {- var key = keys[index];- this[key] = options[key];- }-- if (this.start !== undefined) {- if ('number' !== typeof this.start) {- throw TypeError('start must be a Number');- }- if (this.start < 0) {- throw new Error('start must be >= zero');- }-- this.pos = this.start;- }-- this.busy = false;- this._queue = [];-- if (this.fd === null) {- this._open = fs.open;- this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);- this.flush();- }- }-}--var clone_1 = clone;--function clone (obj) {- if (obj === null || typeof obj !== 'object')- return obj-- if (obj instanceof Object)- var copy = { __proto__: obj.__proto__ };- else- var copy = Object.create(null);-- Object.getOwnPropertyNames(obj).forEach(function (key) {- Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));- });-- return copy-}--var gracefulFs = createCommonjsModule(function (module) {-/* istanbul ignore next - node 0.x polyfill */-var gracefulQueue;-var previousSymbol;--/* istanbul ignore else - node 0.x polyfill */-if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {- gracefulQueue = Symbol.for('graceful-fs.queue');- // This is used in testing by future versions- previousSymbol = Symbol.for('graceful-fs.previous');-} else {- gracefulQueue = '___graceful-fs.queue';- previousSymbol = '___graceful-fs.previous';-}--function noop () {}--var debug = noop;-if (util.debuglog)- debug = util.debuglog('gfs4');-else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))- debug = function() {- var m = util.format.apply(util, arguments);- m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');- console.error(m);- };--// Once time initialization-if (!commonjsGlobal[gracefulQueue]) {- // This queue can be shared by multiple loaded instances- var queue = [];- Object.defineProperty(commonjsGlobal, gracefulQueue, {- get: function() {- return queue- }- });-- // Patch fs.close/closeSync to shared queue version, because we need- // to retry() whenever a close happens *anywhere* in the program.- // This is essential when multiple graceful-fs instances are- // in play at the same time.- fs$2__default.close = (function (fs$close) {- function close (fd, cb) {- return fs$close.call(fs$2__default, fd, function (err) {- // This function uses the graceful-fs shared queue- if (!err) {- retry();- }-- if (typeof cb === 'function')- cb.apply(this, arguments);- })- }-- Object.defineProperty(close, previousSymbol, {- value: fs$close- });- return close- })(fs$2__default.close);-- fs$2__default.closeSync = (function (fs$closeSync) {- function closeSync (fd) {- // This function uses the graceful-fs shared queue- fs$closeSync.apply(fs$2__default, arguments);- retry();- }-- Object.defineProperty(closeSync, previousSymbol, {- value: fs$closeSync- });- return closeSync- })(fs$2__default.closeSync);-- if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {- process.on('exit', function() {- debug(commonjsGlobal[gracefulQueue]);- assert.equal(commonjsGlobal[gracefulQueue].length, 0);- });- }-}--module.exports = patch(clone_1(fs$2__default));-if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$2__default.__patched) {- module.exports = patch(fs$2__default);- fs$2__default.__patched = true;-}--function patch (fs) {- // Everything that references the open() function needs to be in here- polyfills(fs);- fs.gracefulify = patch;-- fs.createReadStream = createReadStream;- fs.createWriteStream = createWriteStream;- var fs$readFile = fs.readFile;- fs.readFile = readFile;- function readFile (path, options, cb) {- if (typeof options === 'function')- cb = options, options = null;-- return go$readFile(path, options, cb)-- function go$readFile (path, options, cb) {- return fs$readFile(path, options, function (err) {- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$readFile, [path, options, cb]]);- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- })- }- }-- var fs$writeFile = fs.writeFile;- fs.writeFile = writeFile;- function writeFile (path, data, options, cb) {- if (typeof options === 'function')- cb = options, options = null;-- return go$writeFile(path, data, options, cb)-- function go$writeFile (path, data, options, cb) {- return fs$writeFile(path, data, options, function (err) {- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$writeFile, [path, data, options, cb]]);- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- })- }- }-- var fs$appendFile = fs.appendFile;- if (fs$appendFile)- fs.appendFile = appendFile;- function appendFile (path, data, options, cb) {- if (typeof options === 'function')- cb = options, options = null;-- return go$appendFile(path, data, options, cb)-- function go$appendFile (path, data, options, cb) {- return fs$appendFile(path, data, options, function (err) {- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$appendFile, [path, data, options, cb]]);- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- })- }- }-- var fs$readdir = fs.readdir;- fs.readdir = readdir;- function readdir (path, options, cb) {- var args = [path];- if (typeof options !== 'function') {- args.push(options);- } else {- cb = options;- }- args.push(go$readdir$cb);-- return go$readdir(args)-- function go$readdir$cb (err, files) {- if (files && files.sort)- files.sort();-- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$readdir, [args]]);-- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- }- }-- function go$readdir (args) {- return fs$readdir.apply(fs, args)- }-- if (process.version.substr(0, 4) === 'v0.8') {- var legStreams = legacyStreams(fs);- ReadStream = legStreams.ReadStream;- WriteStream = legStreams.WriteStream;- }-- var fs$ReadStream = fs.ReadStream;- if (fs$ReadStream) {- ReadStream.prototype = Object.create(fs$ReadStream.prototype);- ReadStream.prototype.open = ReadStream$open;- }-- var fs$WriteStream = fs.WriteStream;- if (fs$WriteStream) {- WriteStream.prototype = Object.create(fs$WriteStream.prototype);- WriteStream.prototype.open = WriteStream$open;- }-- Object.defineProperty(fs, 'ReadStream', {- get: function () {- return ReadStream- },- set: function (val) {- ReadStream = val;- },- enumerable: true,- configurable: true- });- Object.defineProperty(fs, 'WriteStream', {- get: function () {- return WriteStream- },- set: function (val) {- WriteStream = val;- },- enumerable: true,- configurable: true- });-- // legacy names- var FileReadStream = ReadStream;- Object.defineProperty(fs, 'FileReadStream', {- get: function () {- return FileReadStream- },- set: function (val) {- FileReadStream = val;- },- enumerable: true,- configurable: true- });- var FileWriteStream = WriteStream;- Object.defineProperty(fs, 'FileWriteStream', {- get: function () {- return FileWriteStream- },- set: function (val) {- FileWriteStream = val;- },- enumerable: true,- configurable: true- });-- function ReadStream (path, options) {- if (this instanceof ReadStream)- return fs$ReadStream.apply(this, arguments), this- else- return ReadStream.apply(Object.create(ReadStream.prototype), arguments)- }-- function ReadStream$open () {- var that = this;- open(that.path, that.flags, that.mode, function (err, fd) {- if (err) {- if (that.autoClose)- that.destroy();-- that.emit('error', err);- } else {- that.fd = fd;- that.emit('open', fd);- that.read();- }- });- }-- function WriteStream (path, options) {- if (this instanceof WriteStream)- return fs$WriteStream.apply(this, arguments), this- else- return WriteStream.apply(Object.create(WriteStream.prototype), arguments)- }-- function WriteStream$open () {- var that = this;- open(that.path, that.flags, that.mode, function (err, fd) {- if (err) {- that.destroy();- that.emit('error', err);- } else {- that.fd = fd;- that.emit('open', fd);- }- });- }-- function createReadStream (path, options) {- return new fs.ReadStream(path, options)- }-- function createWriteStream (path, options) {- return new fs.WriteStream(path, options)- }-- var fs$open = fs.open;- fs.open = open;- function open (path, flags, mode, cb) {- if (typeof mode === 'function')- cb = mode, mode = null;-- return go$open(path, flags, mode, cb)-- function go$open (path, flags, mode, cb) {- return fs$open(path, flags, mode, function (err, fd) {- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$open, [path, flags, mode, cb]]);- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- })- }- }-- return fs-}--function enqueue (elem) {- debug('ENQUEUE', elem[0].name, elem[1]);- commonjsGlobal[gracefulQueue].push(elem);-}--function retry () {- var elem = commonjsGlobal[gracefulQueue].shift();- if (elem) {- debug('RETRY', elem[0].name, elem[1]);- elem[0].apply(null, elem[1]);- }-}-});--var fs_1 = createCommonjsModule(function (module, exports) {-// This is adapted from https://github.com/normalize/mz-// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors-const u = universalify.fromCallback;---const api = [- 'access',- 'appendFile',- 'chmod',- 'chown',- 'close',- 'copyFile',- 'fchmod',- 'fchown',- 'fdatasync',- 'fstat',- 'fsync',- 'ftruncate',- 'futimes',- 'lchmod',- 'lchown',- 'link',- 'lstat',- 'mkdir',- 'mkdtemp',- 'open',- 'opendir',- 'readdir',- 'readFile',- 'readlink',- 'realpath',- 'rename',- 'rmdir',- 'stat',- 'symlink',- 'truncate',- 'unlink',- 'utimes',- 'writeFile'-].filter(key => {- // Some commands are not available on some systems. Ex:- // fs.opendir was added in Node.js v12.12.0- // fs.lchown is not available on at least some Linux- return typeof gracefulFs[key] === 'function'-});--// Export all keys:-Object.keys(gracefulFs).forEach(key => {- if (key === 'promises') {- // fs.promises is a getter property that triggers ExperimentalWarning- // Don't re-export it here, the getter is defined in "lib/index.js"- return- }- exports[key] = gracefulFs[key];-});--// Universalify async methods:-api.forEach(method => {- exports[method] = u(gracefulFs[method]);-});--// We differ from mz/fs in that we still ship the old, broken, fs.exists()-// since we are a drop-in replacement for the native module-exports.exists = function (filename, callback) {- if (typeof callback === 'function') {- return gracefulFs.exists(filename, callback)- }- return new Promise(resolve => {- return gracefulFs.exists(filename, resolve)- })-};--// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args--exports.read = function (fd, buffer, offset, length, position, callback) {- if (typeof callback === 'function') {- return gracefulFs.read(fd, buffer, offset, length, position, callback)- }- return new Promise((resolve, reject) => {- gracefulFs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {- if (err) return reject(err)- resolve({ bytesRead, buffer });- });- })-};--// Function signature can be-// fs.write(fd, buffer[, offset[, length[, position]]], callback)-// OR-// fs.write(fd, string[, position[, encoding]], callback)-// We need to handle both cases, so we use ...args-exports.write = function (fd, buffer, ...args) {- if (typeof args[args.length - 1] === 'function') {- return gracefulFs.write(fd, buffer, ...args)- }-- return new Promise((resolve, reject) => {- gracefulFs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {- if (err) return reject(err)- resolve({ bytesWritten, buffer });- });- })-};--// fs.writev only available in Node v12.9.0+-if (typeof gracefulFs.writev === 'function') {- // Function signature is- // s.writev(fd, buffers[, position], callback)- // We need to handle the optional arg, so we use ...args- exports.writev = function (fd, buffers, ...args) {- if (typeof args[args.length - 1] === 'function') {- return gracefulFs.writev(fd, buffers, ...args)- }-- return new Promise((resolve, reject) => {- gracefulFs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {- if (err) return reject(err)- resolve({ bytesWritten, buffers });- });- })- };-}--// fs.realpath.native only available in Node v9.2+-if (typeof gracefulFs.realpath.native === 'function') {- exports.realpath.native = u(gracefulFs.realpath.native);-}-});--var atLeastNode = r => {- const n = process.versions.node.split('.').map(x => parseInt(x, 10));- r = r.split('.').map(x => parseInt(x, 10));- return n[0] > r[0] || (n[0] === r[0] && (n[1] > r[1] || (n[1] === r[1] && n[2] >= r[2])))-};--const useNativeRecursiveOption = atLeastNode('10.12.0');--// https://github.com/nodejs/node/issues/8987-// https://github.com/libuv/libuv/pull/1088-const checkPath = pth => {- if (process.platform === 'win32') {- const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path__default.parse(pth).root, ''));-- if (pathHasInvalidWinCharacters) {- const error = new Error(`Path contains invalid characters: ${pth}`);- error.code = 'EINVAL';- throw error- }- }-};--const processOptions = options => {- const defaults = { mode: 0o777 };- if (typeof options === 'number') options = { mode: options };- return { ...defaults, ...options }-};--const permissionError = pth => {- // This replicates the exception of `fs.mkdir` with native the- // `recusive` option when run on an invalid drive under Windows.- const error = new Error(`operation not permitted, mkdir '${pth}'`);- error.code = 'EPERM';- error.errno = -4048;- error.path = pth;- error.syscall = 'mkdir';- return error-};--var makeDir_1 = async (input, options) => {- checkPath(input);- options = processOptions(options);-- if (useNativeRecursiveOption) {- const pth = path__default.resolve(input);-- return fs_1.mkdir(pth, {- mode: options.mode,- recursive: true- })- }-- const make = async pth => {- try {- await fs_1.mkdir(pth, options.mode);- } catch (error) {- if (error.code === 'EPERM') {- throw error- }-- if (error.code === 'ENOENT') {- if (path__default.dirname(pth) === pth) {- throw permissionError(pth)- }-- if (error.message.includes('null bytes')) {- throw error- }-- await make(path__default.dirname(pth));- return make(pth)- }-- try {- const stats = await fs_1.stat(pth);- if (!stats.isDirectory()) {- // This error is never exposed to the user- // it is caught below, and the original error is thrown- throw new Error('The path is not a directory')- }- } catch {- throw error- }- }- };-- return make(path__default.resolve(input))-};--var makeDirSync = (input, options) => {- checkPath(input);- options = processOptions(options);-- if (useNativeRecursiveOption) {- const pth = path__default.resolve(input);-- return fs_1.mkdirSync(pth, {- mode: options.mode,- recursive: true- })- }-- const make = pth => {- try {- fs_1.mkdirSync(pth, options.mode);- } catch (error) {- if (error.code === 'EPERM') {- throw error- }-- if (error.code === 'ENOENT') {- if (path__default.dirname(pth) === pth) {- throw permissionError(pth)- }-- if (error.message.includes('null bytes')) {- throw error- }-- make(path__default.dirname(pth));- return make(pth)- }-- try {- if (!fs_1.statSync(pth).isDirectory()) {- // This error is never exposed to the user- // it is caught below, and the original error is thrown- throw new Error('The path is not a directory')- }- } catch {- throw error- }- }- };-- return make(path__default.resolve(input))-};--var makeDir = {- makeDir: makeDir_1,- makeDirSync: makeDirSync-};--const u = universalify.fromPromise;-const { makeDir: _makeDir, makeDirSync: makeDirSync$1 } = makeDir;-const makeDir$1 = u(_makeDir);--var mkdirs = {- mkdirs: makeDir$1,- mkdirsSync: makeDirSync$1,- // alias- mkdirp: makeDir$1,- mkdirpSync: makeDirSync$1,- ensureDir: makeDir$1,- ensureDirSync: makeDirSync$1-};--function utimesMillis (path, atime, mtime, callback) {- // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)- gracefulFs.open(path, 'r+', (err, fd) => {- if (err) return callback(err)- gracefulFs.futimes(fd, atime, mtime, futimesErr => {- gracefulFs.close(fd, closeErr => {- if (callback) callback(futimesErr || closeErr);- });- });- });-}--function utimesMillisSync (path, atime, mtime) {- const fd = gracefulFs.openSync(path, 'r+');- gracefulFs.futimesSync(fd, atime, mtime);- return gracefulFs.closeSync(fd)-}--var utimes = {- utimesMillis,- utimesMillisSync-};--const nodeSupportsBigInt = atLeastNode('10.5.0');-const stat = (file) => nodeSupportsBigInt ? fs_1.stat(file, { bigint: true }) : fs_1.stat(file);-const statSync = (file) => nodeSupportsBigInt ? fs_1.statSync(file, { bigint: true }) : fs_1.statSync(file);--function getStats (src, dest) {- return Promise.all([- stat(src),- stat(dest).catch(err => {- if (err.code === 'ENOENT') return null- throw err- })- ]).then(([srcStat, destStat]) => ({ srcStat, destStat }))-}--function getStatsSync (src, dest) {- let destStat;- const srcStat = statSync(src);- try {- destStat = statSync(dest);- } catch (err) {- if (err.code === 'ENOENT') return { srcStat, destStat: null }- throw err- }- return { srcStat, destStat }-}--function checkPaths (src, dest, funcName, cb) {- util.callbackify(getStats)(src, dest, (err, stats) => {- if (err) return cb(err)- const { srcStat, destStat } = stats;- if (destStat && areIdentical(srcStat, destStat)) {- return cb(new Error('Source and destination must not be the same.'))- }- if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {- return cb(new Error(errMsg(src, dest, funcName)))- }- return cb(null, { srcStat, destStat })- });-}--function checkPathsSync (src, dest, funcName) {- const { srcStat, destStat } = getStatsSync(src, dest);- if (destStat && areIdentical(srcStat, destStat)) {- throw new Error('Source and destination must not be the same.')- }- if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {- throw new Error(errMsg(src, dest, funcName))- }- return { srcStat, destStat }-}--// recursively check if dest parent is a subdirectory of src.-// It works for all file types including symlinks since it-// checks the src and dest inodes. It starts from the deepest-// parent and stops once it reaches the src parent or the root path.-function checkParentPaths (src, srcStat, dest, funcName, cb) {- const srcParent = path__default.resolve(path__default.dirname(src));- const destParent = path__default.resolve(path__default.dirname(dest));- if (destParent === srcParent || destParent === path__default.parse(destParent).root) return cb()- const callback = (err, destStat) => {- if (err) {- if (err.code === 'ENOENT') return cb()- return cb(err)- }- if (areIdentical(srcStat, destStat)) {- return cb(new Error(errMsg(src, dest, funcName)))- }- return checkParentPaths(src, srcStat, destParent, funcName, cb)- };- if (nodeSupportsBigInt) fs_1.stat(destParent, { bigint: true }, callback);- else fs_1.stat(destParent, callback);-}--function checkParentPathsSync (src, srcStat, dest, funcName) {- const srcParent = path__default.resolve(path__default.dirname(src));- const destParent = path__default.resolve(path__default.dirname(dest));- if (destParent === srcParent || destParent === path__default.parse(destParent).root) return- let destStat;- try {- destStat = statSync(destParent);- } catch (err) {- if (err.code === 'ENOENT') return- throw err- }- if (areIdentical(srcStat, destStat)) {- throw new Error(errMsg(src, dest, funcName))- }- return checkParentPathsSync(src, srcStat, destParent, funcName)-}--function areIdentical (srcStat, destStat) {- if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) {- if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) {- // definitive answer- return true- }- // Use additional heuristics if we can't use 'bigint'.- // Different 'ino' could be represented the same if they are >= Number.MAX_SAFE_INTEGER- // See issue 657- if (destStat.size === srcStat.size &&- destStat.mode === srcStat.mode &&- destStat.nlink === srcStat.nlink &&- destStat.atimeMs === srcStat.atimeMs &&- destStat.mtimeMs === srcStat.mtimeMs &&- destStat.ctimeMs === srcStat.ctimeMs &&- destStat.birthtimeMs === srcStat.birthtimeMs) {- // heuristic answer- return true- }- }- return false-}--// return true if dest is a subdir of src, otherwise false.-// It only checks the path strings.-function isSrcSubdir (src, dest) {- const srcArr = path__default.resolve(src).split(path__default.sep).filter(i => i);- const destArr = path__default.resolve(dest).split(path__default.sep).filter(i => i);- return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true)-}--function errMsg (src, dest, funcName) {- return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`-}--var stat_1 = {- checkPaths,- checkPathsSync,- checkParentPaths,- checkParentPathsSync,- isSrcSubdir-};--const mkdirsSync = mkdirs.mkdirsSync;-const utimesMillisSync$1 = utimes.utimesMillisSync;---function copySync (src, dest, opts) {- if (typeof opts === 'function') {- opts = { filter: opts };- }-- opts = opts || {};- opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now- opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber-- // Warn about using preserveTimestamps on 32-bit node- if (opts.preserveTimestamps && process.arch === 'ia32') {- console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n- see https://github.com/jprichardson/node-fs-extra/issues/269`);- }-- const { srcStat, destStat } = stat_1.checkPathsSync(src, dest, 'copy');- stat_1.checkParentPathsSync(src, srcStat, dest, 'copy');- return handleFilterAndCopy(destStat, src, dest, opts)-}--function handleFilterAndCopy (destStat, src, dest, opts) {- if (opts.filter && !opts.filter(src, dest)) return- const destParent = path__default.dirname(dest);- if (!gracefulFs.existsSync(destParent)) mkdirsSync(destParent);- return startCopy(destStat, src, dest, opts)-}--function startCopy (destStat, src, dest, opts) {- if (opts.filter && !opts.filter(src, dest)) return- return getStats$1(destStat, src, dest, opts)-}--function getStats$1 (destStat, src, dest, opts) {- const statSync = opts.dereference ? gracefulFs.statSync : gracefulFs.lstatSync;- const srcStat = statSync(src);-- if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)- else if (srcStat.isFile() ||- srcStat.isCharacterDevice() ||- srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)- else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)-}--function onFile (srcStat, destStat, src, dest, opts) {- if (!destStat) return copyFile(srcStat, src, dest, opts)- return mayCopyFile(srcStat, src, dest, opts)-}--function mayCopyFile (srcStat, src, dest, opts) {- if (opts.overwrite) {- gracefulFs.unlinkSync(dest);- return copyFile(srcStat, src, dest, opts)- } else if (opts.errorOnExist) {- throw new Error(`'${dest}' already exists`)- }-}--function copyFile (srcStat, src, dest, opts) {- gracefulFs.copyFileSync(src, dest);- if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest);- return setDestMode(dest, srcStat.mode)-}--function handleTimestamps (srcMode, src, dest) {- // Make sure the file is writable before setting the timestamp- // otherwise open fails with EPERM when invoked with 'r+'- // (through utimes call)- if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode);- return setDestTimestamps(src, dest)-}--function fileIsNotWritable (srcMode) {- return (srcMode & 0o200) === 0-}--function makeFileWritable (dest, srcMode) {- return setDestMode(dest, srcMode | 0o200)-}--function setDestMode (dest, srcMode) {- return gracefulFs.chmodSync(dest, srcMode)-}--function setDestTimestamps (src, dest) {- // The initial srcStat.atime cannot be trusted- // because it is modified by the read(2) system call- // (See https://nodejs.org/api/fs.html#fs_stat_time_values)- const updatedSrcStat = gracefulFs.statSync(src);- return utimesMillisSync$1(dest, updatedSrcStat.atime, updatedSrcStat.mtime)-}--function onDir (srcStat, destStat, src, dest, opts) {- if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)- if (destStat && !destStat.isDirectory()) {- throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)- }- return copyDir(src, dest, opts)-}--function mkDirAndCopy (srcMode, src, dest, opts) {- gracefulFs.mkdirSync(dest);- copyDir(src, dest, opts);- return setDestMode(dest, srcMode)-}--function copyDir (src, dest, opts) {- gracefulFs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts));-}--function copyDirItem (item, src, dest, opts) {- const srcItem = path__default.join(src, item);- const destItem = path__default.join(dest, item);- const { destStat } = stat_1.checkPathsSync(srcItem, destItem, 'copy');- return startCopy(destStat, srcItem, destItem, opts)-}--function onLink (destStat, src, dest, opts) {- let resolvedSrc = gracefulFs.readlinkSync(src);- if (opts.dereference) {- resolvedSrc = path__default.resolve(process.cwd(), resolvedSrc);- }-- if (!destStat) {- return gracefulFs.symlinkSync(resolvedSrc, dest)- } else {- let resolvedDest;- try {- resolvedDest = gracefulFs.readlinkSync(dest);- } catch (err) {- // dest exists and is a regular file or directory,- // Windows may throw UNKNOWN error. If dest already exists,- // fs throws error anyway, so no need to guard against it here.- if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return gracefulFs.symlinkSync(resolvedSrc, dest)- throw err- }- if (opts.dereference) {- resolvedDest = path__default.resolve(process.cwd(), resolvedDest);- }- if (stat_1.isSrcSubdir(resolvedSrc, resolvedDest)) {- throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)- }-- // prevent copy if src is a subdir of dest since unlinking- // dest in this case would result in removing src contents- // and therefore a broken symlink would be created.- if (gracefulFs.statSync(dest).isDirectory() && stat_1.isSrcSubdir(resolvedDest, resolvedSrc)) {- throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)- }- return copyLink(resolvedSrc, dest)- }-}--function copyLink (resolvedSrc, dest) {- gracefulFs.unlinkSync(dest);- return gracefulFs.symlinkSync(resolvedSrc, dest)-}--var copySync_1 = copySync;--var copySync$1 = {- copySync: copySync_1-};--const u$1 = universalify.fromPromise;---function pathExists (path) {- return fs_1.access(path).then(() => true).catch(() => false)-}--var pathExists_1 = {- pathExists: u$1(pathExists),- pathExistsSync: fs_1.existsSync-};--const mkdirs$1 = mkdirs.mkdirs;-const pathExists$1 = pathExists_1.pathExists;-const utimesMillis$1 = utimes.utimesMillis;---function copy (src, dest, opts, cb) {- if (typeof opts === 'function' && !cb) {- cb = opts;- opts = {};- } else if (typeof opts === 'function') {- opts = { filter: opts };- }-- cb = cb || function () {};- opts = opts || {};-- opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now- opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber-- // Warn about using preserveTimestamps on 32-bit node- if (opts.preserveTimestamps && process.arch === 'ia32') {- console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n- see https://github.com/jprichardson/node-fs-extra/issues/269`);- }-- stat_1.checkPaths(src, dest, 'copy', (err, stats) => {- if (err) return cb(err)- const { srcStat, destStat } = stats;- stat_1.checkParentPaths(src, srcStat, dest, 'copy', err => {- if (err) return cb(err)- if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb)- return checkParentDir(destStat, src, dest, opts, cb)- });- });-}--function checkParentDir (destStat, src, dest, opts, cb) {- const destParent = path__default.dirname(dest);- pathExists$1(destParent, (err, dirExists) => {- if (err) return cb(err)- if (dirExists) return startCopy$1(destStat, src, dest, opts, cb)- mkdirs$1(destParent, err => {- if (err) return cb(err)- return startCopy$1(destStat, src, dest, opts, cb)- });- });-}--function handleFilter (onInclude, destStat, src, dest, opts, cb) {- Promise.resolve(opts.filter(src, dest)).then(include => {- if (include) return onInclude(destStat, src, dest, opts, cb)- return cb()- }, error => cb(error));-}--function startCopy$1 (destStat, src, dest, opts, cb) {- if (opts.filter) return handleFilter(getStats$2, destStat, src, dest, opts, cb)- return getStats$2(destStat, src, dest, opts, cb)-}--function getStats$2 (destStat, src, dest, opts, cb) {- const stat = opts.dereference ? gracefulFs.stat : gracefulFs.lstat;- stat(src, (err, srcStat) => {- if (err) return cb(err)-- if (srcStat.isDirectory()) return onDir$1(srcStat, destStat, src, dest, opts, cb)- else if (srcStat.isFile() ||- srcStat.isCharacterDevice() ||- srcStat.isBlockDevice()) return onFile$1(srcStat, destStat, src, dest, opts, cb)- else if (srcStat.isSymbolicLink()) return onLink$1(destStat, src, dest, opts, cb)- });-}--function onFile$1 (srcStat, destStat, src, dest, opts, cb) {- if (!destStat) return copyFile$1(srcStat, src, dest, opts, cb)- return mayCopyFile$1(srcStat, src, dest, opts, cb)-}--function mayCopyFile$1 (srcStat, src, dest, opts, cb) {- if (opts.overwrite) {- gracefulFs.unlink(dest, err => {- if (err) return cb(err)- return copyFile$1(srcStat, src, dest, opts, cb)- });- } else if (opts.errorOnExist) {- return cb(new Error(`'${dest}' already exists`))- } else return cb()-}--function copyFile$1 (srcStat, src, dest, opts, cb) {- gracefulFs.copyFile(src, dest, err => {- if (err) return cb(err)- if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb)- return setDestMode$1(dest, srcStat.mode, cb)- });-}--function handleTimestampsAndMode (srcMode, src, dest, cb) {- // Make sure the file is writable before setting the timestamp- // otherwise open fails with EPERM when invoked with 'r+'- // (through utimes call)- if (fileIsNotWritable$1(srcMode)) {- return makeFileWritable$1(dest, srcMode, err => {- if (err) return cb(err)- return setDestTimestampsAndMode(srcMode, src, dest, cb)- })- }- return setDestTimestampsAndMode(srcMode, src, dest, cb)-}--function fileIsNotWritable$1 (srcMode) {- return (srcMode & 0o200) === 0-}--function makeFileWritable$1 (dest, srcMode, cb) {- return setDestMode$1(dest, srcMode | 0o200, cb)-}--function setDestTimestampsAndMode (srcMode, src, dest, cb) {- setDestTimestamps$1(src, dest, err => {- if (err) return cb(err)- return setDestMode$1(dest, srcMode, cb)- });-}--function setDestMode$1 (dest, srcMode, cb) {- return gracefulFs.chmod(dest, srcMode, cb)-}--function setDestTimestamps$1 (src, dest, cb) {- // The initial srcStat.atime cannot be trusted- // because it is modified by the read(2) system call- // (See https://nodejs.org/api/fs.html#fs_stat_time_values)- gracefulFs.stat(src, (err, updatedSrcStat) => {- if (err) return cb(err)- return utimesMillis$1(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb)- });-}--function onDir$1 (srcStat, destStat, src, dest, opts, cb) {- if (!destStat) return mkDirAndCopy$1(srcStat.mode, src, dest, opts, cb)- if (destStat && !destStat.isDirectory()) {- return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))- }- return copyDir$1(src, dest, opts, cb)-}--function mkDirAndCopy$1 (srcMode, src, dest, opts, cb) {- gracefulFs.mkdir(dest, err => {- if (err) return cb(err)- copyDir$1(src, dest, opts, err => {- if (err) return cb(err)- return setDestMode$1(dest, srcMode, cb)- });- });-}--function copyDir$1 (src, dest, opts, cb) {- gracefulFs.readdir(src, (err, items) => {- if (err) return cb(err)- return copyDirItems(items, src, dest, opts, cb)- });-}--function copyDirItems (items, src, dest, opts, cb) {- const item = items.pop();- if (!item) return cb()- return copyDirItem$1(items, item, src, dest, opts, cb)-}--function copyDirItem$1 (items, item, src, dest, opts, cb) {- const srcItem = path__default.join(src, item);- const destItem = path__default.join(dest, item);- stat_1.checkPaths(srcItem, destItem, 'copy', (err, stats) => {- if (err) return cb(err)- const { destStat } = stats;- startCopy$1(destStat, srcItem, destItem, opts, err => {- if (err) return cb(err)- return copyDirItems(items, src, dest, opts, cb)- });- });-}--function onLink$1 (destStat, src, dest, opts, cb) {- gracefulFs.readlink(src, (err, resolvedSrc) => {- if (err) return cb(err)- if (opts.dereference) {- resolvedSrc = path__default.resolve(process.cwd(), resolvedSrc);- }-- if (!destStat) {- return gracefulFs.symlink(resolvedSrc, dest, cb)- } else {- gracefulFs.readlink(dest, (err, resolvedDest) => {- if (err) {- // dest exists and is a regular file or directory,- // Windows may throw UNKNOWN error. If dest already exists,- // fs throws error anyway, so no need to guard against it here.- if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return gracefulFs.symlink(resolvedSrc, dest, cb)- return cb(err)- }- if (opts.dereference) {- resolvedDest = path__default.resolve(process.cwd(), resolvedDest);- }- if (stat_1.isSrcSubdir(resolvedSrc, resolvedDest)) {- return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`))- }-- // do not copy if src is a subdir of dest since unlinking- // dest in this case would result in removing src contents- // and therefore a broken symlink would be created.- if (destStat.isDirectory() && stat_1.isSrcSubdir(resolvedDest, resolvedSrc)) {- return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))- }- return copyLink$1(resolvedSrc, dest, cb)- });- }- });-}--function copyLink$1 (resolvedSrc, dest, cb) {- gracefulFs.unlink(dest, err => {- if (err) return cb(err)- return gracefulFs.symlink(resolvedSrc, dest, cb)- });-}--var copy_1 = copy;--const u$2 = universalify.fromCallback;-var copy$1 = {- copy: u$2(copy_1)-};--const isWindows = (process.platform === 'win32');--function defaults (options) {- const methods = [- 'unlink',- 'chmod',- 'stat',- 'lstat',- 'rmdir',- 'readdir'- ];- methods.forEach(m => {- options[m] = options[m] || gracefulFs[m];- m = m + 'Sync';- options[m] = options[m] || gracefulFs[m];- });-- options.maxBusyTries = options.maxBusyTries || 3;-}--function rimraf (p, options, cb) {- let busyTries = 0;-- if (typeof options === 'function') {- cb = options;- options = {};- }-- assert(p, 'rimraf: missing path');- assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string');- assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required');- assert(options, 'rimraf: invalid options argument provided');- assert.strictEqual(typeof options, 'object', 'rimraf: options should be object');-- defaults(options);-- rimraf_(p, options, function CB (er) {- if (er) {- if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') &&- busyTries < options.maxBusyTries) {- busyTries++;- const time = busyTries * 100;- // try again, with the same exact callback as this one.- return setTimeout(() => rimraf_(p, options, CB), time)- }-- // already gone- if (er.code === 'ENOENT') er = null;- }-- cb(er);- });-}--// Two possible strategies.-// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR-// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR-//-// Both result in an extra syscall when you guess wrong. However, there-// are likely far more normal files in the world than directories. This-// is based on the assumption that a the average number of files per-// directory is >= 1.-//-// If anyone ever complains about this, then I guess the strategy could-// be made configurable somehow. But until then, YAGNI.-function rimraf_ (p, options, cb) {- assert(p);- assert(options);- assert(typeof cb === 'function');-- // sunos lets the root user unlink directories, which is... weird.- // so we have to lstat here and make sure it's not a dir.- options.lstat(p, (er, st) => {- if (er && er.code === 'ENOENT') {- return cb(null)- }-- // Windows can EPERM on stat. Life is suffering.- if (er && er.code === 'EPERM' && isWindows) {- return fixWinEPERM(p, options, er, cb)- }-- if (st && st.isDirectory()) {- return rmdir(p, options, er, cb)- }-- options.unlink(p, er => {- if (er) {- if (er.code === 'ENOENT') {- return cb(null)- }- if (er.code === 'EPERM') {- return (isWindows)- ? fixWinEPERM(p, options, er, cb)- : rmdir(p, options, er, cb)- }- if (er.code === 'EISDIR') {- return rmdir(p, options, er, cb)- }- }- return cb(er)- });- });-}--function fixWinEPERM (p, options, er, cb) {- assert(p);- assert(options);- assert(typeof cb === 'function');-- options.chmod(p, 0o666, er2 => {- if (er2) {- cb(er2.code === 'ENOENT' ? null : er);- } else {- options.stat(p, (er3, stats) => {- if (er3) {- cb(er3.code === 'ENOENT' ? null : er);- } else if (stats.isDirectory()) {- rmdir(p, options, er, cb);- } else {- options.unlink(p, cb);- }- });- }- });-}--function fixWinEPERMSync (p, options, er) {- let stats;-- assert(p);- assert(options);-- try {- options.chmodSync(p, 0o666);- } catch (er2) {- if (er2.code === 'ENOENT') {- return- } else {- throw er- }- }-- try {- stats = options.statSync(p);- } catch (er3) {- if (er3.code === 'ENOENT') {- return- } else {- throw er- }- }-- if (stats.isDirectory()) {- rmdirSync(p, options, er);- } else {- options.unlinkSync(p);- }-}--function rmdir (p, options, originalEr, cb) {- assert(p);- assert(options);- assert(typeof cb === 'function');-- // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)- // if we guessed wrong, and it's not a directory, then- // raise the original error.- options.rmdir(p, er => {- if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {- rmkids(p, options, cb);- } else if (er && er.code === 'ENOTDIR') {- cb(originalEr);- } else {- cb(er);- }- });-}--function rmkids (p, options, cb) {- assert(p);- assert(options);- assert(typeof cb === 'function');-- options.readdir(p, (er, files) => {- if (er) return cb(er)-- let n = files.length;- let errState;-- if (n === 0) return options.rmdir(p, cb)-- files.forEach(f => {- rimraf(path__default.join(p, f), options, er => {- if (errState) {- return- }- if (er) return cb(errState = er)- if (--n === 0) {- options.rmdir(p, cb);- }- });- });- });-}--// this looks simpler, and is strictly *faster*, but will-// tie up the JavaScript thread and fail on excessively-// deep directory trees.-function rimrafSync (p, options) {- let st;-- options = options || {};- defaults(options);-- assert(p, 'rimraf: missing path');- assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string');- assert(options, 'rimraf: missing options');- assert.strictEqual(typeof options, 'object', 'rimraf: options should be object');-- try {- st = options.lstatSync(p);- } catch (er) {- if (er.code === 'ENOENT') {- return- }-- // Windows can EPERM on stat. Life is suffering.- if (er.code === 'EPERM' && isWindows) {- fixWinEPERMSync(p, options, er);- }- }-- try {- // sunos lets the root user unlink directories, which is... weird.- if (st && st.isDirectory()) {- rmdirSync(p, options, null);- } else {- options.unlinkSync(p);- }- } catch (er) {- if (er.code === 'ENOENT') {- return- } else if (er.code === 'EPERM') {- return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)- } else if (er.code !== 'EISDIR') {- throw er- }- rmdirSync(p, options, er);- }-}--function rmdirSync (p, options, originalEr) {- assert(p);- assert(options);-- try {- options.rmdirSync(p);- } catch (er) {- if (er.code === 'ENOTDIR') {- throw originalEr- } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') {- rmkidsSync(p, options);- } else if (er.code !== 'ENOENT') {- throw er- }- }-}--function rmkidsSync (p, options) {- assert(p);- assert(options);- options.readdirSync(p).forEach(f => rimrafSync(path__default.join(p, f), options));-- if (isWindows) {- // We only end up here once we got ENOTEMPTY at least once, and- // at this point, we are guaranteed to have removed all the kids.- // So, we know that it won't be ENOENT or ENOTDIR or anything else.- // try really hard to delete stuff on windows, because it has a- // PROFOUNDLY annoying habit of not closing handles promptly when- // files are deleted, resulting in spurious ENOTEMPTY errors.- const startTime = Date.now();- do {- try {- const ret = options.rmdirSync(p, options);- return ret- } catch {}- } while (Date.now() - startTime < 500) // give up after 500ms- } else {- const ret = options.rmdirSync(p, options);- return ret- }-}--var rimraf_1 = rimraf;-rimraf.sync = rimrafSync;--const u$3 = universalify.fromCallback;---var remove = {- remove: u$3(rimraf_1),- removeSync: rimraf_1.sync-};--const u$4 = universalify.fromCallback;------const emptyDir = u$4(function emptyDir (dir, callback) {- callback = callback || function () {};- gracefulFs.readdir(dir, (err, items) => {- if (err) return mkdirs.mkdirs(dir, callback)-- items = items.map(item => path__default.join(dir, item));-- deleteItem();-- function deleteItem () {- const item = items.pop();- if (!item) return callback()- remove.remove(item, err => {- if (err) return callback(err)- deleteItem();- });- }- });-});--function emptyDirSync (dir) {- let items;- try {- items = gracefulFs.readdirSync(dir);- } catch {- return mkdirs.mkdirsSync(dir)- }-- items.forEach(item => {- item = path__default.join(dir, item);- remove.removeSync(item);- });-}--var empty = {- emptyDirSync,- emptydirSync: emptyDirSync,- emptyDir,- emptydir: emptyDir-};--const u$5 = universalify.fromCallback;-----function createFile (file, callback) {- function makeFile () {- gracefulFs.writeFile(file, '', err => {- if (err) return callback(err)- callback();- });- }-- gracefulFs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err- if (!err && stats.isFile()) return callback()- const dir = path__default.dirname(file);- gracefulFs.stat(dir, (err, stats) => {- if (err) {- // if the directory doesn't exist, make it- if (err.code === 'ENOENT') {- return mkdirs.mkdirs(dir, err => {- if (err) return callback(err)- makeFile();- })- }- return callback(err)- }-- if (stats.isDirectory()) makeFile();- else {- // parent is not a directory- // This is just to cause an internal ENOTDIR error to be thrown- gracefulFs.readdir(dir, err => {- if (err) return callback(err)- });- }- });- });-}--function createFileSync (file) {- let stats;- try {- stats = gracefulFs.statSync(file);- } catch {}- if (stats && stats.isFile()) return-- const dir = path__default.dirname(file);- try {- if (!gracefulFs.statSync(dir).isDirectory()) {- // parent is not a directory- // This is just to cause an internal ENOTDIR error to be thrown- gracefulFs.readdirSync(dir);- }- } catch (err) {- // If the stat call above failed because the directory doesn't exist, create it- if (err && err.code === 'ENOENT') mkdirs.mkdirsSync(dir);- else throw err- }-- gracefulFs.writeFileSync(file, '');-}--var file = {- createFile: u$5(createFile),- createFileSync-};--const u$6 = universalify.fromCallback;----const pathExists$2 = pathExists_1.pathExists;--function createLink (srcpath, dstpath, callback) {- function makeLink (srcpath, dstpath) {- gracefulFs.link(srcpath, dstpath, err => {- if (err) return callback(err)- callback(null);- });- }-- pathExists$2(dstpath, (err, destinationExists) => {- if (err) return callback(err)- if (destinationExists) return callback(null)- gracefulFs.lstat(srcpath, (err) => {- if (err) {- err.message = err.message.replace('lstat', 'ensureLink');- return callback(err)- }-- const dir = path__default.dirname(dstpath);- pathExists$2(dir, (err, dirExists) => {- if (err) return callback(err)- if (dirExists) return makeLink(srcpath, dstpath)- mkdirs.mkdirs(dir, err => {- if (err) return callback(err)- makeLink(srcpath, dstpath);- });- });- });- });-}--function createLinkSync (srcpath, dstpath) {- const destinationExists = gracefulFs.existsSync(dstpath);- if (destinationExists) return undefined-- try {- gracefulFs.lstatSync(srcpath);- } catch (err) {- err.message = err.message.replace('lstat', 'ensureLink');- throw err- }-- const dir = path__default.dirname(dstpath);- const dirExists = gracefulFs.existsSync(dir);- if (dirExists) return gracefulFs.linkSync(srcpath, dstpath)- mkdirs.mkdirsSync(dir);-- return gracefulFs.linkSync(srcpath, dstpath)-}--var link = {- createLink: u$6(createLink),- createLinkSync-};--const pathExists$3 = pathExists_1.pathExists;--/**- * Function that returns two types of paths, one relative to symlink, and one- * relative to the current working directory. Checks if path is absolute or- * relative. If the path is relative, this function checks if the path is- * relative to symlink or relative to current working directory. This is an- * initiative to find a smarter `srcpath` to supply when building symlinks.- * This allows you to determine which path to use out of one of three possible- * types of source paths. The first is an absolute path. This is detected by- * `path.isAbsolute()`. When an absolute path is provided, it is checked to- * see if it exists. If it does it's used, if not an error is returned- * (callback)/ thrown (sync). The other two options for `srcpath` are a- * relative url. By default Node's `fs.symlink` works by creating a symlink- * using `dstpath` and expects the `srcpath` to be relative to the newly- * created symlink. If you provide a `srcpath` that does not exist on the file- * system it results in a broken symlink. To minimize this, the function- * checks to see if the 'relative to symlink' source file exists, and if it- * does it will use it. If it does not, it checks if there's a file that- * exists that is relative to the current working directory, if does its used.- * This preserves the expectations of the original fs.symlink spec and adds- * the ability to pass in `relative to current working direcotry` paths.- */--function symlinkPaths (srcpath, dstpath, callback) {- if (path__default.isAbsolute(srcpath)) {- return gracefulFs.lstat(srcpath, (err) => {- if (err) {- err.message = err.message.replace('lstat', 'ensureSymlink');- return callback(err)- }- return callback(null, {- toCwd: srcpath,- toDst: srcpath- })- })- } else {- const dstdir = path__default.dirname(dstpath);- const relativeToDst = path__default.join(dstdir, srcpath);- return pathExists$3(relativeToDst, (err, exists) => {- if (err) return callback(err)- if (exists) {- return callback(null, {- toCwd: relativeToDst,- toDst: srcpath- })- } else {- return gracefulFs.lstat(srcpath, (err) => {- if (err) {- err.message = err.message.replace('lstat', 'ensureSymlink');- return callback(err)- }- return callback(null, {- toCwd: srcpath,- toDst: path__default.relative(dstdir, srcpath)- })- })- }- })- }-}--function symlinkPathsSync (srcpath, dstpath) {- let exists;- if (path__default.isAbsolute(srcpath)) {- exists = gracefulFs.existsSync(srcpath);- if (!exists) throw new Error('absolute srcpath does not exist')- return {- toCwd: srcpath,- toDst: srcpath- }- } else {- const dstdir = path__default.dirname(dstpath);- const relativeToDst = path__default.join(dstdir, srcpath);- exists = gracefulFs.existsSync(relativeToDst);- if (exists) {- return {- toCwd: relativeToDst,- toDst: srcpath- }- } else {- exists = gracefulFs.existsSync(srcpath);- if (!exists) throw new Error('relative srcpath does not exist')- return {- toCwd: srcpath,- toDst: path__default.relative(dstdir, srcpath)- }- }- }-}--var symlinkPaths_1 = {- symlinkPaths,- symlinkPathsSync-};--function symlinkType (srcpath, type, callback) {- callback = (typeof type === 'function') ? type : callback;- type = (typeof type === 'function') ? false : type;- if (type) return callback(null, type)- gracefulFs.lstat(srcpath, (err, stats) => {- if (err) return callback(null, 'file')- type = (stats && stats.isDirectory()) ? 'dir' : 'file';- callback(null, type);- });-}--function symlinkTypeSync (srcpath, type) {- let stats;-- if (type) return type- try {- stats = gracefulFs.lstatSync(srcpath);- } catch {- return 'file'- }- return (stats && stats.isDirectory()) ? 'dir' : 'file'-}--var symlinkType_1 = {- symlinkType,- symlinkTypeSync-};--const u$7 = universalify.fromCallback;----const mkdirs$2 = mkdirs.mkdirs;-const mkdirsSync$1 = mkdirs.mkdirsSync;---const symlinkPaths$1 = symlinkPaths_1.symlinkPaths;-const symlinkPathsSync$1 = symlinkPaths_1.symlinkPathsSync;---const symlinkType$1 = symlinkType_1.symlinkType;-const symlinkTypeSync$1 = symlinkType_1.symlinkTypeSync;--const pathExists$4 = pathExists_1.pathExists;--function createSymlink (srcpath, dstpath, type, callback) {- callback = (typeof type === 'function') ? type : callback;- type = (typeof type === 'function') ? false : type;-- pathExists$4(dstpath, (err, destinationExists) => {- if (err) return callback(err)- if (destinationExists) return callback(null)- symlinkPaths$1(srcpath, dstpath, (err, relative) => {- if (err) return callback(err)- srcpath = relative.toDst;- symlinkType$1(relative.toCwd, type, (err, type) => {- if (err) return callback(err)- const dir = path__default.dirname(dstpath);- pathExists$4(dir, (err, dirExists) => {- if (err) return callback(err)- if (dirExists) return gracefulFs.symlink(srcpath, dstpath, type, callback)- mkdirs$2(dir, err => {- if (err) return callback(err)- gracefulFs.symlink(srcpath, dstpath, type, callback);- });- });- });- });- });-}--function createSymlinkSync (srcpath, dstpath, type) {- const destinationExists = gracefulFs.existsSync(dstpath);- if (destinationExists) return undefined-- const relative = symlinkPathsSync$1(srcpath, dstpath);- srcpath = relative.toDst;- type = symlinkTypeSync$1(relative.toCwd, type);- const dir = path__default.dirname(dstpath);- const exists = gracefulFs.existsSync(dir);- if (exists) return gracefulFs.symlinkSync(srcpath, dstpath, type)- mkdirsSync$1(dir);- return gracefulFs.symlinkSync(srcpath, dstpath, type)-}--var symlink = {- createSymlink: u$7(createSymlink),- createSymlinkSync-};--var ensure = {- // file- createFile: file.createFile,- createFileSync: file.createFileSync,- ensureFile: file.createFile,- ensureFileSync: file.createFileSync,- // link- createLink: link.createLink,- createLinkSync: link.createLinkSync,- ensureLink: link.createLink,- ensureLinkSync: link.createLinkSync,- // symlink- createSymlink: symlink.createSymlink,- createSymlinkSync: symlink.createSymlinkSync,- ensureSymlink: symlink.createSymlink,- ensureSymlinkSync: symlink.createSymlinkSync-};--var origCwd$1 = process.cwd;-var cwd$1 = null;--var platform$1 = process.env.GRACEFUL_FS_PLATFORM || process.platform;--process.cwd = function() {- if (!cwd$1)- cwd$1 = origCwd$1.call(process);- return cwd$1-};-try {- process.cwd();-} catch (er) {}--var chdir$1 = process.chdir;-process.chdir = function(d) {- cwd$1 = null;- chdir$1.call(process, d);-};--var polyfills$1 = patch$1;--function patch$1 (fs) {- // (re-)implement some things that are known busted or missing.-- // lchmod, broken prior to 0.6.2- // back-port the fix here.- if (constants$4.hasOwnProperty('O_SYMLINK') &&- process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {- patchLchmod(fs);- }-- // lutimes implementation, or no-op- if (!fs.lutimes) {- patchLutimes(fs);- }-- // https://github.com/isaacs/node-graceful-fs/issues/4- // Chown should not fail on einval or eperm if non-root.- // It should not fail on enosys ever, as this just indicates- // that a fs doesn't support the intended operation.-- fs.chown = chownFix(fs.chown);- fs.fchown = chownFix(fs.fchown);- fs.lchown = chownFix(fs.lchown);-- fs.chmod = chmodFix(fs.chmod);- fs.fchmod = chmodFix(fs.fchmod);- fs.lchmod = chmodFix(fs.lchmod);-- fs.chownSync = chownFixSync(fs.chownSync);- fs.fchownSync = chownFixSync(fs.fchownSync);- fs.lchownSync = chownFixSync(fs.lchownSync);-- fs.chmodSync = chmodFixSync(fs.chmodSync);- fs.fchmodSync = chmodFixSync(fs.fchmodSync);- fs.lchmodSync = chmodFixSync(fs.lchmodSync);-- fs.stat = statFix(fs.stat);- fs.fstat = statFix(fs.fstat);- fs.lstat = statFix(fs.lstat);-- fs.statSync = statFixSync(fs.statSync);- fs.fstatSync = statFixSync(fs.fstatSync);- fs.lstatSync = statFixSync(fs.lstatSync);-- // if lchmod/lchown do not exist, then make them no-ops- if (!fs.lchmod) {- fs.lchmod = function (path, mode, cb) {- if (cb) process.nextTick(cb);- };- fs.lchmodSync = function () {};- }- if (!fs.lchown) {- fs.lchown = function (path, uid, gid, cb) {- if (cb) process.nextTick(cb);- };- fs.lchownSync = function () {};- }-- // on Windows, A/V software can lock the directory, causing this- // to fail with an EACCES or EPERM if the directory contains newly- // created files. Try again on failure, for up to 60 seconds.-- // Set the timeout this long because some Windows Anti-Virus, such as Parity- // bit9, may lock files for up to a minute, causing npm package install- // failures. Also, take care to yield the scheduler. Windows scheduling gives- // CPU to a busy looping process, which can cause the program causing the lock- // contention to be starved of CPU by node, so the contention doesn't resolve.- if (platform$1 === "win32") {- fs.rename = (function (fs$rename) { return function (from, to, cb) {- var start = Date.now();- var backoff = 0;- fs$rename(from, to, function CB (er) {- if (er- && (er.code === "EACCES" || er.code === "EPERM")- && Date.now() - start < 60000) {- setTimeout(function() {- fs.stat(to, function (stater, st) {- if (stater && stater.code === "ENOENT")- fs$rename(from, to, CB);- else- cb(er);- });- }, backoff);- if (backoff < 100)- backoff += 10;- return;- }- if (cb) cb(er);- });- }})(fs.rename);- }-- // if read() returns EAGAIN, then just try it again.- fs.read = (function (fs$read) {- function read (fd, buffer, offset, length, position, callback_) {- var callback;- if (callback_ && typeof callback_ === 'function') {- var eagCounter = 0;- callback = function (er, _, __) {- if (er && er.code === 'EAGAIN' && eagCounter < 10) {- eagCounter ++;- return fs$read.call(fs, fd, buffer, offset, length, position, callback)- }- callback_.apply(this, arguments);- };- }- return fs$read.call(fs, fd, buffer, offset, length, position, callback)- }-- // This ensures `util.promisify` works as it does for native `fs.read`.- read.__proto__ = fs$read;- return read- })(fs.read);-- fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {- var eagCounter = 0;- while (true) {- try {- return fs$readSync.call(fs, fd, buffer, offset, length, position)- } catch (er) {- if (er.code === 'EAGAIN' && eagCounter < 10) {- eagCounter ++;- continue- }- throw er- }- }- }})(fs.readSync);-- function patchLchmod (fs) {- fs.lchmod = function (path, mode, callback) {- fs.open( path- , constants$4.O_WRONLY | constants$4.O_SYMLINK- , mode- , function (err, fd) {- if (err) {- if (callback) callback(err);- return- }- // prefer to return the chmod error, if one occurs,- // but still try to close, and report closing errors if they occur.- fs.fchmod(fd, mode, function (err) {- fs.close(fd, function(err2) {- if (callback) callback(err || err2);- });- });- });- };-- fs.lchmodSync = function (path, mode) {- var fd = fs.openSync(path, constants$4.O_WRONLY | constants$4.O_SYMLINK, mode);-- // prefer to return the chmod error, if one occurs,- // but still try to close, and report closing errors if they occur.- var threw = true;- var ret;- try {- ret = fs.fchmodSync(fd, mode);- threw = false;- } finally {- if (threw) {- try {- fs.closeSync(fd);- } catch (er) {}- } else {- fs.closeSync(fd);- }- }- return ret- };- }-- function patchLutimes (fs) {- if (constants$4.hasOwnProperty("O_SYMLINK")) {- fs.lutimes = function (path, at, mt, cb) {- fs.open(path, constants$4.O_SYMLINK, function (er, fd) {- if (er) {- if (cb) cb(er);- return- }- fs.futimes(fd, at, mt, function (er) {- fs.close(fd, function (er2) {- if (cb) cb(er || er2);- });- });- });- };-- fs.lutimesSync = function (path, at, mt) {- var fd = fs.openSync(path, constants$4.O_SYMLINK);- var ret;- var threw = true;- try {- ret = fs.futimesSync(fd, at, mt);- threw = false;- } finally {- if (threw) {- try {- fs.closeSync(fd);- } catch (er) {}- } else {- fs.closeSync(fd);- }- }- return ret- };-- } else {- fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };- fs.lutimesSync = function () {};- }- }-- function chmodFix (orig) {- if (!orig) return orig- return function (target, mode, cb) {- return orig.call(fs, target, mode, function (er) {- if (chownErOk(er)) er = null;- if (cb) cb.apply(this, arguments);- })- }- }-- function chmodFixSync (orig) {- if (!orig) return orig- return function (target, mode) {- try {- return orig.call(fs, target, mode)- } catch (er) {- if (!chownErOk(er)) throw er- }- }- }--- function chownFix (orig) {- if (!orig) return orig- return function (target, uid, gid, cb) {- return orig.call(fs, target, uid, gid, function (er) {- if (chownErOk(er)) er = null;- if (cb) cb.apply(this, arguments);- })- }- }-- function chownFixSync (orig) {- if (!orig) return orig- return function (target, uid, gid) {- try {- return orig.call(fs, target, uid, gid)- } catch (er) {- if (!chownErOk(er)) throw er- }- }- }-- function statFix (orig) {- if (!orig) return orig- // Older versions of Node erroneously returned signed integers for- // uid + gid.- return function (target, options, cb) {- if (typeof options === 'function') {- cb = options;- options = null;- }- function callback (er, stats) {- if (stats) {- if (stats.uid < 0) stats.uid += 0x100000000;- if (stats.gid < 0) stats.gid += 0x100000000;- }- if (cb) cb.apply(this, arguments);- }- return options ? orig.call(fs, target, options, callback)- : orig.call(fs, target, callback)- }- }-- function statFixSync (orig) {- if (!orig) return orig- // Older versions of Node erroneously returned signed integers for- // uid + gid.- return function (target, options) {- var stats = options ? orig.call(fs, target, options)- : orig.call(fs, target);- if (stats.uid < 0) stats.uid += 0x100000000;- if (stats.gid < 0) stats.gid += 0x100000000;- return stats;- }- }-- // ENOSYS means that the fs doesn't support the op. Just ignore- // that, because it doesn't matter.- //- // if there's no getuid, or if getuid() is something other- // than 0, and the error is EINVAL or EPERM, then just ignore- // it.- //- // This specific case is a silent failure in cp, install, tar,- // and most other unix tools that manage permissions.- //- // When running as root, or if other types of errors are- // encountered, then it's strict.- function chownErOk (er) {- if (!er)- return true-- if (er.code === "ENOSYS")- return true-- var nonroot = !process.getuid || process.getuid() !== 0;- if (nonroot) {- if (er.code === "EINVAL" || er.code === "EPERM")- return true- }-- return false- }-}--var Stream$1 = Stream$2.Stream;--var legacyStreams$1 = legacy$1;--function legacy$1 (fs) {- return {- ReadStream: ReadStream,- WriteStream: WriteStream- }-- function ReadStream (path, options) {- if (!(this instanceof ReadStream)) return new ReadStream(path, options);-- Stream$1.call(this);-- var self = this;-- this.path = path;- this.fd = null;- this.readable = true;- this.paused = false;-- this.flags = 'r';- this.mode = 438; /*=0666*/- this.bufferSize = 64 * 1024;-- options = options || {};-- // Mixin options into this- var keys = Object.keys(options);- for (var index = 0, length = keys.length; index < length; index++) {- var key = keys[index];- this[key] = options[key];- }-- if (this.encoding) this.setEncoding(this.encoding);-- if (this.start !== undefined) {- if ('number' !== typeof this.start) {- throw TypeError('start must be a Number');- }- if (this.end === undefined) {- this.end = Infinity;- } else if ('number' !== typeof this.end) {- throw TypeError('end must be a Number');- }-- if (this.start > this.end) {- throw new Error('start must be <= end');- }-- this.pos = this.start;- }-- if (this.fd !== null) {- process.nextTick(function() {- self._read();- });- return;- }-- fs.open(this.path, this.flags, this.mode, function (err, fd) {- if (err) {- self.emit('error', err);- self.readable = false;- return;- }-- self.fd = fd;- self.emit('open', fd);- self._read();- });- }-- function WriteStream (path, options) {- if (!(this instanceof WriteStream)) return new WriteStream(path, options);-- Stream$1.call(this);-- this.path = path;- this.fd = null;- this.writable = true;-- this.flags = 'w';- this.encoding = 'binary';- this.mode = 438; /*=0666*/- this.bytesWritten = 0;-- options = options || {};-- // Mixin options into this- var keys = Object.keys(options);- for (var index = 0, length = keys.length; index < length; index++) {- var key = keys[index];- this[key] = options[key];- }-- if (this.start !== undefined) {- if ('number' !== typeof this.start) {- throw TypeError('start must be a Number');- }- if (this.start < 0) {- throw new Error('start must be >= zero');- }-- this.pos = this.start;- }-- this.busy = false;- this._queue = [];-- if (this.fd === null) {- this._open = fs.open;- this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);- this.flush();- }- }-}--var clone_1$1 = clone$1;--function clone$1 (obj) {- if (obj === null || typeof obj !== 'object')- return obj-- if (obj instanceof Object)- var copy = { __proto__: obj.__proto__ };- else- var copy = Object.create(null);-- Object.getOwnPropertyNames(obj).forEach(function (key) {- Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));- });-- return copy-}--var gracefulFs$1 = createCommonjsModule(function (module) {-/* istanbul ignore next - node 0.x polyfill */-var gracefulQueue;-var previousSymbol;--/* istanbul ignore else - node 0.x polyfill */-if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {- gracefulQueue = Symbol.for('graceful-fs.queue');- // This is used in testing by future versions- previousSymbol = Symbol.for('graceful-fs.previous');-} else {- gracefulQueue = '___graceful-fs.queue';- previousSymbol = '___graceful-fs.previous';-}--function noop () {}--var debug = noop;-if (util.debuglog)- debug = util.debuglog('gfs4');-else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))- debug = function() {- var m = util.format.apply(util, arguments);- m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');- console.error(m);- };--// Once time initialization-if (!commonjsGlobal[gracefulQueue]) {- // This queue can be shared by multiple loaded instances- var queue = [];- Object.defineProperty(commonjsGlobal, gracefulQueue, {- get: function() {- return queue- }- });-- // Patch fs.close/closeSync to shared queue version, because we need- // to retry() whenever a close happens *anywhere* in the program.- // This is essential when multiple graceful-fs instances are- // in play at the same time.- fs$2__default.close = (function (fs$close) {- function close (fd, cb) {- return fs$close.call(fs$2__default, fd, function (err) {- // This function uses the graceful-fs shared queue- if (!err) {- retry();- }-- if (typeof cb === 'function')- cb.apply(this, arguments);- })- }-- Object.defineProperty(close, previousSymbol, {- value: fs$close- });- return close- })(fs$2__default.close);-- fs$2__default.closeSync = (function (fs$closeSync) {- function closeSync (fd) {- // This function uses the graceful-fs shared queue- fs$closeSync.apply(fs$2__default, arguments);- retry();- }-- Object.defineProperty(closeSync, previousSymbol, {- value: fs$closeSync- });- return closeSync- })(fs$2__default.closeSync);-- if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {- process.on('exit', function() {- debug(commonjsGlobal[gracefulQueue]);- assert.equal(commonjsGlobal[gracefulQueue].length, 0);- });- }-}--module.exports = patch(clone_1$1(fs$2__default));-if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$2__default.__patched) {- module.exports = patch(fs$2__default);- fs$2__default.__patched = true;-}--function patch (fs) {- // Everything that references the open() function needs to be in here- polyfills$1(fs);- fs.gracefulify = patch;-- fs.createReadStream = createReadStream;- fs.createWriteStream = createWriteStream;- var fs$readFile = fs.readFile;- fs.readFile = readFile;- function readFile (path, options, cb) {- if (typeof options === 'function')- cb = options, options = null;-- return go$readFile(path, options, cb)-- function go$readFile (path, options, cb) {- return fs$readFile(path, options, function (err) {- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$readFile, [path, options, cb]]);- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- })- }- }-- var fs$writeFile = fs.writeFile;- fs.writeFile = writeFile;- function writeFile (path, data, options, cb) {- if (typeof options === 'function')- cb = options, options = null;-- return go$writeFile(path, data, options, cb)-- function go$writeFile (path, data, options, cb) {- return fs$writeFile(path, data, options, function (err) {- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$writeFile, [path, data, options, cb]]);- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- })- }- }-- var fs$appendFile = fs.appendFile;- if (fs$appendFile)- fs.appendFile = appendFile;- function appendFile (path, data, options, cb) {- if (typeof options === 'function')- cb = options, options = null;-- return go$appendFile(path, data, options, cb)-- function go$appendFile (path, data, options, cb) {- return fs$appendFile(path, data, options, function (err) {- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$appendFile, [path, data, options, cb]]);- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- })- }- }-- var fs$readdir = fs.readdir;- fs.readdir = readdir;- function readdir (path, options, cb) {- var args = [path];- if (typeof options !== 'function') {- args.push(options);- } else {- cb = options;- }- args.push(go$readdir$cb);-- return go$readdir(args)-- function go$readdir$cb (err, files) {- if (files && files.sort)- files.sort();-- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$readdir, [args]]);-- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- }- }-- function go$readdir (args) {- return fs$readdir.apply(fs, args)- }-- if (process.version.substr(0, 4) === 'v0.8') {- var legStreams = legacyStreams$1(fs);- ReadStream = legStreams.ReadStream;- WriteStream = legStreams.WriteStream;- }-- var fs$ReadStream = fs.ReadStream;- if (fs$ReadStream) {- ReadStream.prototype = Object.create(fs$ReadStream.prototype);- ReadStream.prototype.open = ReadStream$open;- }-- var fs$WriteStream = fs.WriteStream;- if (fs$WriteStream) {- WriteStream.prototype = Object.create(fs$WriteStream.prototype);- WriteStream.prototype.open = WriteStream$open;- }-- Object.defineProperty(fs, 'ReadStream', {- get: function () {- return ReadStream- },- set: function (val) {- ReadStream = val;- },- enumerable: true,- configurable: true- });- Object.defineProperty(fs, 'WriteStream', {- get: function () {- return WriteStream- },- set: function (val) {- WriteStream = val;- },- enumerable: true,- configurable: true- });-- // legacy names- var FileReadStream = ReadStream;- Object.defineProperty(fs, 'FileReadStream', {- get: function () {- return FileReadStream- },- set: function (val) {- FileReadStream = val;- },- enumerable: true,- configurable: true- });- var FileWriteStream = WriteStream;- Object.defineProperty(fs, 'FileWriteStream', {- get: function () {- return FileWriteStream- },- set: function (val) {- FileWriteStream = val;- },- enumerable: true,- configurable: true- });-- function ReadStream (path, options) {- if (this instanceof ReadStream)- return fs$ReadStream.apply(this, arguments), this- else- return ReadStream.apply(Object.create(ReadStream.prototype), arguments)- }-- function ReadStream$open () {- var that = this;- open(that.path, that.flags, that.mode, function (err, fd) {- if (err) {- if (that.autoClose)- that.destroy();-- that.emit('error', err);- } else {- that.fd = fd;- that.emit('open', fd);- that.read();- }- });- }-- function WriteStream (path, options) {- if (this instanceof WriteStream)- return fs$WriteStream.apply(this, arguments), this- else- return WriteStream.apply(Object.create(WriteStream.prototype), arguments)- }-- function WriteStream$open () {- var that = this;- open(that.path, that.flags, that.mode, function (err, fd) {- if (err) {- that.destroy();- that.emit('error', err);- } else {- that.fd = fd;- that.emit('open', fd);- }- });- }-- function createReadStream (path, options) {- return new fs.ReadStream(path, options)- }-- function createWriteStream (path, options) {- return new fs.WriteStream(path, options)- }-- var fs$open = fs.open;- fs.open = open;- function open (path, flags, mode, cb) {- if (typeof mode === 'function')- cb = mode, mode = null;-- return go$open(path, flags, mode, cb)-- function go$open (path, flags, mode, cb) {- return fs$open(path, flags, mode, function (err, fd) {- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))- enqueue([go$open, [path, flags, mode, cb]]);- else {- if (typeof cb === 'function')- cb.apply(this, arguments);- retry();- }- })- }- }-- return fs-}--function enqueue (elem) {- debug('ENQUEUE', elem[0].name, elem[1]);- commonjsGlobal[gracefulQueue].push(elem);-}--function retry () {- var elem = commonjsGlobal[gracefulQueue].shift();- if (elem) {- debug('RETRY', elem[0].name, elem[1]);- elem[0].apply(null, elem[1]);- }-}-});--function stringify (obj, options = {}) {- const EOL = options.EOL || '\n';-- const str = JSON.stringify(obj, options ? options.replacer : null, options.spaces);-- return str.replace(/\n/g, EOL) + EOL-}--function stripBom (content) {- // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified- if (Buffer.isBuffer(content)) content = content.toString('utf8');- return content.replace(/^\uFEFF/, '')-}--var utils = { stringify, stripBom };--let _fs;-try {- _fs = gracefulFs$1;-} catch (_) {- _fs = fs$2__default;-}--const { stringify: stringify$1, stripBom: stripBom$1 } = utils;--async function _readFile (file, options = {}) {- if (typeof options === 'string') {- options = { encoding: options };- }-- const fs = options.fs || _fs;-- const shouldThrow = 'throws' in options ? options.throws : true;-- let data = await universalify.fromCallback(fs.readFile)(file, options);-- data = stripBom$1(data);-- let obj;- try {- obj = JSON.parse(data, options ? options.reviver : null);- } catch (err) {- if (shouldThrow) {- err.message = `${file}: ${err.message}`;- throw err- } else {- return null- }- }-- return obj-}--const readFile = universalify.fromPromise(_readFile);--function readFileSync (file, options = {}) {- if (typeof options === 'string') {- options = { encoding: options };- }-- const fs = options.fs || _fs;-- const shouldThrow = 'throws' in options ? options.throws : true;-- try {- let content = fs.readFileSync(file, options);- content = stripBom$1(content);- return JSON.parse(content, options.reviver)- } catch (err) {- if (shouldThrow) {- err.message = `${file}: ${err.message}`;- throw err- } else {- return null- }- }-}--async function _writeFile (file, obj, options = {}) {- const fs = options.fs || _fs;-- const str = stringify$1(obj, options);-- await universalify.fromCallback(fs.writeFile)(file, str, options);-}--const writeFile = universalify.fromPromise(_writeFile);--function writeFileSync (file, obj, options = {}) {- const fs = options.fs || _fs;-- const str = stringify$1(obj, options);- // not sure if fs.writeFileSync returns anything, but just in case- return fs.writeFileSync(file, str, options)-}--const jsonfile = {- readFile,- readFileSync,- writeFile,- writeFileSync-};--var jsonfile_1 = jsonfile;--var jsonfile$1 = {- // jsonfile exports- readJson: jsonfile_1.readFile,- readJsonSync: jsonfile_1.readFileSync,- writeJson: jsonfile_1.writeFile,- writeJsonSync: jsonfile_1.writeFileSync-};--const u$8 = universalify.fromCallback;----const pathExists$5 = pathExists_1.pathExists;--function outputFile (file, data, encoding, callback) {- if (typeof encoding === 'function') {- callback = encoding;- encoding = 'utf8';- }-- const dir = path__default.dirname(file);- pathExists$5(dir, (err, itDoes) => {- if (err) return callback(err)- if (itDoes) return gracefulFs.writeFile(file, data, encoding, callback)-- mkdirs.mkdirs(dir, err => {- if (err) return callback(err)-- gracefulFs.writeFile(file, data, encoding, callback);- });- });-}--function outputFileSync (file, ...args) {- const dir = path__default.dirname(file);- if (gracefulFs.existsSync(dir)) {- return gracefulFs.writeFileSync(file, ...args)- }- mkdirs.mkdirsSync(dir);- gracefulFs.writeFileSync(file, ...args);-}--var output = {- outputFile: u$8(outputFile),- outputFileSync-};--const { stringify: stringify$2 } = utils;-const { outputFile: outputFile$1 } = output;--async function outputJson (file, data, options = {}) {- const str = stringify$2(data, options);-- await outputFile$1(file, str, options);-}--var outputJson_1 = outputJson;--const { stringify: stringify$3 } = utils;-const { outputFileSync: outputFileSync$1 } = output;--function outputJsonSync (file, data, options) {- const str = stringify$3(data, options);-- outputFileSync$1(file, str, options);-}--var outputJsonSync_1 = outputJsonSync;--const u$9 = universalify.fromPromise;---jsonfile$1.outputJson = u$9(outputJson_1);-jsonfile$1.outputJsonSync = outputJsonSync_1;-// aliases-jsonfile$1.outputJSON = jsonfile$1.outputJson;-jsonfile$1.outputJSONSync = jsonfile$1.outputJsonSync;-jsonfile$1.writeJSON = jsonfile$1.writeJson;-jsonfile$1.writeJSONSync = jsonfile$1.writeJsonSync;-jsonfile$1.readJSON = jsonfile$1.readJson;-jsonfile$1.readJSONSync = jsonfile$1.readJsonSync;--var json = jsonfile$1;--const copySync$2 = copySync$1.copySync;-const removeSync = remove.removeSync;-const mkdirpSync = mkdirs.mkdirpSync;---function moveSync (src, dest, opts) {- opts = opts || {};- const overwrite = opts.overwrite || opts.clobber || false;-- const { srcStat } = stat_1.checkPathsSync(src, dest, 'move');- stat_1.checkParentPathsSync(src, srcStat, dest, 'move');- mkdirpSync(path__default.dirname(dest));- return doRename(src, dest, overwrite)-}--function doRename (src, dest, overwrite) {- if (overwrite) {- removeSync(dest);- return rename(src, dest, overwrite)- }- if (gracefulFs.existsSync(dest)) throw new Error('dest already exists.')- return rename(src, dest, overwrite)-}--function rename (src, dest, overwrite) {- try {- gracefulFs.renameSync(src, dest);- } catch (err) {- if (err.code !== 'EXDEV') throw err- return moveAcrossDevice(src, dest, overwrite)- }-}--function moveAcrossDevice (src, dest, overwrite) {- const opts = {- overwrite,- errorOnExist: true- };- copySync$2(src, dest, opts);- return removeSync(src)-}--var moveSync_1 = moveSync;--var moveSync$1 = {- moveSync: moveSync_1-};--const copy$2 = copy$1.copy;-const remove$1 = remove.remove;-const mkdirp = mkdirs.mkdirp;-const pathExists$6 = pathExists_1.pathExists;---function move (src, dest, opts, cb) {- if (typeof opts === 'function') {- cb = opts;- opts = {};- }-- const overwrite = opts.overwrite || opts.clobber || false;-- stat_1.checkPaths(src, dest, 'move', (err, stats) => {- if (err) return cb(err)- const { srcStat } = stats;- stat_1.checkParentPaths(src, srcStat, dest, 'move', err => {- if (err) return cb(err)- mkdirp(path__default.dirname(dest), err => {- if (err) return cb(err)- return doRename$1(src, dest, overwrite, cb)- });- });- });-}--function doRename$1 (src, dest, overwrite, cb) {- if (overwrite) {- return remove$1(dest, err => {- if (err) return cb(err)- return rename$1(src, dest, overwrite, cb)- })- }- pathExists$6(dest, (err, destExists) => {- if (err) return cb(err)- if (destExists) return cb(new Error('dest already exists.'))- return rename$1(src, dest, overwrite, cb)- });-}--function rename$1 (src, dest, overwrite, cb) {- gracefulFs.rename(src, dest, err => {- if (!err) return cb()- if (err.code !== 'EXDEV') return cb(err)- return moveAcrossDevice$1(src, dest, overwrite, cb)- });-}--function moveAcrossDevice$1 (src, dest, overwrite, cb) {- const opts = {- overwrite,- errorOnExist: true- };- copy$2(src, dest, opts, err => {- if (err) return cb(err)- return remove$1(src, cb)- });-}--var move_1 = move;--const u$a = universalify.fromCallback;-var move$1 = {- move: u$a(move_1)-};--var lib = createCommonjsModule(function (module) {--module.exports = {- // Export promiseified graceful-fs:- ...fs_1,- // Export extra methods:- ...copySync$1,- ...copy$1,- ...empty,- ...ensure,- ...json,- ...mkdirs,- ...moveSync$1,- ...move$1,- ...output,- ...pathExists_1,- ...remove-};--// Export fs.promises as a getter property so that we don't trigger-// ExperimentalWarning before fs.promises is actually accessed.--if (Object.getOwnPropertyDescriptor(fs$2__default, 'promises')) {- Object.defineProperty(module.exports, 'promises', {- get () { return fs$2__default.promises }- });-}-});--const resolveFrom = (fromDirectory, moduleId, silent) => {- if (typeof fromDirectory !== 'string') {- throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``);- }-- if (typeof moduleId !== 'string') {- throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);- }-- try {- fromDirectory = fs$2__default.realpathSync(fromDirectory);- } catch (error) {- if (error.code === 'ENOENT') {- fromDirectory = path__default.resolve(fromDirectory);- } else if (silent) {- return;- } else {- throw error;- }- }-- const fromFile = path__default.join(fromDirectory, 'noop.js');-- const resolveFileName = () => Module._resolveFilename(moduleId, {- id: fromFile,- filename: fromFile,- paths: Module._nodeModulePaths(fromDirectory)- });-- if (silent) {- try {- return resolveFileName();- } catch (error) {- return;- }- }-- return resolveFileName();-};--var resolveFrom_1 = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId);-var silent = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId, true);-resolveFrom_1.silent = silent;--/* eslint-disable no-unused-expressions */-const builtinTypes = ['String', 'Float', 'Int', 'Boolean', 'ID', 'Upload'];-const builtinDirectives = [- 'deprecated',- 'skip',- 'include',- 'cacheControl',- 'key',- 'external',- 'requires',- 'provides',- 'connection',- 'client',-];-const IMPORT_FROM_REGEX = /^import\s+(\*|(.*))\s+from\s+('|")(.*)('|");?$/;-const IMPORT_DEFAULT_REGEX = /^import\s+('|")(.*)('|");?$/;-function processImport(filePath, cwd = process.cwd(), predefinedImports = {}) {- const visitedFiles = new Map();- const set = visitFile(filePath, path.join(cwd + '/root.graphql'), visitedFiles, predefinedImports);- const definitionSet = new Set();- for (const defs of set.values()) {- for (const def of defs) {- definitionSet.add(def);- }- }- return {- kind: Kind.DOCUMENT,- definitions: [...definitionSet],- };-}-function visitFile(filePath, cwd, visitedFiles, predefinedImports) {- if (!path.isAbsolute(filePath) && !(filePath in predefinedImports)) {- filePath = resolveFilePath(cwd, filePath);- }- if (!visitedFiles.has(filePath)) {- const fileContent = filePath in predefinedImports ? predefinedImports[filePath] : lib.readFileSync(filePath, 'utf8');- const importLines = [];- let otherLines = '';- for (const line of fileContent.split('\n')) {- const trimmedLine = line.trim();- if (trimmedLine.startsWith('#import ') || trimmedLine.startsWith('# import ')) {- importLines.push(trimmedLine);- }- else if (trimmedLine) {- otherLines += line + '\n';- }- }- const definitionsByName = new Map();- const dependenciesByDefinitionName = new Map();- if (otherLines) {- const fileDefinitionMap = new Map();- // To prevent circular dependency- visitedFiles.set(filePath, fileDefinitionMap);- const document = parse(new Source(otherLines, filePath), {- noLocation: true,- });- for (const definition of document.definitions) {- if ('name' in definition || definition.kind === Kind.SCHEMA_DEFINITION) {- const definitionName = 'name' in definition ? definition.name.value : 'schema';- if (!definitionsByName.has(definitionName)) {- definitionsByName.set(definitionName, new Set());- }- const definitionsSet = definitionsByName.get(definitionName);- definitionsSet.add(definition);- if (!dependenciesByDefinitionName.has(definitionName)) {- dependenciesByDefinitionName.set(definitionName, new Set());- }- const dependencySet = dependenciesByDefinitionName.get(definitionName);- switch (definition.kind) {- case Kind.OPERATION_DEFINITION:- visitOperationDefinitionNode(definition, dependencySet);- break;- case Kind.FRAGMENT_DEFINITION:- visitFragmentDefinitionNode(definition, dependencySet);- break;- case Kind.OBJECT_TYPE_DEFINITION:- visitObjectTypeDefinitionNode(definition, dependencySet, dependenciesByDefinitionName);- break;- case Kind.INTERFACE_TYPE_DEFINITION:- visitInterfaceTypeDefinitionNode(definition, dependencySet, dependenciesByDefinitionName);- break;- case Kind.UNION_TYPE_DEFINITION:- visitUnionTypeDefinitionNode(definition, dependencySet);- break;- case Kind.ENUM_TYPE_DEFINITION:- visitEnumTypeDefinitionNode(definition, dependencySet);- break;- case Kind.INPUT_OBJECT_TYPE_DEFINITION:- visitInputObjectTypeDefinitionNode(definition, dependencySet);- break;- case Kind.DIRECTIVE_DEFINITION:- visitDirectiveDefinitionNode(definition, dependencySet);- break;- case Kind.SCALAR_TYPE_DEFINITION:- visitScalarDefinitionNode(definition, dependencySet);- break;- case Kind.SCHEMA_DEFINITION:- visitSchemaDefinitionNode(definition, dependencySet);- break;- case Kind.OBJECT_TYPE_EXTENSION:- visitObjectTypeExtensionNode(definition, dependencySet, dependenciesByDefinitionName);- break;- case Kind.INTERFACE_TYPE_EXTENSION:- visitInterfaceTypeExtensionNode(definition, dependencySet, dependenciesByDefinitionName);- break;- case Kind.UNION_TYPE_EXTENSION:- visitUnionTypeExtensionNode(definition, dependencySet);- break;- case Kind.ENUM_TYPE_EXTENSION:- visitEnumTypeExtensionNode(definition, dependencySet);- break;- case Kind.INPUT_OBJECT_TYPE_EXTENSION:- visitInputObjectTypeExtensionNode(definition, dependencySet);- break;- case Kind.SCALAR_TYPE_EXTENSION:- visitScalarExtensionNode(definition, dependencySet);- break;- }- if ('fields' in definition) {- for (const field of definition.fields) {- const definitionName = definition.name.value + '.' + field.name.value;- if (!definitionsByName.has(definitionName)) {- definitionsByName.set(definitionName, new Set());- }- const definitionsSet = definitionsByName.get(definitionName);- definitionsSet.add({- ...definition,- fields: [field],- });- if (!dependenciesByDefinitionName.has(definitionName)) {- dependenciesByDefinitionName.set(definitionName, new Set());- }- const dependencySet = dependenciesByDefinitionName.get(definitionName);- switch (field.kind) {- case Kind.FIELD_DEFINITION:- visitFieldDefinitionNode(field, dependencySet);- break;- case Kind.INPUT_VALUE_DEFINITION:- visitInputValueDefinitionNode(field, dependencySet);- break;- }- }- }- }- }- for (const [definitionName, definitions] of definitionsByName) {- if (!fileDefinitionMap.has(definitionName)) {- fileDefinitionMap.set(definitionName, new Set());- }- const definitionsWithDependencies = fileDefinitionMap.get(definitionName);- for (const definition of definitions) {- definitionsWithDependencies.add(definition);- }- const dependenciesOfDefinition = dependenciesByDefinitionName.get(definitionName);- for (const dependencyName of dependenciesOfDefinition) {- const dependencyDefinitions = definitionsByName.get(dependencyName);- dependencyDefinitions === null || dependencyDefinitions === void 0 ? void 0 : dependencyDefinitions.forEach(dependencyDefinition => {- definitionsWithDependencies.add(dependencyDefinition);- });- }- }- }- const allImportedDefinitionsMap = new Map();- for (const line of importLines) {- const { imports, from } = parseImportLine(line.replace('#', '').trim());- const importFileDefinitionMap = visitFile(from, filePath, visitedFiles, predefinedImports);- if (imports.includes('*')) {- for (const [importedDefinitionName, importedDefinitions] of importFileDefinitionMap) {- const [importedDefinitionTypeName] = importedDefinitionName.split('.');- if (!allImportedDefinitionsMap.has(importedDefinitionTypeName)) {- allImportedDefinitionsMap.set(importedDefinitionTypeName, new Set());- }- const allImportedDefinitions = allImportedDefinitionsMap.get(importedDefinitionTypeName);- for (const importedDefinition of importedDefinitions) {- allImportedDefinitions.add(importedDefinition);- }- }- }- else {- for (let importedDefinitionName of imports) {- if (importedDefinitionName.endsWith('.*')) {- // Adding whole type means the same thing with adding every single field- importedDefinitionName = importedDefinitionName.replace('.*', '');- }- const [importedDefinitionTypeName] = importedDefinitionName.split('.');- if (!allImportedDefinitionsMap.has(importedDefinitionTypeName)) {- allImportedDefinitionsMap.set(importedDefinitionTypeName, new Set());- }- const allImportedDefinitions = allImportedDefinitionsMap.get(importedDefinitionTypeName);- const importedDefinitions = importFileDefinitionMap.get(importedDefinitionName);- if (!importedDefinitions) {- throw new Error(`${importedDefinitionName} is not exported by ${from} imported by ${filePath}`);- }- for (const importedDefinition of importedDefinitions) {- allImportedDefinitions.add(importedDefinition);- }- }- }- }- if (!otherLines) {- visitedFiles.set(filePath, allImportedDefinitionsMap);- }- else {- const fileDefinitionMap = visitedFiles.get(filePath);- for (const [definitionName] of definitionsByName) {- const addDefinition = (definition) => {- definitionsWithDependencies.add(definition);- // Regenerate field exports if some fields are imported after visitor- if ('fields' in definition) {- for (const field of definition.fields) {- const fieldName = field.name.value;- const fieldDefinitionName = definition.name.value + '.' + fieldName;- const allImportedDefinitions = allImportedDefinitionsMap.get(definitionName);- allImportedDefinitions === null || allImportedDefinitions === void 0 ? void 0 : allImportedDefinitions.forEach(importedDefinition => {- if (!fileDefinitionMap.has(fieldDefinitionName)) {- fileDefinitionMap.set(fieldDefinitionName, new Set());- }- const definitionsWithDeps = fileDefinitionMap.get(fieldDefinitionName);- definitionsWithDeps.add(importedDefinition);- });- }- }- };- const definitionsWithDependencies = fileDefinitionMap.get(definitionName);- const allImportedDefinitions = allImportedDefinitionsMap.get(definitionName);- allImportedDefinitions === null || allImportedDefinitions === void 0 ? void 0 : allImportedDefinitions.forEach(importedDefinition => {- addDefinition(importedDefinition);- });- const dependenciesOfDefinition = dependenciesByDefinitionName.get(definitionName);- for (const dependencyName of dependenciesOfDefinition) {- // If that dependency cannot be found both in imports and this file, throw an error- if (!allImportedDefinitionsMap.has(dependencyName) && !definitionsByName.has(dependencyName)) {- throw new Error(`Couldn't find type ${dependencyName} in any of the schemas.`);- }- const dependencyDefinitionsFromImports = allImportedDefinitionsMap.get(dependencyName);- dependencyDefinitionsFromImports === null || dependencyDefinitionsFromImports === void 0 ? void 0 : dependencyDefinitionsFromImports.forEach(dependencyDefinition => {- addDefinition(dependencyDefinition);- });- }- }- }- }- return visitedFiles.get(filePath);-}-function parseImportLine(importLine) {- if (IMPORT_FROM_REGEX.test(importLine)) {- // Apply regex to import line- // Extract matches into named variables- const [, wildcard, importsString, , from] = importLine.match(IMPORT_FROM_REGEX);- if (from) {- // Extract imported types- const imports = wildcard === '*' ? ['*'] : importsString.split(',').map(d => d.trim());- // Return information about the import line- return { imports, from };- }- }- else if (IMPORT_DEFAULT_REGEX.test(importLine)) {- const [, , from] = importLine.match(IMPORT_DEFAULT_REGEX);- if (from) {- return { imports: ['*'], from };- }- }- throw new Error(`- Import statement is not valid:- > ${importLine}- If you want to have comments starting with '# import', please use ''' instead!- You can only have 'import' statements in the following pattern;- # import [Type].[Field] from [File]- `);-}-function resolveFilePath(filePath, importFrom) {- const dirName = path.dirname(filePath);- try {- const fullPath = path.join(dirName, importFrom);- return lib.realpathSync(fullPath);- }- catch (e) {- if (e.code === 'ENOENT') {- return resolveFrom_1(dirName, importFrom);- }- }-}-function visitOperationDefinitionNode(node, dependencySet) {- dependencySet.add(node.name.value);- node.selectionSet.selections.forEach(selectionNode => visitSelectionNode(selectionNode, dependencySet));-}-function visitSelectionNode(node, dependencySet) {- switch (node.kind) {- case Kind.FIELD:- visitFieldNode(node, dependencySet);- break;- case Kind.FRAGMENT_SPREAD:- visitFragmentSpreadNode(node, dependencySet);- break;- case Kind.INLINE_FRAGMENT:- visitInlineFragmentNode(node, dependencySet);- break;- }-}-function visitFieldNode(node, dependencySet) {- var _a;- (_a = node.selectionSet) === null || _a === void 0 ? void 0 : _a.selections.forEach(selectionNode => visitSelectionNode(selectionNode, dependencySet));-}-function visitFragmentSpreadNode(node, dependencySet) {- dependencySet.add(node.name.value);-}-function visitInlineFragmentNode(node, dependencySet) {- node.selectionSet.selections.forEach(selectionNode => visitSelectionNode(selectionNode, dependencySet));-}-function visitFragmentDefinitionNode(node, dependencySet) {- dependencySet.add(node.name.value);- node.selectionSet.selections.forEach(selectionNode => visitSelectionNode(selectionNode, dependencySet));-}-function visitObjectTypeDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a, _b, _c;- const typeName = node.name.value;- dependencySet.add(typeName);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(fieldDefinitionNode => visitFieldDefinitionNode(fieldDefinitionNode, dependencySet));- (_c = node.interfaces) === null || _c === void 0 ? void 0 : _c.forEach(namedTypeNode => {- visitNamedTypeNode(namedTypeNode, dependencySet);- const interfaceName = namedTypeNode.name.value;- // interface should be dependent to the type as well- if (!dependenciesByDefinitionName.has(interfaceName)) {- dependenciesByDefinitionName.set(interfaceName, new Set());- }- dependenciesByDefinitionName.get(interfaceName).add(typeName);- });-}-function visitDirectiveNode(node, dependencySet) {- const directiveName = node.name.value;- if (!builtinDirectives.includes(directiveName)) {- dependencySet.add(node.name.value);- }-}-function visitFieldDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a, _b;- (_a = node.arguments) === null || _a === void 0 ? void 0 : _a.forEach(inputValueDefinitionNode => visitInputValueDefinitionNode(inputValueDefinitionNode, dependencySet));- (_b = node.directives) === null || _b === void 0 ? void 0 : _b.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- visitTypeNode(node.type, dependencySet);-}-function visitTypeNode(node, dependencySet, dependenciesByDefinitionName) {- switch (node.kind) {- case Kind.LIST_TYPE:- visitListTypeNode(node, dependencySet);- break;- case Kind.NON_NULL_TYPE:- visitNonNullTypeNode(node, dependencySet);- break;- case Kind.NAMED_TYPE:- visitNamedTypeNode(node, dependencySet);- break;- }-}-function visitListTypeNode(node, dependencySet, dependenciesByDefinitionName) {- visitTypeNode(node.type, dependencySet);-}-function visitNonNullTypeNode(node, dependencySet, dependenciesByDefinitionName) {- visitTypeNode(node.type, dependencySet);-}-function visitNamedTypeNode(node, dependencySet) {- const namedTypeName = node.name.value;- if (!builtinTypes.includes(namedTypeName)) {- dependencySet.add(node.name.value);- }-}-function visitInputValueDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a;- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- visitTypeNode(node.type, dependencySet);-}-function visitInterfaceTypeDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a, _b, _c;- const typeName = node.name.value;- dependencySet.add(typeName);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(fieldDefinitionNode => visitFieldDefinitionNode(fieldDefinitionNode, dependencySet));- (_c = node.interfaces) === null || _c === void 0 ? void 0 : _c.forEach((namedTypeNode) => {- visitNamedTypeNode(namedTypeNode, dependencySet);- const interfaceName = namedTypeNode.name.value;- // interface should be dependent to the type as well- if (!dependenciesByDefinitionName.has(interfaceName)) {- dependenciesByDefinitionName.set(interfaceName, new Set());- }- dependenciesByDefinitionName.get(interfaceName).add(typeName);- });-}-function visitUnionTypeDefinitionNode(node, dependencySet) {- var _a;- dependencySet.add(node.name.value);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- node.types.forEach(namedTypeNode => visitNamedTypeNode(namedTypeNode, dependencySet));-}-function visitEnumTypeDefinitionNode(node, dependencySet) {- var _a;- dependencySet.add(node.name.value);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));-}-function visitInputObjectTypeDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a, _b;- dependencySet.add(node.name.value);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(inputValueDefinitionNode => visitInputValueDefinitionNode(inputValueDefinitionNode, dependencySet));-}-function visitDirectiveDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a;- dependencySet.add(node.name.value);- (_a = node.arguments) === null || _a === void 0 ? void 0 : _a.forEach(inputValueDefinitionNode => visitInputValueDefinitionNode(inputValueDefinitionNode, dependencySet));-}-function visitObjectTypeExtensionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a, _b, _c;- const typeName = node.name.value;- dependencySet.add(typeName);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(fieldDefinitionNode => visitFieldDefinitionNode(fieldDefinitionNode, dependencySet));- (_c = node.interfaces) === null || _c === void 0 ? void 0 : _c.forEach(namedTypeNode => {- visitNamedTypeNode(namedTypeNode, dependencySet);- const interfaceName = namedTypeNode.name.value;- // interface should be dependent to the type as well- if (!dependenciesByDefinitionName.has(interfaceName)) {- dependenciesByDefinitionName.set(interfaceName, new Set());- }- dependenciesByDefinitionName.get(interfaceName).add(typeName);- });-}-function visitInterfaceTypeExtensionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a, _b, _c;- const typeName = node.name.value;- dependencySet.add(typeName);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(fieldDefinitionNode => visitFieldDefinitionNode(fieldDefinitionNode, dependencySet));- (_c = node.interfaces) === null || _c === void 0 ? void 0 : _c.forEach((namedTypeNode) => {- visitNamedTypeNode(namedTypeNode, dependencySet);- const interfaceName = namedTypeNode.name.value;- // interface should be dependent to the type as well- if (!dependenciesByDefinitionName.has(interfaceName)) {- dependenciesByDefinitionName.set(interfaceName, new Set());- }- dependenciesByDefinitionName.get(interfaceName).add(typeName);- });-}-function visitUnionTypeExtensionNode(node, dependencySet) {- var _a;- dependencySet.add(node.name.value);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- node.types.forEach(namedTypeNode => visitNamedTypeNode(namedTypeNode, dependencySet));-}-function visitEnumTypeExtensionNode(node, dependencySet) {- var _a;- dependencySet.add(node.name.value);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));-}-function visitInputObjectTypeExtensionNode(node, dependencySet, dependenciesByDefinitionName) {- var _a, _b;- dependencySet.add(node.name.value);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(inputValueDefinitionNode => visitInputValueDefinitionNode(inputValueDefinitionNode, dependencySet));-}-function visitSchemaDefinitionNode(node, dependencySet) {- var _a;- dependencySet.add('schema');- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));- node.operationTypes.forEach(operationTypeDefinitionNode => visitOperationTypeDefinitionNode(operationTypeDefinitionNode, dependencySet));-}-function visitScalarDefinitionNode(node, dependencySet) {- var _a;- dependencySet.add(node.name.value);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));-}-function visitScalarExtensionNode(node, dependencySet) {- var _a;- dependencySet.add(node.name.value);- (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));-}-function visitOperationTypeDefinitionNode(node, dependencySet) {- visitNamedTypeNode(node.type, dependencySet);-}--function mergeArguments(args1, args2, config) {- const result = deduplicateArguments([].concat(args2, args1).filter(a => a));- if (config && config.sort) {- result.sort(compareNodes);- }- return result;-}-function deduplicateArguments(args) {- return args.reduce((acc, current) => {- const dup = acc.find(arg => arg.name.value === current.name.value);- if (!dup) {- return acc.concat([current]);- }- return acc;- }, []);-}--let commentsRegistry = {};-function resetComments() {- commentsRegistry = {};-}-function collectComment(node) {- const entityName = node.name.value;- pushComment(node, entityName);- switch (node.kind) {- case 'EnumTypeDefinition':- node.values.forEach(value => {- pushComment(value, entityName, value.name.value);- });- break;- case 'ObjectTypeDefinition':- case 'InputObjectTypeDefinition':- case 'InterfaceTypeDefinition':- if (node.fields) {- node.fields.forEach((field) => {- pushComment(field, entityName, field.name.value);- if (isFieldDefinitionNode(field) && field.arguments) {- field.arguments.forEach(arg => {- pushComment(arg, entityName, field.name.value, arg.name.value);- });- }- });- }- break;- }-}-function pushComment(node, entity, field, argument) {- const comment = getDescription(node, { commentDescriptions: true });- if (typeof comment !== 'string' || comment.length === 0) {- return;- }- const keys = [entity];- if (field) {- keys.push(field);- if (argument) {- keys.push(argument);- }- }- const path = keys.join('.');- if (!commentsRegistry[path]) {- commentsRegistry[path] = [];- }- commentsRegistry[path].push(comment);-}-function printComment(comment) {- return '\n# ' + comment.replace(/\n/g, '\n# ');-}-/**- * 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.- */-/**- * NOTE: ==> This file has been modified just to add comments to the printed AST- * This is a temp measure, we will move to using the original non modified printer.js ASAP.- */-// import { visit, VisitFn } from 'graphql/language/visitor';-/**- * Given maybeArray, print an empty string if it is null or empty, otherwise- * print all items together separated by separator if provided- */-function join$1(maybeArray, separator) {- return maybeArray ? maybeArray.filter(x => x).join(separator || '') : '';-}-function addDescription$1(cb) {- return (node, _key, _parent, path, ancestors) => {- const keys = [];- const parent = path.reduce((prev, key) => {- if (['fields', 'arguments', 'values'].includes(key)) {- keys.push(prev.name.value);- }- return prev[key];- }, ancestors[0]);- const key = [...keys, parent.name.value].join('.');- const items = [];- if (commentsRegistry[key]) {- items.push(...commentsRegistry[key]);- }- return join$1([...items.map(printComment), node.description, cb(node)], '\n');- };-}-function indent$1(maybeString) {- return maybeString && ` ${maybeString.replace(/\n/g, '\n ')}`;-}-/**- * Given array, print each item on its own line, wrapped in an- * indented "{ }" block.- */-function block$1(array) {- return array && array.length !== 0 ? `{\n${indent$1(join$1(array, '\n'))}\n}` : '';-}-/**- * If maybeString is not null or empty, then wrap with start and end, otherwise- * print an empty string.- */-function wrap$1(start, maybeString, end) {- return maybeString ? start + maybeString + (end || '') : '';-}-/**- * 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$1(value, isDescription) {- const escaped = value.replace(/"""/g, '\\"""');- return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1- ? `"""${escaped.replace(/"$/, '"\n')}"""`- : `"""\n${isDescription ? escaped : indent$1(escaped)}\n"""`;-}-/**- * Converts an AST into a string, using one set of reasonable- * formatting rules.- */-function printWithComments(ast) {- return visit(ast, {- leave: {- Name: node => node.value,- Variable: node => `$${node.name}`,- // Document- Document: node => `${node.definitions- .map(defNode => `${defNode}\n${defNode[0] === '#' ? '' : '\n'}`)- .join('')- .trim()}\n`,- OperationTypeDefinition: node => `${node.operation}: ${node.type}`,- VariableDefinition: ({ variable, type, defaultValue }) => `${variable}: ${type}${wrap$1(' = ', defaultValue)}`,- SelectionSet: ({ selections }) => block$1(selections),- Field: ({ alias, name, arguments: args, directives, selectionSet }) => join$1([wrap$1('', alias, ': ') + name + wrap$1('(', join$1(args, ', '), ')'), join$1(directives, ' '), selectionSet], ' '),- Argument: addDescription$1(({ name, value }) => `${name}: ${value}`),- // Value- IntValue: ({ value }) => value,- FloatValue: ({ value }) => value,- StringValue: ({ value, block: isBlockString }, key) => isBlockString ? printBlockString$1(value, key === 'description') : JSON.stringify(value),- BooleanValue: ({ value }) => (value ? 'true' : 'false'),- NullValue: () => 'null',- EnumValue: ({ value }) => value,- ListValue: ({ values }) => `[${join$1(values, ', ')}]`,- ObjectValue: ({ fields }) => `{${join$1(fields, ', ')}}`,- ObjectField: ({ name, value }) => `${name}: ${value}`,- // Directive- Directive: ({ name, arguments: args }) => `@${name}${wrap$1('(', join$1(args, ', '), ')')}`,- // Type- NamedType: ({ name }) => name,- ListType: ({ type }) => `[${type}]`,- NonNullType: ({ type }) => `${type}!`,- // Type System Definitions- SchemaDefinition: ({ directives, operationTypes }) => join$1(['schema', join$1(directives, ' '), block$1(operationTypes)], ' '),- ScalarTypeDefinition: addDescription$1(({ name, directives }) => join$1(['scalar', name, join$1(directives, ' ')], ' ')),- ObjectTypeDefinition: addDescription$1(({ name, interfaces, directives, fields }) => join$1(['type', name, wrap$1('implements ', join$1(interfaces, ' & ')), join$1(directives, ' '), block$1(fields)], ' ')),- FieldDefinition: addDescription$1(({ name, arguments: args, type, directives }) => `${name + wrap$1('(', join$1(args, ', '), ')')}: ${type}${wrap$1(' ', join$1(directives, ' '))}`),- InputValueDefinition: addDescription$1(({ name, type, defaultValue, directives }) => join$1([`${name}: ${type}`, wrap$1('= ', defaultValue), join$1(directives, ' ')], ' ')),- InterfaceTypeDefinition: addDescription$1(({ name, directives, fields }) => join$1(['interface', name, join$1(directives, ' '), block$1(fields)], ' ')),- UnionTypeDefinition: addDescription$1(({ name, directives, types }) => join$1(['union', name, join$1(directives, ' '), types && types.length !== 0 ? `= ${join$1(types, ' | ')}` : ''], ' ')),- EnumTypeDefinition: addDescription$1(({ name, directives, values }) => join$1(['enum', name, join$1(directives, ' '), block$1(values)], ' ')),- EnumValueDefinition: addDescription$1(({ name, directives }) => join$1([name, join$1(directives, ' ')], ' ')),- InputObjectTypeDefinition: addDescription$1(({ name, directives, fields }) => join$1(['input', name, join$1(directives, ' '), block$1(fields)], ' ')),- ScalarTypeExtension: ({ name, directives }) => join$1(['extend scalar', name, join$1(directives, ' ')], ' '),- ObjectTypeExtension: ({ name, interfaces, directives, fields }) => join$1(['extend type', name, wrap$1('implements ', join$1(interfaces, ' & ')), join$1(directives, ' '), block$1(fields)], ' '),- InterfaceTypeExtension: ({ name, directives, fields }) => join$1(['extend interface', name, join$1(directives, ' '), block$1(fields)], ' '),- UnionTypeExtension: ({ name, directives, types }) => join$1(['extend union', name, join$1(directives, ' '), types && types.length !== 0 ? `= ${join$1(types, ' | ')}` : ''], ' '),- EnumTypeExtension: ({ name, directives, values }) => join$1(['extend enum', name, join$1(directives, ' '), block$1(values)], ' '),- InputObjectTypeExtension: ({ name, directives, fields }) => join$1(['extend input', name, join$1(directives, ' '), block$1(fields)], ' '),- DirectiveDefinition: addDescription$1(({ name, arguments: args, locations }) => `directive @${name}${wrap$1('(', join$1(args, ', '), ')')} on ${join$1(locations, ' | ')}`),- },- });-}-function isFieldDefinitionNode(node) {- return node.kind === 'FieldDefinition';-}--function directiveAlreadyExists(directivesArr, otherDirective) {- return !!directivesArr.find(directive => directive.name.value === otherDirective.name.value);-}-function nameAlreadyExists(name, namesArr) {- return namesArr.some(({ value }) => value === name.value);-}-function mergeArguments$1(a1, a2) {- const result = [...a2];- for (const argument of a1) {- const existingIndex = result.findIndex(a => a.name.value === argument.name.value);- if (existingIndex > -1) {- const existingArg = result[existingIndex];- if (existingArg.value.kind === 'ListValue') {- const source = existingArg.value.values;- const target = argument.value.values;- // merge values of two lists- existingArg.value.values = deduplicateLists(source, target, (targetVal, source) => {- const value = targetVal.value;- return !value || !source.some((sourceVal) => sourceVal.value === value);- });- }- else {- existingArg.value = argument.value;- }- }- else {- result.push(argument);- }- }- return result;-}-function deduplicateDirectives(directives) {- return directives- .map((directive, i, all) => {- const firstAt = all.findIndex(d => d.name.value === directive.name.value);- if (firstAt !== i) {- const dup = all[firstAt];- directive.arguments = mergeArguments$1(directive.arguments, dup.arguments);- return null;- }- return directive;- })- .filter(d => d);-}-function mergeDirectives(d1 = [], d2 = [], config) {- const reverseOrder = config && config.reverseDirectives;- const asNext = reverseOrder ? d1 : d2;- const asFirst = reverseOrder ? d2 : d1;- const result = deduplicateDirectives([...asNext]);- for (const directive of asFirst) {- if (directiveAlreadyExists(result, directive)) {- const existingDirectiveIndex = result.findIndex(d => d.name.value === directive.name.value);- const existingDirective = result[existingDirectiveIndex];- result[existingDirectiveIndex].arguments = mergeArguments$1(directive.arguments || [], existingDirective.arguments || []);- }- else {- result.push(directive);- }- }- return result;-}-function validateInputs(node, existingNode) {- const printedNode = print(node);- const printedExistingNode = print(existingNode);- const leaveInputs = new RegExp('(directive @w*d*)|( on .*$)', 'g');- const sameArguments = printedNode.replace(leaveInputs, '') === printedExistingNode.replace(leaveInputs, '');- if (!sameArguments) {- throw new Error(`Unable to merge GraphQL directive "${node.name.value}". \nExisting directive: \n\t${printedExistingNode} \nReceived directive: \n\t${printedNode}`);- }-}-function mergeDirective(node, existingNode) {- if (existingNode) {- validateInputs(node, existingNode);- return {- ...node,- locations: [- ...existingNode.locations,- ...node.locations.filter(name => !nameAlreadyExists(name, existingNode.locations)),- ],- };- }- return node;-}-function deduplicateLists(source, target, filterFn) {- return source.concat(target.filter(val => filterFn(val, source)));-}--function mergeEnumValues(first, second, config) {- const enumValueMap = new Map();- for (const firstValue of first) {- enumValueMap.set(firstValue.name.value, firstValue);- }- for (const secondValue of second) {- const enumValue = secondValue.name.value;- if (enumValueMap.has(enumValue)) {- const firstValue = enumValueMap.get(enumValue);- firstValue.description = secondValue.description || firstValue.description;- firstValue.directives = mergeDirectives(secondValue.directives, firstValue.directives);- }- else {- enumValueMap.set(enumValue, secondValue);- }- }- const result = [...enumValueMap.values()];- if (config && config.sort) {- result.sort(compareNodes);- }- return result;-}--function mergeEnum(e1, e2, config) {- if (e2) {- return {- name: e1.name,- description: e1['description'] || e2['description'],- kind: (config && config.convertExtensions) || e1.kind === 'EnumTypeDefinition' || e2.kind === 'EnumTypeDefinition'- ? 'EnumTypeDefinition'- : 'EnumTypeExtension',- loc: e1.loc,- directives: mergeDirectives(e1.directives, e2.directives, config),- values: mergeEnumValues(e1.values, e2.values, config),- };- }- return config && config.convertExtensions- ? {- ...e1,- kind: 'EnumTypeDefinition',- }- : e1;-}--function isStringTypes(types) {- return typeof types === 'string';-}-function isSourceTypes(types) {- return types instanceof Source;-}-function isGraphQLType(definition) {- return definition.kind === 'ObjectTypeDefinition';-}-function isGraphQLTypeExtension(definition) {- return definition.kind === 'ObjectTypeExtension';-}-function isGraphQLEnum(definition) {- return definition.kind === 'EnumTypeDefinition';-}-function isGraphQLEnumExtension(definition) {- return definition.kind === 'EnumTypeExtension';-}-function isGraphQLUnion(definition) {- return definition.kind === 'UnionTypeDefinition';-}-function isGraphQLUnionExtension(definition) {- return definition.kind === 'UnionTypeExtension';-}-function isGraphQLScalar(definition) {- return definition.kind === 'ScalarTypeDefinition';-}-function isGraphQLScalarExtension(definition) {- return definition.kind === 'ScalarTypeExtension';-}-function isGraphQLInputType(definition) {- return definition.kind === 'InputObjectTypeDefinition';-}-function isGraphQLInputTypeExtension(definition) {- return definition.kind === 'InputObjectTypeExtension';-}-function isGraphQLInterface(definition) {- return definition.kind === 'InterfaceTypeDefinition';-}-function isGraphQLInterfaceExtension(definition) {- return definition.kind === 'InterfaceTypeExtension';-}-function isGraphQLDirective(definition) {- return definition.kind === 'DirectiveDefinition';-}-function extractType(type) {- let visitedType = type;- while (visitedType.kind === 'ListType' || visitedType.kind === 'NonNullType') {- visitedType = visitedType.type;- }- return visitedType;-}-function isSchemaDefinition(node) {- return node.kind === 'SchemaDefinition';-}-function isWrappingTypeNode(type) {- return type.kind !== Kind.NAMED_TYPE;-}-function isListTypeNode(type) {- return type.kind === Kind.LIST_TYPE;-}-function isNonNullTypeNode(type) {- return type.kind === Kind.NON_NULL_TYPE;-}-function printTypeNode(type) {- if (isListTypeNode(type)) {- return `[${printTypeNode(type.type)}]`;- }- if (isNonNullTypeNode(type)) {- return `${printTypeNode(type.type)}!`;- }- return type.name.value;-}--function fieldAlreadyExists(fieldsArr, otherField) {- const result = fieldsArr.find(field => field.name.value === otherField.name.value);- if (result) {- const t1 = extractType(result.type);- const t2 = extractType(otherField.type);- if (t1.name.value !== t2.name.value) {- throw new Error(`Field "${otherField.name.value}" already defined with a different type. Declared as "${t1.name.value}", but you tried to override with "${t2.name.value}"`);- }- }- return !!result;-}-function mergeFields(type, f1, f2, config) {- const result = [...f2];- for (const field of f1) {- if (fieldAlreadyExists(result, field)) {- const existing = result.find((f) => f.name.value === field.name.value);- if (config && config.throwOnConflict) {- preventConflicts(type, existing, field, false);- }- else {- preventConflicts(type, existing, field, true);- }- if (isNonNullTypeNode(field.type) && !isNonNullTypeNode(existing.type)) {- existing.type = field.type;- }- existing.arguments = mergeArguments(field['arguments'] || [], existing.arguments || [], config);- existing.directives = mergeDirectives(field.directives, existing.directives, config);- existing.description = field.description || existing.description;- }- else {- result.push(field);- }- }- if (config && config.sort) {- result.sort(compareNodes);- }- if (config && config.exclusions) {- return result.filter(field => !config.exclusions.includes(`${type.name.value}.${field.name.value}`));- }- return result;-}-function preventConflicts(type, a, b, ignoreNullability = false) {- const aType = printTypeNode(a.type);- const bType = printTypeNode(b.type);- if (isNotEqual(aType, bType)) {- if (safeChangeForFieldType(a.type, b.type, ignoreNullability) === false) {- throw new Error(`Field '${type.name.value}.${a.name.value}' changed type from '${aType}' to '${bType}'`);- }- }-}-function safeChangeForFieldType(oldType, newType, ignoreNullability = false) {- // both are named- if (!isWrappingTypeNode(oldType) && !isWrappingTypeNode(newType)) {- return oldType.toString() === newType.toString();- }- // new is non-null- if (isNonNullTypeNode(newType)) {- const ofType = isNonNullTypeNode(oldType) ? oldType.type : oldType;- return safeChangeForFieldType(ofType, newType.type);- }- // old is non-null- if (isNonNullTypeNode(oldType)) {- return safeChangeForFieldType(newType, oldType, ignoreNullability);- }- // old is list- if (isListTypeNode(oldType)) {- return ((isListTypeNode(newType) && safeChangeForFieldType(oldType.type, newType.type)) ||- (isNonNullTypeNode(newType) && safeChangeForFieldType(oldType, newType['type'])));- }- return false;-}--function mergeInputType(node, existingNode, config) {- if (existingNode) {- try {- return {- name: node.name,- description: node['description'] || existingNode['description'],- kind: (config && config.convertExtensions) ||- node.kind === 'InputObjectTypeDefinition' ||- existingNode.kind === 'InputObjectTypeDefinition'- ? 'InputObjectTypeDefinition'- : 'InputObjectTypeExtension',- loc: node.loc,- fields: mergeFields(node, node.fields, existingNode.fields, config),- directives: mergeDirectives(node.directives, existingNode.directives, config),- };- }- catch (e) {- throw new Error(`Unable to merge GraphQL input type "${node.name.value}": ${e.message}`);- }- }- return config && config.convertExtensions- ? {- ...node,- kind: 'InputObjectTypeDefinition',- }- : node;-}--function mergeInterface(node, existingNode, config) {- if (existingNode) {- try {- return {- name: node.name,- description: node['description'] || existingNode['description'],- kind: (config && config.convertExtensions) ||- node.kind === 'InterfaceTypeDefinition' ||- existingNode.kind === 'InterfaceTypeDefinition'- ? 'InterfaceTypeDefinition'- : 'InterfaceTypeExtension',- loc: node.loc,- fields: mergeFields(node, node.fields, existingNode.fields, config),- directives: mergeDirectives(node.directives, existingNode.directives, config),- };- }- catch (e) {- throw new Error(`Unable to merge GraphQL interface "${node.name.value}": ${e.message}`);- }- }- return config && config.convertExtensions- ? {- ...node,- kind: 'InterfaceTypeDefinition',- }- : node;-}--function alreadyExists(arr, other) {- return !!arr.find(i => i.name.value === other.name.value);-}-function mergeNamedTypeArray(first, second, config) {- const result = [...second, ...first.filter(d => !alreadyExists(second, d))];- if (config && config.sort) {- result.sort(compareNodes);- }- return result;-}--function mergeType(node, existingNode, config) {- if (existingNode) {- try {- return {- name: node.name,- description: node['description'] || existingNode['description'],- kind: (config && config.convertExtensions) ||- node.kind === 'ObjectTypeDefinition' ||- existingNode.kind === 'ObjectTypeDefinition'- ? 'ObjectTypeDefinition'- : 'ObjectTypeExtension',- loc: node.loc,- fields: mergeFields(node, node.fields, existingNode.fields, config),- directives: mergeDirectives(node.directives, existingNode.directives, config),- interfaces: mergeNamedTypeArray(node.interfaces, existingNode.interfaces, config),- };- }- catch (e) {- throw new Error(`Unable to merge GraphQL type "${node.name.value}": ${e.message}`);- }- }- return config && config.convertExtensions- ? {- ...node,- kind: 'ObjectTypeDefinition',- }- : node;-}--function mergeUnion(first, second, config) {- if (second) {- return {- name: first.name,- description: first['description'] || second['description'],- directives: mergeDirectives(first.directives, second.directives, config),- kind: (config && config.convertExtensions) ||- first.kind === 'UnionTypeDefinition' ||- second.kind === 'UnionTypeDefinition'- ? 'UnionTypeDefinition'- : 'UnionTypeExtension',- loc: first.loc,- types: mergeNamedTypeArray(first.types, second.types, config),- };- }- return config && config.convertExtensions- ? {- ...first,- kind: 'UnionTypeDefinition',- }- : first;-}--function mergeGraphQLNodes(nodes, config) {- return nodes.reduce((prev, nodeDefinition) => {- const node = nodeDefinition;- if (node && node.name && node.name.value) {- const name = node.name.value;- if (config && config.commentDescriptions) {- collectComment(node);- }- if (config &&- config.exclusions &&- (config.exclusions.includes(name + '.*') || config.exclusions.includes(name))) {- delete prev[name];- }- else if (isGraphQLType(nodeDefinition) || isGraphQLTypeExtension(nodeDefinition)) {- prev[name] = mergeType(nodeDefinition, prev[name], config);- }- else if (isGraphQLEnum(nodeDefinition) || isGraphQLEnumExtension(nodeDefinition)) {- prev[name] = mergeEnum(nodeDefinition, prev[name], config);- }- else if (isGraphQLUnion(nodeDefinition) || isGraphQLUnionExtension(nodeDefinition)) {- prev[name] = mergeUnion(nodeDefinition, prev[name], config);- }- else if (isGraphQLScalar(nodeDefinition) || isGraphQLScalarExtension(nodeDefinition)) {- prev[name] = nodeDefinition;- }- else if (isGraphQLInputType(nodeDefinition) || isGraphQLInputTypeExtension(nodeDefinition)) {- prev[name] = mergeInputType(nodeDefinition, prev[name], config);- }- else if (isGraphQLInterface(nodeDefinition) || isGraphQLInterfaceExtension(nodeDefinition)) {- prev[name] = mergeInterface(nodeDefinition, prev[name], config);- }- else if (isGraphQLDirective(nodeDefinition)) {- prev[name] = mergeDirective(nodeDefinition, prev[name]);- }- }- return prev;- }, {});-}--function mergeTypeDefs(types, config) {- resetComments();- const doc = {- kind: Kind.DOCUMENT,- definitions: mergeGraphQLTypes(types, {- useSchemaDefinition: true,- forceSchemaDefinition: false,- throwOnConflict: false,- commentDescriptions: false,- ...config,- }),- };- let result;- if (config && config.commentDescriptions) {- result = printWithComments(doc);- }- else {- result = doc;- }- resetComments();- return result;-}-function mergeGraphQLTypes(types, config) {- resetComments();- const allNodes = types- .map(type => {- if (Array.isArray(type)) {- type = mergeTypeDefs(type);- }- if (isSchema(type)) {- return parse(printSchemaWithDirectives(type));- }- else if (isStringTypes(type) || isSourceTypes(type)) {- return parse(type);- }- return type;- })- .map(ast => ast.definitions)- .reduce((defs, newDef = []) => [...defs, ...newDef], []);- // XXX: right now we don't handle multiple schema definitions- let schemaDef = allNodes.filter(isSchemaDefinition).reduce((def, node) => {- node.operationTypes- .filter(op => op.type.name.value)- .forEach(op => {- def[op.operation] = op.type.name.value;- });- return def;- }, {- query: null,- mutation: null,- subscription: null,- });- const mergedNodes = mergeGraphQLNodes(allNodes, config);- const allTypes = Object.keys(mergedNodes);- if (config && config.sort) {- allTypes.sort(typeof config.sort === 'function' ? config.sort : undefined);- }- if (config && config.useSchemaDefinition) {- const queryType = schemaDef.query ? schemaDef.query : allTypes.find(t => t === 'Query');- const mutationType = schemaDef.mutation ? schemaDef.mutation : allTypes.find(t => t === 'Mutation');- const subscriptionType = schemaDef.subscription ? schemaDef.subscription : allTypes.find(t => t === 'Subscription');- schemaDef = {- query: queryType,- mutation: mutationType,- subscription: subscriptionType,- };- }- const schemaDefinition = createSchemaDefinition(schemaDef, {- force: config.forceSchemaDefinition,- });- if (!schemaDefinition) {- return Object.values(mergedNodes);- }- return [...Object.values(mergedNodes), parse(schemaDefinition).definitions[0]];-}--const FILE_EXTENSIONS = ['.gql', '.gqls', '.graphql', '.graphqls'];-function isGraphQLImportFile(rawSDL) {- const trimmedRawSDL = rawSDL.trim();- return trimmedRawSDL.startsWith('# import') || trimmedRawSDL.startsWith('#import');-}-/**- * This loader loads documents and type definitions from `.graphql` files.- *- * You can load a single source:- *- * ```js- * const schema = await loadSchema('schema.graphql', {- * loaders: [- * new GraphQLFileLoader()- * ]- * });- * ```- *- * Or provide a glob pattern to load multiple sources:- *- * ```js- * const schema = await loadSchema('graphql/*.graphql', {- * loaders: [- * new GraphQLFileLoader()- * ]- * });- * ```- */-class GraphQLFileLoader {- loaderId() {- return 'graphql-file';- }- async canLoad(pointer, options) {- if (isValidPath(pointer)) {- if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);- return lib.pathExists(normalizedFilePath);- }- }- return false;- }- canLoadSync(pointer, options) {- if (isValidPath(pointer)) {- if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);- return lib.pathExistsSync(normalizedFilePath);- }- }- return false;- }- async load(pointer, options) {- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);- const rawSDL = await lib.readFile(normalizedFilePath, { encoding: 'utf8' });- return this.handleFileContent(rawSDL, pointer, options);- }- loadSync(pointer, options) {- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);- const rawSDL = lib.readFileSync(normalizedFilePath, { encoding: 'utf8' });- return this.handleFileContent(rawSDL, pointer, options);- }- handleFileContent(rawSDL, pointer, options) {- if (!options.skipGraphQLImport && isGraphQLImportFile(rawSDL)) {- const document = processImport(pointer, options.cwd);- const typeSystemDefinitions = document.definitions- .filter(d => !isExecutableDefinitionNode(d))- .map(definition => ({- kind: Kind.DOCUMENT,- definitions: [definition],- }));- const mergedTypeDefs = mergeTypeDefs(typeSystemDefinitions, { useSchemaDefinition: false });- const executableDefinitions = document.definitions.filter(isExecutableDefinitionNode);- return {- location: pointer,- document: {- ...mergedTypeDefs,- definitions: [...mergedTypeDefs.definitions, ...executableDefinitions],- },- };- }- return parseGraphQLSDL(pointer, rawSDL, options);- }-}--const FILE_EXTENSIONS$1 = ['.json'];-/**- * This loader loads documents and type definitions from JSON files.- *- * The JSON file can be the result of an introspection query made against a schema:- *- * ```js- * const schema = await loadSchema('schema-introspection.json', {- * loaders: [- * new JsonFileLoader()- * ]- * });- * ```- *- * Or it can be a `DocumentNode` object representing a GraphQL document or type definitions:- *- * ```js- * const documents = await loadDocuments('queries/*.json', {- * loaders: [- * new GraphQLFileLoader()- * ]- * });- * ```- */-class JsonFileLoader {- loaderId() {- return 'json-file';- }- async canLoad(pointer, options) {- if (isValidPath(pointer)) {- if (FILE_EXTENSIONS$1.find(extension => pointer.endsWith(extension))) {- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);- return lib.pathExists(normalizedFilePath);- }- }- return false;- }- canLoadSync(pointer, options) {- if (isValidPath(pointer)) {- if (FILE_EXTENSIONS$1.find(extension => pointer.endsWith(extension))) {- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);- return lib.pathExistsSync(normalizedFilePath);- }- }- return false;- }- async load(pointer, options) {- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);- try {- const jsonContent = await lib.readFile(normalizedFilePath, { encoding: 'utf8' });- return parseGraphQLJSON(pointer, jsonContent, options);- }- catch (e) {- throw new Error(`Unable to read JSON file: ${normalizedFilePath}: ${e.message || /* istanbul ignore next */ e}`);- }- }- loadSync(pointer, options) {- const normalizedFilepath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);- try {- const jsonContent = lib.readFileSync(normalizedFilepath, 'utf8');- return parseGraphQLJSON(pointer, jsonContent, options);- }- catch (e) {- throw new Error(`Unable to read JSON file: ${normalizedFilepath}: ${e.message || /* istanbul ignore next */ e}`);- }- }-}--/*!- * is-extglob <https://github.com/jonschlinkert/is-extglob>- *- * Copyright (c) 2014-2016, Jon Schlinkert.- * Licensed under the MIT License.- */--var isExtglob = function isExtglob(str) {- if (typeof str !== 'string' || str === '') {- return false;- }-- var match;- while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {- if (match[2]) return true;- str = str.slice(match.index + match[0].length);- }-- return false;-};--/*!- * is-glob <https://github.com/jonschlinkert/is-glob>- *- * Copyright (c) 2014-2017, Jon Schlinkert.- * Released under the MIT License.- */---var chars = { '{': '}', '(': ')', '[': ']'};-var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;-var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;--var isGlob = function isGlob(str, options) {- if (typeof str !== 'string' || str === '') {- return false;- }-- if (isExtglob(str)) {- return true;- }-- var regex = strictRegex;- var match;-- // optionally relax regex- if (options && options.strict === false) {- regex = relaxedRegex;- }-- while ((match = regex.exec(str))) {- if (match[2]) return true;- var idx = match.index + match[0].length;-- // if an open bracket/brace/paren is escaped,- // set the index to the next closing character- var open = match[1];- var close = open ? chars[open] : null;- if (open && close) {- var n = str.indexOf(close, idx);- if (n !== -1) {- idx = n + 1;- }- }-- str = str.slice(idx);- }- return false;-};--const pTry = (fn, ...arguments_) => new Promise(resolve => {- resolve(fn(...arguments_));-});--var pTry_1 = pTry;-// TODO: remove this in the next major version-var _default = pTry;-pTry_1.default = _default;--const pLimit = concurrency => {- if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {- throw new TypeError('Expected `concurrency` to be a number from 1 and up');- }-- const queue = [];- let activeCount = 0;-- const next = () => {- activeCount--;-- if (queue.length > 0) {- queue.shift()();- }- };-- const run = async (fn, resolve, ...args) => {- activeCount++;-- // TODO: Get rid of `pTry`. It's not needed anymore.- const result = pTry_1(fn, ...args);-- resolve(result);-- try {- await result;- } catch {}-- next();- };-- const enqueue = (fn, resolve, ...args) => {- queue.push(run.bind(null, fn, resolve, ...args));-- (async () => {- // This function needs to wait until the next microtask before comparing- // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously- // when the run function is dequeued and called. The comparison in the if-statement- // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.- await Promise.resolve();-- if (activeCount < concurrency && queue.length > 0) {- queue.shift()();- }- })();- };-- const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));- Object.defineProperties(generator, {- activeCount: {- get: () => activeCount- },- pendingCount: {- get: () => queue.length- },- clearQueue: {- value: () => {- queue.length = 0;- }- }- });-- return generator;-};--var pLimit_1 = pLimit;--var importFrom = (fromDirectory, moduleId) => commonjsRequire(resolveFrom_1(fromDirectory, moduleId));--var silent$1 = (fromDirectory, moduleId) => {- try {- return commonjsRequire(resolveFrom_1(fromDirectory, moduleId));- } catch (_) {}-};-importFrom.silent = silent$1;--var isWin = process.platform === 'win32';--var removeTrailingSeparator = function (str) {- var i = str.length - 1;- if (i < 2) {- return str;- }- while (isSeparator(str, i)) {- i--;- }- return str.substr(0, i + 1);-};--function isSeparator(str, i) {- var char = str[i];- return i > 0 && (char === '/' || (isWin && char === '\\'));-}--/*!- * normalize-path <https://github.com/jonschlinkert/normalize-path>- *- * Copyright (c) 2014-2017, Jon Schlinkert.- * Released under the MIT License.- */----var normalizePath = function normalizePath(str, stripTrailing) {- if (typeof str !== 'string') {- throw new TypeError('expected a string');- }- str = str.replace(/[\\\/]+/g, '/');- if (stripTrailing !== false) {- str = removeTrailingSeparator(str);- }- return str;-};--var unixify = function unixify(filepath, stripTrailing) {- filepath = normalizePath(filepath, stripTrailing);- return filepath.replace(/^([a-zA-Z]+:|\.\/)/, '');-};--var arrayUnion = (...arguments_) => {- return [...new Set([].concat(...arguments_))];-};--/*- * merge2- * https://github.com/teambition/merge2- *- * Copyright (c) 2014-2016 Teambition- * Licensed under the MIT license.- */--const PassThrough = Stream$2.PassThrough;-const slice = Array.prototype.slice;--var merge2_1 = merge2;--function merge2 () {- const streamsQueue = [];- let merging = false;- const args = slice.call(arguments);- let options = args[args.length - 1];-- if (options && !Array.isArray(options) && options.pipe == null) args.pop();- else options = {};-- const doEnd = options.end !== false;- if (options.objectMode == null) options.objectMode = true;- if (options.highWaterMark == null) options.highWaterMark = 64 * 1024;- const mergedStream = PassThrough(options);-- function addStream () {- for (let i = 0, len = arguments.length; i < len; i++) {- streamsQueue.push(pauseStreams(arguments[i], options));- }- mergeStream();- return this- }-- function mergeStream () {- if (merging) return- merging = true;-- let streams = streamsQueue.shift();- if (!streams) {- process.nextTick(endStream);- return- }- if (!Array.isArray(streams)) streams = [streams];-- let pipesCount = streams.length + 1;-- function next () {- if (--pipesCount > 0) return- merging = false;- mergeStream();- }-- function pipe (stream) {- function onend () {- stream.removeListener('merge2UnpipeEnd', onend);- stream.removeListener('end', onend);- next();- }- // skip ended stream- if (stream._readableState.endEmitted) return next()-- stream.on('merge2UnpipeEnd', onend);- stream.on('end', onend);- stream.pipe(mergedStream, { end: false });- // compatible for old stream- stream.resume();- }-- for (let i = 0; i < streams.length; i++) pipe(streams[i]);-- next();- }-- function endStream () {- merging = false;- // emit 'queueDrain' when all streams merged.- mergedStream.emit('queueDrain');- return doEnd && mergedStream.end()- }-- mergedStream.setMaxListeners(0);- mergedStream.add = addStream;- mergedStream.on('unpipe', function (stream) {- stream.emit('merge2UnpipeEnd');- });-- if (args.length) addStream.apply(null, args);- return mergedStream-}--// check and pause streams for pipe.-function pauseStreams (streams, options) {- if (!Array.isArray(streams)) {- // Backwards-compat with old-style streams- if (!streams._readableState && streams.pipe) streams = streams.pipe(PassThrough(options));- if (!streams._readableState || !streams.pause || !streams.pipe) {- throw new Error('Only readable stream can be merged.')- }- streams.pause();- } else {- for (let i = 0, len = streams.length; i < len; i++) streams[i] = pauseStreams(streams[i], options);- }- return streams-}--var array = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); -function flatten(items) { - return items.reduce((collection, item) => [].concat(collection, item), []); -} -exports.flatten = flatten;-});--var errno = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); -function isEnoentCodeError(error) { - return error.code === 'ENOENT'; -} -exports.isEnoentCodeError = isEnoentCodeError;-});--var fs = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); -class DirentFromStats { - constructor(name, stats) { - this.name = name; - this.isBlockDevice = stats.isBlockDevice.bind(stats); - this.isCharacterDevice = stats.isCharacterDevice.bind(stats); - this.isDirectory = stats.isDirectory.bind(stats); - this.isFIFO = stats.isFIFO.bind(stats); - this.isFile = stats.isFile.bind(stats); - this.isSocket = stats.isSocket.bind(stats); - this.isSymbolicLink = stats.isSymbolicLink.bind(stats); - } -} -function createDirentFromStats(name, stats) { - return new DirentFromStats(name, stats); -} -exports.createDirentFromStats = createDirentFromStats;-});--var path_1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([*?|(){}[\]]|^!|[@+!](?=\())/g; -/** - * Designed to work only with simple paths: `dir\\file`. - */ -function unixify(filepath) { - return filepath.replace(/\\/g, '/'); -} -exports.unixify = unixify; -function makeAbsolute(cwd, filepath) { - return path__default.resolve(cwd, filepath); -} -exports.makeAbsolute = makeAbsolute; -function escape(pattern) { - return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); -} -exports.escape = escape;-});--var pathPosixDirname = path__default.posix.dirname;-var isWin32 = require$$1.platform() === 'win32';--var slash = '/';-var backslash = /\\/g;-var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;-var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;-var escaped = /\\([\*\?\|\[\]\(\)\{\}])/g;--/**- * @param {string} str- * @param {Object} opts- * @param {boolean} [opts.flipBackslashes=true]- */-var globParent = function globParent(str, opts) {- var options = Object.assign({ flipBackslashes: true }, opts);-- // flip windows path separators- if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {- str = str.replace(backslash, slash);- }-- // special case for strings ending in enclosure containing path separator- if (enclosure.test(str)) {- str += slash;- }-- // preserves full path in case of trailing path separator- str += 'a';-- // remove path parts that are globby- do {- str = pathPosixDirname(str);- } while (isGlob(str) || globby.test(str));-- // remove escape chars and return result- return str.replace(escaped, '$1');-};--var utils$1 = createCommonjsModule(function (module, exports) {--exports.isInteger = num => {- if (typeof num === 'number') {- return Number.isInteger(num);- }- if (typeof num === 'string' && num.trim() !== '') {- return Number.isInteger(Number(num));- }- return false;-};--/**- * Find a node of the given type- */--exports.find = (node, type) => node.nodes.find(node => node.type === type);--/**- * Find a node of the given type- */--exports.exceedsLimit = (min, max, step = 1, limit) => {- if (limit === false) return false;- if (!exports.isInteger(min) || !exports.isInteger(max)) return false;- return ((Number(max) - Number(min)) / Number(step)) >= limit;-};--/**- * Escape the given node with '\\' before node.value- */--exports.escapeNode = (block, n = 0, type) => {- let node = block.nodes[n];- if (!node) return;-- if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {- if (node.escaped !== true) {- node.value = '\\' + node.value;- node.escaped = true;- }- }-};--/**- * Returns true if the given brace node should be enclosed in literal braces- */--exports.encloseBrace = node => {- if (node.type !== 'brace') return false;- if ((node.commas >> 0 + node.ranges >> 0) === 0) {- node.invalid = true;- return true;- }- return false;-};--/**- * Returns true if a brace node is invalid.- */--exports.isInvalidBrace = block => {- if (block.type !== 'brace') return false;- if (block.invalid === true || block.dollar) return true;- if ((block.commas >> 0 + block.ranges >> 0) === 0) {- block.invalid = true;- return true;- }- if (block.open !== true || block.close !== true) {- block.invalid = true;- return true;- }- return false;-};--/**- * Returns true if a node is an open or close node- */--exports.isOpenOrClose = node => {- if (node.type === 'open' || node.type === 'close') {- return true;- }- return node.open === true || node.close === true;-};--/**- * Reduce an array of text nodes.- */--exports.reduce = nodes => nodes.reduce((acc, node) => {- if (node.type === 'text') acc.push(node.value);- if (node.type === 'range') node.type = 'text';- return acc;-}, []);--/**- * Flatten an array- */--exports.flatten = (...args) => {- const result = [];- const flat = arr => {- for (let i = 0; i < arr.length; i++) {- let ele = arr[i];- Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);- }- return result;- };- flat(args);- return result;-};-});--var stringify$4 = (ast, options = {}) => {- let stringify = (node, parent = {}) => {- let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent);- let invalidNode = node.invalid === true && options.escapeInvalid === true;- let output = '';-- if (node.value) {- if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) {- return '\\' + node.value;- }- return node.value;- }-- if (node.value) {- return node.value;- }-- if (node.nodes) {- for (let child of node.nodes) {- output += stringify(child);- }- }- return output;- };-- return stringify(ast);-};--/*!- * is-number <https://github.com/jonschlinkert/is-number>- *- * Copyright (c) 2014-present, Jon Schlinkert.- * Released under the MIT License.- */--var isNumber = function(num) {- if (typeof num === 'number') {- return num - num === 0;- }- if (typeof num === 'string' && num.trim() !== '') {- return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);- }- return false;-};--const toRegexRange = (min, max, options) => {- if (isNumber(min) === false) {- throw new TypeError('toRegexRange: expected the first argument to be a number');- }-- if (max === void 0 || min === max) {- return String(min);- }-- if (isNumber(max) === false) {- throw new TypeError('toRegexRange: expected the second argument to be a number.');- }-- let opts = { relaxZeros: true, ...options };- if (typeof opts.strictZeros === 'boolean') {- opts.relaxZeros = opts.strictZeros === false;- }-- let relax = String(opts.relaxZeros);- let shorthand = String(opts.shorthand);- let capture = String(opts.capture);- let wrap = String(opts.wrap);- let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;-- if (toRegexRange.cache.hasOwnProperty(cacheKey)) {- return toRegexRange.cache[cacheKey].result;- }-- let a = Math.min(min, max);- let b = Math.max(min, max);-- if (Math.abs(a - b) === 1) {- let result = min + '|' + max;- if (opts.capture) {- return `(${result})`;- }- if (opts.wrap === false) {- return result;- }- return `(?:${result})`;- }-- let isPadded = hasPadding(min) || hasPadding(max);- let state = { min, max, a, b };- let positives = [];- let negatives = [];-- if (isPadded) {- state.isPadded = isPadded;- state.maxLen = String(state.max).length;- }-- if (a < 0) {- let newMin = b < 0 ? Math.abs(b) : 1;- negatives = splitToPatterns(newMin, Math.abs(a), state, opts);- a = state.a = 0;- }-- if (b >= 0) {- positives = splitToPatterns(a, b, state, opts);- }-- state.negatives = negatives;- state.positives = positives;- state.result = collatePatterns(negatives, positives);-- if (opts.capture === true) {- state.result = `(${state.result})`;- } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {- state.result = `(?:${state.result})`;- }-- toRegexRange.cache[cacheKey] = state;- return state.result;-};--function collatePatterns(neg, pos, options) {- let onlyNegative = filterPatterns(neg, pos, '-', false) || [];- let onlyPositive = filterPatterns(pos, neg, '', false) || [];- let intersected = filterPatterns(neg, pos, '-?', true) || [];- let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);- return subpatterns.join('|');-}--function splitToRanges(min, max) {- let nines = 1;- let zeros = 1;-- let stop = countNines(min, nines);- let stops = new Set([max]);-- while (min <= stop && stop <= max) {- stops.add(stop);- nines += 1;- stop = countNines(min, nines);- }-- stop = countZeros(max + 1, zeros) - 1;-- while (min < stop && stop <= max) {- stops.add(stop);- zeros += 1;- stop = countZeros(max + 1, zeros) - 1;- }-- stops = [...stops];- stops.sort(compare);- return stops;-}--/**- * Convert a range to a regex pattern- * @param {Number} `start`- * @param {Number} `stop`- * @return {String}- */--function rangeToPattern(start, stop, options) {- if (start === stop) {- return { pattern: start, count: [], digits: 0 };- }-- let zipped = zip(start, stop);- let digits = zipped.length;- let pattern = '';- let count = 0;-- for (let i = 0; i < digits; i++) {- let [startDigit, stopDigit] = zipped[i];-- if (startDigit === stopDigit) {- pattern += startDigit;-- } else if (startDigit !== '0' || stopDigit !== '9') {- pattern += toCharacterClass(startDigit, stopDigit);-- } else {- count++;- }- }-- if (count) {- pattern += options.shorthand === true ? '\\d' : '[0-9]';- }-- return { pattern, count: [count], digits };-}--function splitToPatterns(min, max, tok, options) {- let ranges = splitToRanges(min, max);- let tokens = [];- let start = min;- let prev;-- for (let i = 0; i < ranges.length; i++) {- let max = ranges[i];- let obj = rangeToPattern(String(start), String(max), options);- let zeros = '';-- if (!tok.isPadded && prev && prev.pattern === obj.pattern) {- if (prev.count.length > 1) {- prev.count.pop();- }-- prev.count.push(obj.count[0]);- prev.string = prev.pattern + toQuantifier(prev.count);- start = max + 1;- continue;- }-- if (tok.isPadded) {- zeros = padZeros(max, tok, options);- }-- obj.string = zeros + obj.pattern + toQuantifier(obj.count);- tokens.push(obj);- start = max + 1;- prev = obj;- }-- return tokens;-}--function filterPatterns(arr, comparison, prefix, intersection, options) {- let result = [];-- for (let ele of arr) {- let { string } = ele;-- // only push if _both_ are negative...- if (!intersection && !contains(comparison, 'string', string)) {- result.push(prefix + string);- }-- // or _both_ are positive- if (intersection && contains(comparison, 'string', string)) {- result.push(prefix + string);- }- }- return result;-}--/**- * Zip strings- */--function zip(a, b) {- let arr = [];- for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);- return arr;-}--function compare(a, b) {- return a > b ? 1 : b > a ? -1 : 0;-}--function contains(arr, key, val) {- return arr.some(ele => ele[key] === val);-}--function countNines(min, len) {- return Number(String(min).slice(0, -len) + '9'.repeat(len));-}--function countZeros(integer, zeros) {- return integer - (integer % Math.pow(10, zeros));-}--function toQuantifier(digits) {- let [start = 0, stop = ''] = digits;- if (stop || start > 1) {- return `{${start + (stop ? ',' + stop : '')}}`;- }- return '';-}--function toCharacterClass(a, b, options) {- return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;-}--function hasPadding(str) {- return /^-?(0+)\d/.test(str);-}--function padZeros(value, tok, options) {- if (!tok.isPadded) {- return value;- }-- let diff = Math.abs(tok.maxLen - String(value).length);- let relax = options.relaxZeros !== false;-- switch (diff) {- case 0:- return '';- case 1:- return relax ? '0?' : '0';- case 2:- return relax ? '0{0,2}' : '00';- default: {- return relax ? `0{0,${diff}}` : `0{${diff}}`;- }- }-}--/**- * Cache- */--toRegexRange.cache = {};-toRegexRange.clearCache = () => (toRegexRange.cache = {});--/**- * Expose `toRegexRange`- */--var toRegexRange_1 = toRegexRange;--const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);--const transform = toNumber => {- return value => toNumber === true ? Number(value) : String(value);-};--const isValidValue = value => {- return typeof value === 'number' || (typeof value === 'string' && value !== '');-};--const isNumber$1 = num => Number.isInteger(+num);--const zeros = input => {- let value = `${input}`;- let index = -1;- if (value[0] === '-') value = value.slice(1);- if (value === '0') return false;- while (value[++index] === '0');- return index > 0;-};--const stringify$5 = (start, end, options) => {- if (typeof start === 'string' || typeof end === 'string') {- return true;- }- return options.stringify === true;-};--const pad = (input, maxLength, toNumber) => {- if (maxLength > 0) {- let dash = input[0] === '-' ? '-' : '';- if (dash) input = input.slice(1);- input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));- }- if (toNumber === false) {- return String(input);- }- return input;-};--const toMaxLen = (input, maxLength) => {- let negative = input[0] === '-' ? '-' : '';- if (negative) {- input = input.slice(1);- maxLength--;- }- while (input.length < maxLength) input = '0' + input;- return negative ? ('-' + input) : input;-};--const toSequence = (parts, options) => {- parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);- parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);-- let prefix = options.capture ? '' : '?:';- let positives = '';- let negatives = '';- let result;-- if (parts.positives.length) {- positives = parts.positives.join('|');- }-- if (parts.negatives.length) {- negatives = `-(${prefix}${parts.negatives.join('|')})`;- }-- if (positives && negatives) {- result = `${positives}|${negatives}`;- } else {- result = positives || negatives;- }-- if (options.wrap) {- return `(${prefix}${result})`;- }-- return result;-};--const toRange = (a, b, isNumbers, options) => {- if (isNumbers) {- return toRegexRange_1(a, b, { wrap: false, ...options });- }-- let start = String.fromCharCode(a);- if (a === b) return start;-- let stop = String.fromCharCode(b);- return `[${start}-${stop}]`;-};--const toRegex = (start, end, options) => {- if (Array.isArray(start)) {- let wrap = options.wrap === true;- let prefix = options.capture ? '' : '?:';- return wrap ? `(${prefix}${start.join('|')})` : start.join('|');- }- return toRegexRange_1(start, end, options);-};--const rangeError = (...args) => {- return new RangeError('Invalid range arguments: ' + util.inspect(...args));-};--const invalidRange = (start, end, options) => {- if (options.strictRanges === true) throw rangeError([start, end]);- return [];-};--const invalidStep = (step, options) => {- if (options.strictRanges === true) {- throw new TypeError(`Expected step "${step}" to be a number`);- }- return [];-};--const fillNumbers = (start, end, step = 1, options = {}) => {- let a = Number(start);- let b = Number(end);-- if (!Number.isInteger(a) || !Number.isInteger(b)) {- if (options.strictRanges === true) throw rangeError([start, end]);- return [];- }-- // fix negative zero- if (a === 0) a = 0;- if (b === 0) b = 0;-- let descending = a > b;- let startString = String(start);- let endString = String(end);- let stepString = String(step);- step = Math.max(Math.abs(step), 1);-- let padded = zeros(startString) || zeros(endString) || zeros(stepString);- let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;- let toNumber = padded === false && stringify$5(start, end, options) === false;- let format = options.transform || transform(toNumber);-- if (options.toRegex && step === 1) {- return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);- }-- let parts = { negatives: [], positives: [] };- let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));- let range = [];- let index = 0;-- while (descending ? a >= b : a <= b) {- if (options.toRegex === true && step > 1) {- push(a);- } else {- range.push(pad(format(a, index), maxLen, toNumber));- }- a = descending ? a - step : a + step;- index++;- }-- if (options.toRegex === true) {- return step > 1- ? toSequence(parts, options)- : toRegex(range, null, { wrap: false, ...options });- }-- return range;-};--const fillLetters = (start, end, step = 1, options = {}) => {- if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {- return invalidRange(start, end, options);- }--- let format = options.transform || (val => String.fromCharCode(val));- let a = `${start}`.charCodeAt(0);- let b = `${end}`.charCodeAt(0);-- let descending = a > b;- let min = Math.min(a, b);- let max = Math.max(a, b);-- if (options.toRegex && step === 1) {- return toRange(min, max, false, options);- }-- let range = [];- let index = 0;-- while (descending ? a >= b : a <= b) {- range.push(format(a, index));- a = descending ? a - step : a + step;- index++;- }-- if (options.toRegex === true) {- return toRegex(range, null, { wrap: false, options });- }-- return range;-};--const fill = (start, end, step, options = {}) => {- if (end == null && isValidValue(start)) {- return [start];- }-- if (!isValidValue(start) || !isValidValue(end)) {- return invalidRange(start, end, options);- }-- if (typeof step === 'function') {- return fill(start, end, 1, { transform: step });- }-- if (isObject$1(step)) {- return fill(start, end, 0, step);- }-- let opts = { ...options };- if (opts.capture === true) opts.wrap = true;- step = step || opts.step || 1;-- if (!isNumber$1(step)) {- if (step != null && !isObject$1(step)) return invalidStep(step, opts);- return fill(start, end, 1, step);- }-- if (isNumber$1(start) && isNumber$1(end)) {- return fillNumbers(start, end, step, opts);- }-- return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);-};--var fillRange = fill;--const compile = (ast, options = {}) => {- let walk = (node, parent = {}) => {- let invalidBlock = utils$1.isInvalidBrace(parent);- let invalidNode = node.invalid === true && options.escapeInvalid === true;- let invalid = invalidBlock === true || invalidNode === true;- let prefix = options.escapeInvalid === true ? '\\' : '';- let output = '';-- if (node.isOpen === true) {- return prefix + node.value;- }- if (node.isClose === true) {- return prefix + node.value;- }-- if (node.type === 'open') {- return invalid ? (prefix + node.value) : '(';- }-- if (node.type === 'close') {- return invalid ? (prefix + node.value) : ')';- }-- if (node.type === 'comma') {- return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');- }-- if (node.value) {- return node.value;- }-- if (node.nodes && node.ranges > 0) {- let args = utils$1.reduce(node.nodes);- let range = fillRange(...args, { ...options, wrap: false, toRegex: true });-- if (range.length !== 0) {- return args.length > 1 && range.length > 1 ? `(${range})` : range;- }- }-- if (node.nodes) {- for (let child of node.nodes) {- output += walk(child, node);- }- }- return output;- };-- return walk(ast);-};--var compile_1 = compile;--const append = (queue = '', stash = '', enclose = false) => {- let result = [];-- queue = [].concat(queue);- stash = [].concat(stash);-- if (!stash.length) return queue;- if (!queue.length) {- return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash;- }-- for (let item of queue) {- if (Array.isArray(item)) {- for (let value of item) {- result.push(append(value, stash, enclose));- }- } else {- for (let ele of stash) {- if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;- result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));- }- }- }- return utils$1.flatten(result);-};--const expand = (ast, options = {}) => {- let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;-- let walk = (node, parent = {}) => {- node.queue = [];-- let p = parent;- let q = parent.queue;-- while (p.type !== 'brace' && p.type !== 'root' && p.parent) {- p = p.parent;- q = p.queue;- }-- if (node.invalid || node.dollar) {- q.push(append(q.pop(), stringify$4(node, options)));- return;- }-- if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {- q.push(append(q.pop(), ['{}']));- return;- }-- if (node.nodes && node.ranges > 0) {- let args = utils$1.reduce(node.nodes);-- if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) {- throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');- }-- let range = fillRange(...args, options);- if (range.length === 0) {- range = stringify$4(node, options);- }-- q.push(append(q.pop(), range));- node.nodes = [];- return;- }-- let enclose = utils$1.encloseBrace(node);- let queue = node.queue;- let block = node;-- while (block.type !== 'brace' && block.type !== 'root' && block.parent) {- block = block.parent;- queue = block.queue;- }-- for (let i = 0; i < node.nodes.length; i++) {- let child = node.nodes[i];-- if (child.type === 'comma' && node.type === 'brace') {- if (i === 1) queue.push('');- queue.push('');- continue;- }-- if (child.type === 'close') {- q.push(append(q.pop(), queue, enclose));- continue;- }-- if (child.value && child.type !== 'open') {- queue.push(append(queue.pop(), child.value));- continue;- }-- if (child.nodes) {- walk(child, node);- }- }-- return queue;- };-- return utils$1.flatten(walk(ast));-};--var expand_1 = expand;--var constants = {- MAX_LENGTH: 1024 * 64,-- // Digits- CHAR_0: '0', /* 0 */- CHAR_9: '9', /* 9 */-- // Alphabet chars.- CHAR_UPPERCASE_A: 'A', /* A */- CHAR_LOWERCASE_A: 'a', /* a */- CHAR_UPPERCASE_Z: 'Z', /* Z */- CHAR_LOWERCASE_Z: 'z', /* z */-- CHAR_LEFT_PARENTHESES: '(', /* ( */- CHAR_RIGHT_PARENTHESES: ')', /* ) */-- CHAR_ASTERISK: '*', /* * */-- // Non-alphabetic chars.- CHAR_AMPERSAND: '&', /* & */- CHAR_AT: '@', /* @ */- CHAR_BACKSLASH: '\\', /* \ */- CHAR_BACKTICK: '`', /* ` */- CHAR_CARRIAGE_RETURN: '\r', /* \r */- CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */- CHAR_COLON: ':', /* : */- CHAR_COMMA: ',', /* , */- CHAR_DOLLAR: '$', /* . */- CHAR_DOT: '.', /* . */- CHAR_DOUBLE_QUOTE: '"', /* " */- CHAR_EQUAL: '=', /* = */- CHAR_EXCLAMATION_MARK: '!', /* ! */- CHAR_FORM_FEED: '\f', /* \f */- CHAR_FORWARD_SLASH: '/', /* / */- CHAR_HASH: '#', /* # */- CHAR_HYPHEN_MINUS: '-', /* - */- CHAR_LEFT_ANGLE_BRACKET: '<', /* < */- CHAR_LEFT_CURLY_BRACE: '{', /* { */- CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */- CHAR_LINE_FEED: '\n', /* \n */- CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */- CHAR_PERCENT: '%', /* % */- CHAR_PLUS: '+', /* + */- CHAR_QUESTION_MARK: '?', /* ? */- CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */- CHAR_RIGHT_CURLY_BRACE: '}', /* } */- CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */- CHAR_SEMICOLON: ';', /* ; */- CHAR_SINGLE_QUOTE: '\'', /* ' */- CHAR_SPACE: ' ', /* */- CHAR_TAB: '\t', /* \t */- CHAR_UNDERSCORE: '_', /* _ */- CHAR_VERTICAL_LINE: '|', /* | */- CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */-};--/**- * Constants- */--const {- MAX_LENGTH,- CHAR_BACKSLASH, /* \ */- CHAR_BACKTICK, /* ` */- CHAR_COMMA, /* , */- CHAR_DOT, /* . */- CHAR_LEFT_PARENTHESES, /* ( */- CHAR_RIGHT_PARENTHESES, /* ) */- CHAR_LEFT_CURLY_BRACE, /* { */- CHAR_RIGHT_CURLY_BRACE, /* } */- CHAR_LEFT_SQUARE_BRACKET, /* [ */- CHAR_RIGHT_SQUARE_BRACKET, /* ] */- CHAR_DOUBLE_QUOTE, /* " */- CHAR_SINGLE_QUOTE, /* ' */- CHAR_NO_BREAK_SPACE,- CHAR_ZERO_WIDTH_NOBREAK_SPACE-} = constants;--/**- * parse- */--const parse$1 = (input, options = {}) => {- if (typeof input !== 'string') {- throw new TypeError('Expected a string');- }-- let opts = options || {};- let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;- if (input.length > max) {- throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);- }-- let ast = { type: 'root', input, nodes: [] };- let stack = [ast];- let block = ast;- let prev = ast;- let brackets = 0;- let length = input.length;- let index = 0;- let depth = 0;- let value;-- /**- * Helpers- */-- const advance = () => input[index++];- const push = node => {- if (node.type === 'text' && prev.type === 'dot') {- prev.type = 'text';- }-- if (prev && prev.type === 'text' && node.type === 'text') {- prev.value += node.value;- return;- }-- block.nodes.push(node);- node.parent = block;- node.prev = prev;- prev = node;- return node;- };-- push({ type: 'bos' });-- while (index < length) {- block = stack[stack.length - 1];- value = advance();-- /**- * Invalid chars- */-- if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {- continue;- }-- /**- * Escaped chars- */-- if (value === CHAR_BACKSLASH) {- push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });- continue;- }-- /**- * Right square bracket (literal): ']'- */-- if (value === CHAR_RIGHT_SQUARE_BRACKET) {- push({ type: 'text', value: '\\' + value });- continue;- }-- /**- * Left square bracket: '['- */-- if (value === CHAR_LEFT_SQUARE_BRACKET) {- brackets++;- let next;-- while (index < length && (next = advance())) {- value += next;-- if (next === CHAR_LEFT_SQUARE_BRACKET) {- brackets++;- continue;- }-- if (next === CHAR_BACKSLASH) {- value += advance();- continue;- }-- if (next === CHAR_RIGHT_SQUARE_BRACKET) {- brackets--;-- if (brackets === 0) {- break;- }- }- }-- push({ type: 'text', value });- continue;- }-- /**- * Parentheses- */-- if (value === CHAR_LEFT_PARENTHESES) {- block = push({ type: 'paren', nodes: [] });- stack.push(block);- push({ type: 'text', value });- continue;- }-- if (value === CHAR_RIGHT_PARENTHESES) {- if (block.type !== 'paren') {- push({ type: 'text', value });- continue;- }- block = stack.pop();- push({ type: 'text', value });- block = stack[stack.length - 1];- continue;- }-- /**- * Quotes: '|"|`- */-- if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {- let open = value;- let next;-- if (options.keepQuotes !== true) {- value = '';- }-- while (index < length && (next = advance())) {- if (next === CHAR_BACKSLASH) {- value += next + advance();- continue;- }-- if (next === open) {- if (options.keepQuotes === true) value += next;- break;- }-- value += next;- }-- push({ type: 'text', value });- continue;- }-- /**- * Left curly brace: '{'- */-- if (value === CHAR_LEFT_CURLY_BRACE) {- depth++;-- let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;- let brace = {- type: 'brace',- open: true,- close: false,- dollar,- depth,- commas: 0,- ranges: 0,- nodes: []- };-- block = push(brace);- stack.push(block);- push({ type: 'open', value });- continue;- }-- /**- * Right curly brace: '}'- */-- if (value === CHAR_RIGHT_CURLY_BRACE) {- if (block.type !== 'brace') {- push({ type: 'text', value });- continue;- }-- let type = 'close';- block = stack.pop();- block.close = true;-- push({ type, value });- depth--;-- block = stack[stack.length - 1];- continue;- }-- /**- * Comma: ','- */-- if (value === CHAR_COMMA && depth > 0) {- if (block.ranges > 0) {- block.ranges = 0;- let open = block.nodes.shift();- block.nodes = [open, { type: 'text', value: stringify$4(block) }];- }-- push({ type: 'comma', value });- block.commas++;- continue;- }-- /**- * Dot: '.'- */-- if (value === CHAR_DOT && depth > 0 && block.commas === 0) {- let siblings = block.nodes;-- if (depth === 0 || siblings.length === 0) {- push({ type: 'text', value });- continue;- }-- if (prev.type === 'dot') {- block.range = [];- prev.value += value;- prev.type = 'range';-- if (block.nodes.length !== 3 && block.nodes.length !== 5) {- block.invalid = true;- block.ranges = 0;- prev.type = 'text';- continue;- }-- block.ranges++;- block.args = [];- continue;- }-- if (prev.type === 'range') {- siblings.pop();-- let before = siblings[siblings.length - 1];- before.value += prev.value + value;- prev = before;- block.ranges--;- continue;- }-- push({ type: 'dot', value });- continue;- }-- /**- * Text- */-- push({ type: 'text', value });- }-- // Mark imbalanced braces and brackets as invalid- do {- block = stack.pop();-- if (block.type !== 'root') {- block.nodes.forEach(node => {- if (!node.nodes) {- if (node.type === 'open') node.isOpen = true;- if (node.type === 'close') node.isClose = true;- if (!node.nodes) node.type = 'text';- node.invalid = true;- }- });-- // get the location of the block on parent.nodes (block's siblings)- let parent = stack[stack.length - 1];- let index = parent.nodes.indexOf(block);- // replace the (invalid) block with it's nodes- parent.nodes.splice(index, 1, ...block.nodes);- }- } while (stack.length > 0);-- push({ type: 'eos' });- return ast;-};--var parse_1 = parse$1;--/**- * Expand the given pattern or create a regex-compatible string.- *- * ```js- * const braces = require('braces');- * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']- * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']- * ```- * @param {String} `str`- * @param {Object} `options`- * @return {String}- * @api public- */--const braces = (input, options = {}) => {- let output = [];-- if (Array.isArray(input)) {- for (let pattern of input) {- let result = braces.create(pattern, options);- if (Array.isArray(result)) {- output.push(...result);- } else {- output.push(result);- }- }- } else {- output = [].concat(braces.create(input, options));- }-- if (options && options.expand === true && options.nodupes === true) {- output = [...new Set(output)];- }- return output;-};--/**- * Parse the given `str` with the given `options`.- *- * ```js- * // braces.parse(pattern, [, options]);- * const ast = braces.parse('a/{b,c}/d');- * console.log(ast);- * ```- * @param {String} pattern Brace pattern to parse- * @param {Object} options- * @return {Object} Returns an AST- * @api public- */--braces.parse = (input, options = {}) => parse_1(input, options);--/**- * Creates a braces string from an AST, or an AST node.- *- * ```js- * const braces = require('braces');- * let ast = braces.parse('foo/{a,b}/bar');- * console.log(stringify(ast.nodes[2])); //=> '{a,b}'- * ```- * @param {String} `input` Brace pattern or AST.- * @param {Object} `options`- * @return {Array} Returns an array of expanded values.- * @api public- */--braces.stringify = (input, options = {}) => {- if (typeof input === 'string') {- return stringify$4(braces.parse(input, options), options);- }- return stringify$4(input, options);-};--/**- * Compiles a brace pattern into a regex-compatible, optimized string.- * This method is called by the main [braces](#braces) function by default.- *- * ```js- * const braces = require('braces');- * console.log(braces.compile('a/{b,c}/d'));- * //=> ['a/(b|c)/d']- * ```- * @param {String} `input` Brace pattern or AST.- * @param {Object} `options`- * @return {Array} Returns an array of expanded values.- * @api public- */--braces.compile = (input, options = {}) => {- if (typeof input === 'string') {- input = braces.parse(input, options);- }- return compile_1(input, options);-};--/**- * Expands a brace pattern into an array. This method is called by the- * main [braces](#braces) function when `options.expand` is true. Before- * using this method it's recommended that you read the [performance notes](#performance))- * and advantages of using [.compile](#compile) instead.- *- * ```js- * const braces = require('braces');- * console.log(braces.expand('a/{b,c}/d'));- * //=> ['a/b/d', 'a/c/d'];- * ```- * @param {String} `pattern` Brace pattern- * @param {Object} `options`- * @return {Array} Returns an array of expanded values.- * @api public- */--braces.expand = (input, options = {}) => {- if (typeof input === 'string') {- input = braces.parse(input, options);- }-- let result = expand_1(input, options);-- // filter out empty strings if specified- if (options.noempty === true) {- result = result.filter(Boolean);- }-- // filter out duplicates if specified- if (options.nodupes === true) {- result = [...new Set(result)];- }-- return result;-};--/**- * Processes a brace pattern and returns either an expanded array- * (if `options.expand` is true), a highly optimized regex-compatible string.- * This method is called by the main [braces](#braces) function.- *- * ```js- * const braces = require('braces');- * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))- * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'- * ```- * @param {String} `pattern` Brace pattern- * @param {Object} `options`- * @return {Array} Returns an array of expanded values.- * @api public- */--braces.create = (input, options = {}) => {- if (input === '' || input.length < 3) {- return [input];- }-- return options.expand !== true- ? braces.compile(input, options)- : braces.expand(input, options);-};--/**- * Expose "braces"- */--var braces_1 = braces;--const WIN_SLASH = '\\\\/';-const WIN_NO_SLASH = `[^${WIN_SLASH}]`;--/**- * Posix glob regex- */--const DOT_LITERAL = '\\.';-const PLUS_LITERAL = '\\+';-const QMARK_LITERAL = '\\?';-const SLASH_LITERAL = '\\/';-const ONE_CHAR = '(?=.)';-const QMARK = '[^/]';-const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;-const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;-const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;-const NO_DOT = `(?!${DOT_LITERAL})`;-const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;-const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;-const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;-const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;-const STAR = `${QMARK}*?`;--const POSIX_CHARS = {- DOT_LITERAL,- PLUS_LITERAL,- QMARK_LITERAL,- SLASH_LITERAL,- ONE_CHAR,- QMARK,- END_ANCHOR,- DOTS_SLASH,- NO_DOT,- NO_DOTS,- NO_DOT_SLASH,- NO_DOTS_SLASH,- QMARK_NO_DOT,- STAR,- START_ANCHOR-};--/**- * Windows glob regex- */--const WINDOWS_CHARS = {- ...POSIX_CHARS,-- SLASH_LITERAL: `[${WIN_SLASH}]`,- QMARK: WIN_NO_SLASH,- STAR: `${WIN_NO_SLASH}*?`,- DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,- NO_DOT: `(?!${DOT_LITERAL})`,- NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,- NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,- NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,- QMARK_NO_DOT: `[^.${WIN_SLASH}]`,- START_ANCHOR: `(?:^|[${WIN_SLASH}])`,- END_ANCHOR: `(?:[${WIN_SLASH}]|$)`-};--/**- * POSIX Bracket Regex- */--const POSIX_REGEX_SOURCE = {- alnum: 'a-zA-Z0-9',- alpha: 'a-zA-Z',- ascii: '\\x00-\\x7F',- blank: ' \\t',- cntrl: '\\x00-\\x1F\\x7F',- digit: '0-9',- graph: '\\x21-\\x7E',- lower: 'a-z',- print: '\\x20-\\x7E ',- punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',- space: ' \\t\\r\\n\\v\\f',- upper: 'A-Z',- word: 'A-Za-z0-9_',- xdigit: 'A-Fa-f0-9'-};--var constants$1 = {- MAX_LENGTH: 1024 * 64,- POSIX_REGEX_SOURCE,-- // regular expressions- REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,- REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,- REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,- REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,- REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,- REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,-- // Replace globs with equivalent patterns to reduce parsing time.- REPLACEMENTS: {- '***': '*',- '**/**': '**',- '**/**/**': '**'- },-- // Digits- CHAR_0: 48, /* 0 */- CHAR_9: 57, /* 9 */-- // Alphabet chars.- CHAR_UPPERCASE_A: 65, /* A */- CHAR_LOWERCASE_A: 97, /* a */- CHAR_UPPERCASE_Z: 90, /* Z */- CHAR_LOWERCASE_Z: 122, /* z */-- CHAR_LEFT_PARENTHESES: 40, /* ( */- CHAR_RIGHT_PARENTHESES: 41, /* ) */-- CHAR_ASTERISK: 42, /* * */-- // Non-alphabetic chars.- CHAR_AMPERSAND: 38, /* & */- CHAR_AT: 64, /* @ */- CHAR_BACKWARD_SLASH: 92, /* \ */- CHAR_CARRIAGE_RETURN: 13, /* \r */- CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */- CHAR_COLON: 58, /* : */- CHAR_COMMA: 44, /* , */- CHAR_DOT: 46, /* . */- CHAR_DOUBLE_QUOTE: 34, /* " */- CHAR_EQUAL: 61, /* = */- CHAR_EXCLAMATION_MARK: 33, /* ! */- CHAR_FORM_FEED: 12, /* \f */- CHAR_FORWARD_SLASH: 47, /* / */- CHAR_GRAVE_ACCENT: 96, /* ` */- CHAR_HASH: 35, /* # */- CHAR_HYPHEN_MINUS: 45, /* - */- CHAR_LEFT_ANGLE_BRACKET: 60, /* < */- CHAR_LEFT_CURLY_BRACE: 123, /* { */- CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */- CHAR_LINE_FEED: 10, /* \n */- CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */- CHAR_PERCENT: 37, /* % */- CHAR_PLUS: 43, /* + */- CHAR_QUESTION_MARK: 63, /* ? */- CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */- CHAR_RIGHT_CURLY_BRACE: 125, /* } */- CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */- CHAR_SEMICOLON: 59, /* ; */- CHAR_SINGLE_QUOTE: 39, /* ' */- CHAR_SPACE: 32, /* */- CHAR_TAB: 9, /* \t */- CHAR_UNDERSCORE: 95, /* _ */- CHAR_VERTICAL_LINE: 124, /* | */- CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */-- SEP: path__default.sep,-- /**- * Create EXTGLOB_CHARS- */-- extglobChars(chars) {- return {- '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },- '?': { type: 'qmark', open: '(?:', close: ')?' },- '+': { type: 'plus', open: '(?:', close: ')+' },- '*': { type: 'star', open: '(?:', close: ')*' },- '@': { type: 'at', open: '(?:', close: ')' }- };- },-- /**- * Create GLOB_CHARS- */-- globChars(win32) {- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;- }-};--var utils$2 = createCommonjsModule(function (module, exports) {---const win32 = process.platform === 'win32';-const {- REGEX_BACKSLASH,- REGEX_REMOVE_BACKSLASH,- REGEX_SPECIAL_CHARS,- REGEX_SPECIAL_CHARS_GLOBAL-} = constants$1;--exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);-exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);-exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);-exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');-exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');--exports.removeBackslashes = str => {- return str.replace(REGEX_REMOVE_BACKSLASH, match => {- return match === '\\' ? '' : match;- });-};--exports.supportsLookbehinds = () => {- const segs = process.version.slice(1).split('.').map(Number);- if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {- return true;- }- return false;-};--exports.isWindows = options => {- if (options && typeof options.windows === 'boolean') {- return options.windows;- }- return win32 === true || path__default.sep === '\\';-};--exports.escapeLast = (input, char, lastIdx) => {- const idx = input.lastIndexOf(char, lastIdx);- if (idx === -1) return input;- if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);- return `${input.slice(0, idx)}\\${input.slice(idx)}`;-};--exports.removePrefix = (input, state = {}) => {- let output = input;- if (output.startsWith('./')) {- output = output.slice(2);- state.prefix = './';- }- return output;-};--exports.wrapOutput = (input, state = {}, options = {}) => {- const prepend = options.contains ? '' : '^';- const append = options.contains ? '' : '$';-- let output = `${prepend}(?:${input})${append}`;- if (state.negated === true) {- output = `(?:^(?!${output}).*$)`;- }- return output;-};-});--const {- CHAR_ASTERISK, /* * */- CHAR_AT, /* @ */- CHAR_BACKWARD_SLASH, /* \ */- CHAR_COMMA: CHAR_COMMA$1, /* , */- CHAR_DOT: CHAR_DOT$1, /* . */- CHAR_EXCLAMATION_MARK, /* ! */- CHAR_FORWARD_SLASH, /* / */- CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */- CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */- CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */- CHAR_PLUS, /* + */- CHAR_QUESTION_MARK, /* ? */- CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */- CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */- CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */-} = constants$1;--const isPathSeparator = code => {- return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;-};--const depth = token => {- if (token.isPrefix !== true) {- token.depth = token.isGlobstar ? Infinity : 1;- }-};--/**- * Quickly scans a glob pattern and returns an object with a handful of- * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),- * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).- *- * ```js- * const pm = require('picomatch');- * console.log(pm.scan('foo/bar/*.js'));- * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }- * ```- * @param {String} `str`- * @param {Object} `options`- * @return {Object} Returns an object with tokens and regex source string.- * @api public- */--const scan = (input, options) => {- const opts = options || {};-- const length = input.length - 1;- const scanToEnd = opts.parts === true || opts.scanToEnd === true;- const slashes = [];- const tokens = [];- const parts = [];-- let str = input;- let index = -1;- let start = 0;- let lastIndex = 0;- let isBrace = false;- let isBracket = false;- let isGlob = false;- let isExtglob = false;- let isGlobstar = false;- let braceEscaped = false;- let backslashes = false;- let negated = false;- let finished = false;- let braces = 0;- let prev;- let code;- let token = { value: '', depth: 0, isGlob: false };-- const eos = () => index >= length;- const peek = () => str.charCodeAt(index + 1);- const advance = () => {- prev = code;- return str.charCodeAt(++index);- };-- while (index < length) {- code = advance();- let next;-- if (code === CHAR_BACKWARD_SLASH) {- backslashes = token.backslashes = true;- code = advance();-- if (code === CHAR_LEFT_CURLY_BRACE$1) {- braceEscaped = true;- }- continue;- }-- if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {- braces++;-- while (eos() !== true && (code = advance())) {- if (code === CHAR_BACKWARD_SLASH) {- backslashes = token.backslashes = true;- advance();- continue;- }-- if (code === CHAR_LEFT_CURLY_BRACE$1) {- braces++;- continue;- }-- if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {- isBrace = token.isBrace = true;- isGlob = token.isGlob = true;- finished = true;-- if (scanToEnd === true) {- continue;- }-- break;- }-- if (braceEscaped !== true && code === CHAR_COMMA$1) {- isBrace = token.isBrace = true;- isGlob = token.isGlob = true;- finished = true;-- if (scanToEnd === true) {- continue;- }-- break;- }-- if (code === CHAR_RIGHT_CURLY_BRACE$1) {- braces--;-- if (braces === 0) {- braceEscaped = false;- isBrace = token.isBrace = true;- finished = true;- break;- }- }- }-- if (scanToEnd === true) {- continue;- }-- break;- }-- if (code === CHAR_FORWARD_SLASH) {- slashes.push(index);- tokens.push(token);- token = { value: '', depth: 0, isGlob: false };-- if (finished === true) continue;- if (prev === CHAR_DOT$1 && index === (start + 1)) {- start += 2;- continue;- }-- lastIndex = index + 1;- continue;- }-- if (opts.noext !== true) {- const isExtglobChar = code === CHAR_PLUS- || code === CHAR_AT- || code === CHAR_ASTERISK- || code === CHAR_QUESTION_MARK- || code === CHAR_EXCLAMATION_MARK;-- if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {- isGlob = token.isGlob = true;- isExtglob = token.isExtglob = true;- finished = true;-- if (scanToEnd === true) {- while (eos() !== true && (code = advance())) {- if (code === CHAR_BACKWARD_SLASH) {- backslashes = token.backslashes = true;- code = advance();- continue;- }-- if (code === CHAR_RIGHT_PARENTHESES$1) {- isGlob = token.isGlob = true;- finished = true;- break;- }- }- continue;- }- break;- }- }-- if (code === CHAR_ASTERISK) {- if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;- isGlob = token.isGlob = true;- finished = true;-- if (scanToEnd === true) {- continue;- }- break;- }-- if (code === CHAR_QUESTION_MARK) {- isGlob = token.isGlob = true;- finished = true;-- if (scanToEnd === true) {- continue;- }- break;- }-- if (code === CHAR_LEFT_SQUARE_BRACKET$1) {- while (eos() !== true && (next = advance())) {- if (next === CHAR_BACKWARD_SLASH) {- backslashes = token.backslashes = true;- advance();- continue;- }-- if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {- isBracket = token.isBracket = true;- isGlob = token.isGlob = true;- finished = true;-- if (scanToEnd === true) {- continue;- }- break;- }- }- }-- if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {- negated = token.negated = true;- start++;- continue;- }-- if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {- while (eos() !== true && (code = advance())) {- if (code === CHAR_BACKWARD_SLASH) {- backslashes = token.backslashes = true;- code = advance();- continue;- }-- if (code === CHAR_RIGHT_PARENTHESES$1) {- isGlob = token.isGlob = true;- finished = true;-- if (scanToEnd === true) {- continue;- }- break;- }- }- }-- if (isGlob === true) {- finished = true;-- if (scanToEnd === true) {- continue;- }-- break;- }- }-- if (opts.noext === true) {- isExtglob = false;- isGlob = false;- }-- let base = str;- let prefix = '';- let glob = '';-- if (start > 0) {- prefix = str.slice(0, start);- str = str.slice(start);- lastIndex -= start;- }-- if (base && isGlob === true && lastIndex > 0) {- base = str.slice(0, lastIndex);- glob = str.slice(lastIndex);- } else if (isGlob === true) {- base = '';- glob = str;- } else {- base = str;- }-- if (base && base !== '' && base !== '/' && base !== str) {- if (isPathSeparator(base.charCodeAt(base.length - 1))) {- base = base.slice(0, -1);- }- }-- if (opts.unescape === true) {- if (glob) glob = utils$2.removeBackslashes(glob);-- if (base && backslashes === true) {- base = utils$2.removeBackslashes(base);- }- }-- const state = {- prefix,- input,- start,- base,- glob,- isBrace,- isBracket,- isGlob,- isExtglob,- isGlobstar,- negated- };-- if (opts.tokens === true) {- state.maxDepth = 0;- if (!isPathSeparator(code)) {- tokens.push(token);- }- state.tokens = tokens;- }-- if (opts.parts === true || opts.tokens === true) {- let prevIndex;-- for (let idx = 0; idx < slashes.length; idx++) {- const n = prevIndex ? prevIndex + 1 : start;- const i = slashes[idx];- const value = input.slice(n, i);- if (opts.tokens) {- if (idx === 0 && start !== 0) {- tokens[idx].isPrefix = true;- tokens[idx].value = prefix;- } else {- tokens[idx].value = value;- }- depth(tokens[idx]);- state.maxDepth += tokens[idx].depth;- }- if (idx !== 0 || value !== '') {- parts.push(value);- }- prevIndex = i;- }-- if (prevIndex && prevIndex + 1 < input.length) {- const value = input.slice(prevIndex + 1);- parts.push(value);-- if (opts.tokens) {- tokens[tokens.length - 1].value = value;- depth(tokens[tokens.length - 1]);- state.maxDepth += tokens[tokens.length - 1].depth;- }- }-- state.slashes = slashes;- state.parts = parts;- }-- return state;-};--var scan_1 = scan;--/**- * Constants- */--const {- MAX_LENGTH: MAX_LENGTH$1,- POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,- REGEX_NON_SPECIAL_CHARS,- REGEX_SPECIAL_CHARS_BACKREF,- REPLACEMENTS-} = constants$1;--/**- * Helpers- */--const expandRange = (args, options) => {- if (typeof options.expandRange === 'function') {- return options.expandRange(...args, options);- }-- args.sort();- const value = `[${args.join('-')}]`;-- try {- /* eslint-disable-next-line no-new */- new RegExp(value);- } catch (ex) {- return args.map(v => utils$2.escapeRegex(v)).join('..');- }-- return value;-};--/**- * Create the message for a syntax error- */--const syntaxError$1 = (type, char) => {- return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;-};--/**- * Parse the given input string.- * @param {String} input- * @param {Object} options- * @return {Object}- */--const parse$2 = (input, options) => {- if (typeof input !== 'string') {- throw new TypeError('Expected a string');- }-- input = REPLACEMENTS[input] || input;-- const opts = { ...options };- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;-- let len = input.length;- if (len > max) {- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);- }-- const bos = { type: 'bos', value: '', output: opts.prepend || '' };- const tokens = [bos];-- const capture = opts.capture ? '' : '?:';- const win32 = utils$2.isWindows(options);-- // create constants based on platform, for windows or posix- const PLATFORM_CHARS = constants$1.globChars(win32);- const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);-- const {- DOT_LITERAL,- PLUS_LITERAL,- SLASH_LITERAL,- ONE_CHAR,- DOTS_SLASH,- NO_DOT,- NO_DOT_SLASH,- NO_DOTS_SLASH,- QMARK,- QMARK_NO_DOT,- STAR,- START_ANCHOR- } = PLATFORM_CHARS;-- const globstar = (opts) => {- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;- };-- const nodot = opts.dot ? '' : NO_DOT;- const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;- let star = opts.bash === true ? globstar(opts) : STAR;-- if (opts.capture) {- star = `(${star})`;- }-- // minimatch options support- if (typeof opts.noext === 'boolean') {- opts.noextglob = opts.noext;- }-- const state = {- input,- index: -1,- start: 0,- dot: opts.dot === true,- consumed: '',- output: '',- prefix: '',- backtrack: false,- negated: false,- brackets: 0,- braces: 0,- parens: 0,- quotes: 0,- globstar: false,- tokens- };-- input = utils$2.removePrefix(input, state);- len = input.length;-- const extglobs = [];- const braces = [];- const stack = [];- let prev = bos;- let value;-- /**- * Tokenizing helpers- */-- const eos = () => state.index === len - 1;- const peek = state.peek = (n = 1) => input[state.index + n];- const advance = state.advance = () => input[++state.index];- const remaining = () => input.slice(state.index + 1);- const consume = (value = '', num = 0) => {- state.consumed += value;- state.index += num;- };- const append = token => {- state.output += token.output != null ? token.output : token.value;- consume(token.value);- };-- const negate = () => {- let count = 1;-- while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {- advance();- state.start++;- count++;- }-- if (count % 2 === 0) {- return false;- }-- state.negated = true;- state.start++;- return true;- };-- const increment = type => {- state[type]++;- stack.push(type);- };-- const decrement = type => {- state[type]--;- stack.pop();- };-- /**- * Push tokens onto the tokens array. This helper speeds up- * tokenizing by 1) helping us avoid backtracking as much as possible,- * and 2) helping us avoid creating extra tokens when consecutive- * characters are plain text. This improves performance and simplifies- * lookbehinds.- */-- const push = tok => {- if (prev.type === 'globstar') {- const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');- const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));-- if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {- state.output = state.output.slice(0, -prev.output.length);- prev.type = 'star';- prev.value = '*';- prev.output = star;- state.output += prev.output;- }- }-- if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {- extglobs[extglobs.length - 1].inner += tok.value;- }-- if (tok.value || tok.output) append(tok);- if (prev && prev.type === 'text' && tok.type === 'text') {- prev.value += tok.value;- prev.output = (prev.output || '') + tok.value;- return;- }-- tok.prev = prev;- tokens.push(tok);- prev = tok;- };-- const extglobOpen = (type, value) => {- const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };-- token.prev = prev;- token.parens = state.parens;- token.output = state.output;- const output = (opts.capture ? '(' : '') + token.open;-- increment('parens');--- push({ type, value, output: state.output ? '' : ONE_CHAR });- push({ type: 'paren', extglob: true, value: advance(), output });- extglobs.push(token);- };-- const extglobClose = token => {- let output = token.close + (opts.capture ? ')' : '');-- if (token.type === 'negate') {- let extglobStar = star;-- if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {- extglobStar = globstar(opts);- }-- if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {- output = token.close = `)$))${extglobStar}`;- }-- if (token.prev.type === 'bos' && eos()) {- state.negatedExtglob = true;- }- }-- push({ type: 'paren', extglob: true, value, output });- decrement('parens');- };-- /**- * Fast paths- */-- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {- let backslashes = false;-- let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {- if (first === '\\') {- backslashes = true;- return m;- }-- if (first === '?') {- if (esc) {- return esc + first + (rest ? QMARK.repeat(rest.length) : '');- }- if (index === 0) {- return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');- }- return QMARK.repeat(chars.length);- }-- if (first === '.') {- return DOT_LITERAL.repeat(chars.length);- }-- if (first === '*') {- if (esc) {- return esc + first + (rest ? star : '');- }- return star;- }- return esc ? m : `\\${m}`;- });-- if (backslashes === true) {- if (opts.unescape === true) {- output = output.replace(/\\/g, '');- } else {- output = output.replace(/\\+/g, m => {- return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');- });- }- }-- if (output === input && opts.contains === true) {- state.output = input;- return state;- }-- state.output = utils$2.wrapOutput(output, state, options);- return state;- }-- /**- * Tokenize input until we reach end-of-string- */-- while (!eos()) {- value = advance();-- if (value === '\u0000') {- continue;- }-- /**- * Escaped characters- */-- if (value === '\\') {- const next = peek();-- if (next === '/' && opts.bash !== true) {- continue;- }-- if (next === '.' || next === ';') {- continue;- }-- if (!next) {- value += '\\';- push({ type: 'text', value });- continue;- }-- // collapse slashes to reduce potential for exploits- const match = /^\\+/.exec(remaining());- let slashes = 0;-- if (match && match[0].length > 2) {- slashes = match[0].length;- state.index += slashes;- if (slashes % 2 !== 0) {- value += '\\';- }- }-- if (opts.unescape === true) {- value = advance() || '';- } else {- value += advance() || '';- }-- if (state.brackets === 0) {- push({ type: 'text', value });- continue;- }- }-- /**- * If we're inside a regex character class, continue- * until we reach the closing bracket.- */-- if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {- if (opts.posix !== false && value === ':') {- const inner = prev.value.slice(1);- if (inner.includes('[')) {- prev.posix = true;-- if (inner.includes(':')) {- const idx = prev.value.lastIndexOf('[');- const pre = prev.value.slice(0, idx);- const rest = prev.value.slice(idx + 2);- const posix = POSIX_REGEX_SOURCE$1[rest];- if (posix) {- prev.value = pre + posix;- state.backtrack = true;- advance();-- if (!bos.output && tokens.indexOf(prev) === 1) {- bos.output = ONE_CHAR;- }- continue;- }- }- }- }-- if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {- value = `\\${value}`;- }-- if (value === ']' && (prev.value === '[' || prev.value === '[^')) {- value = `\\${value}`;- }-- if (opts.posix === true && value === '!' && prev.value === '[') {- value = '^';- }-- prev.value += value;- append({ value });- continue;- }-- /**- * If we're inside a quoted string, continue- * until we reach the closing double quote.- */-- if (state.quotes === 1 && value !== '"') {- value = utils$2.escapeRegex(value);- prev.value += value;- append({ value });- continue;- }-- /**- * Double quotes- */-- if (value === '"') {- state.quotes = state.quotes === 1 ? 0 : 1;- if (opts.keepQuotes === true) {- push({ type: 'text', value });- }- continue;- }-- /**- * Parentheses- */-- if (value === '(') {- increment('parens');- push({ type: 'paren', value });- continue;- }-- if (value === ')') {- if (state.parens === 0 && opts.strictBrackets === true) {- throw new SyntaxError(syntaxError$1('opening', '('));- }-- const extglob = extglobs[extglobs.length - 1];- if (extglob && state.parens === extglob.parens + 1) {- extglobClose(extglobs.pop());- continue;- }-- push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });- decrement('parens');- continue;- }-- /**- * Square brackets- */-- if (value === '[') {- if (opts.nobracket === true || !remaining().includes(']')) {- if (opts.nobracket !== true && opts.strictBrackets === true) {- throw new SyntaxError(syntaxError$1('closing', ']'));- }-- value = `\\${value}`;- } else {- increment('brackets');- }-- push({ type: 'bracket', value });- continue;- }-- if (value === ']') {- if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {- push({ type: 'text', value, output: `\\${value}` });- continue;- }-- if (state.brackets === 0) {- if (opts.strictBrackets === true) {- throw new SyntaxError(syntaxError$1('opening', '['));- }-- push({ type: 'text', value, output: `\\${value}` });- continue;- }-- decrement('brackets');-- const prevValue = prev.value.slice(1);- if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {- value = `/${value}`;- }-- prev.value += value;- append({ value });-- // when literal brackets are explicitly disabled- // assume we should match with a regex character class- if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {- continue;- }-- const escaped = utils$2.escapeRegex(prev.value);- state.output = state.output.slice(0, -prev.value.length);-- // when literal brackets are explicitly enabled- // assume we should escape the brackets to match literal characters- if (opts.literalBrackets === true) {- state.output += escaped;- prev.value = escaped;- continue;- }-- // when the user specifies nothing, try to match both- prev.value = `(${capture}${escaped}|${prev.value})`;- state.output += prev.value;- continue;- }-- /**- * Braces- */-- if (value === '{' && opts.nobrace !== true) {- increment('braces');-- const open = {- type: 'brace',- value,- output: '(',- outputIndex: state.output.length,- tokensIndex: state.tokens.length- };-- braces.push(open);- push(open);- continue;- }-- if (value === '}') {- const brace = braces[braces.length - 1];-- if (opts.nobrace === true || !brace) {- push({ type: 'text', value, output: value });- continue;- }-- let output = ')';-- if (brace.dots === true) {- const arr = tokens.slice();- const range = [];-- for (let i = arr.length - 1; i >= 0; i--) {- tokens.pop();- if (arr[i].type === 'brace') {- break;- }- if (arr[i].type !== 'dots') {- range.unshift(arr[i].value);- }- }-- output = expandRange(range, opts);- state.backtrack = true;- }-- if (brace.comma !== true && brace.dots !== true) {- const out = state.output.slice(0, brace.outputIndex);- const toks = state.tokens.slice(brace.tokensIndex);- brace.value = brace.output = '\\{';- value = output = `\\}`;- state.output = out;- for (const t of toks) {- state.output += (t.output || t.value);- }- }-- push({ type: 'brace', value, output });- decrement('braces');- braces.pop();- continue;- }-- /**- * Pipes- */-- if (value === '|') {- if (extglobs.length > 0) {- extglobs[extglobs.length - 1].conditions++;- }- push({ type: 'text', value });- continue;- }-- /**- * Commas- */-- if (value === ',') {- let output = value;-- const brace = braces[braces.length - 1];- if (brace && stack[stack.length - 1] === 'braces') {- brace.comma = true;- output = '|';- }-- push({ type: 'comma', value, output });- continue;- }-- /**- * Slashes- */-- if (value === '/') {- // if the beginning of the glob is "./", advance the start- // to the current index, and don't add the "./" characters- // to the state. This greatly simplifies lookbehinds when- // checking for BOS characters like "!" and "." (not "./")- if (prev.type === 'dot' && state.index === state.start + 1) {- state.start = state.index + 1;- state.consumed = '';- state.output = '';- tokens.pop();- prev = bos; // reset "prev" to the first token- continue;- }-- push({ type: 'slash', value, output: SLASH_LITERAL });- continue;- }-- /**- * Dots- */-- if (value === '.') {- if (state.braces > 0 && prev.type === 'dot') {- if (prev.value === '.') prev.output = DOT_LITERAL;- const brace = braces[braces.length - 1];- prev.type = 'dots';- prev.output += value;- prev.value += value;- brace.dots = true;- continue;- }-- if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {- push({ type: 'text', value, output: DOT_LITERAL });- continue;- }-- push({ type: 'dot', value, output: DOT_LITERAL });- continue;- }-- /**- * Question marks- */-- if (value === '?') {- const isGroup = prev && prev.value === '(';- if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {- extglobOpen('qmark', value);- continue;- }-- if (prev && prev.type === 'paren') {- const next = peek();- let output = value;-- if (next === '<' && !utils$2.supportsLookbehinds()) {- throw new Error('Node.js v10 or higher is required for regex lookbehinds');- }-- if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {- output = `\\${value}`;- }-- push({ type: 'text', value, output });- continue;- }-- if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {- push({ type: 'qmark', value, output: QMARK_NO_DOT });- continue;- }-- push({ type: 'qmark', value, output: QMARK });- continue;- }-- /**- * Exclamation- */-- if (value === '!') {- if (opts.noextglob !== true && peek() === '(') {- if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {- extglobOpen('negate', value);- continue;- }- }-- if (opts.nonegate !== true && state.index === 0) {- negate();- continue;- }- }-- /**- * Plus- */-- if (value === '+') {- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {- extglobOpen('plus', value);- continue;- }-- if ((prev && prev.value === '(') || opts.regex === false) {- push({ type: 'plus', value, output: PLUS_LITERAL });- continue;- }-- if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {- push({ type: 'plus', value });- continue;- }-- push({ type: 'plus', value: PLUS_LITERAL });- continue;- }-- /**- * Plain text- */-- if (value === '@') {- if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {- push({ type: 'at', extglob: true, value, output: '' });- continue;- }-- push({ type: 'text', value });- continue;- }-- /**- * Plain text- */-- if (value !== '*') {- if (value === '$' || value === '^') {- value = `\\${value}`;- }-- const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());- if (match) {- value += match[0];- state.index += match[0].length;- }-- push({ type: 'text', value });- continue;- }-- /**- * Stars- */-- if (prev && (prev.type === 'globstar' || prev.star === true)) {- prev.type = 'star';- prev.star = true;- prev.value += value;- prev.output = star;- state.backtrack = true;- state.globstar = true;- consume(value);- continue;- }-- let rest = remaining();- if (opts.noextglob !== true && /^\([^?]/.test(rest)) {- extglobOpen('star', value);- continue;- }-- if (prev.type === 'star') {- if (opts.noglobstar === true) {- consume(value);- continue;- }-- const prior = prev.prev;- const before = prior.prev;- const isStart = prior.type === 'slash' || prior.type === 'bos';- const afterStar = before && (before.type === 'star' || before.type === 'globstar');-- if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {- push({ type: 'star', value, output: '' });- continue;- }-- const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');- const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');- if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {- push({ type: 'star', value, output: '' });- continue;- }-- // strip consecutive `/**/`- while (rest.slice(0, 3) === '/**') {- const after = input[state.index + 4];- if (after && after !== '/') {- break;- }- rest = rest.slice(3);- consume('/**', 3);- }-- if (prior.type === 'bos' && eos()) {- prev.type = 'globstar';- prev.value += value;- prev.output = globstar(opts);- state.output = prev.output;- state.globstar = true;- consume(value);- continue;- }-- if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {- state.output = state.output.slice(0, -(prior.output + prev.output).length);- prior.output = `(?:${prior.output}`;-- prev.type = 'globstar';- prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');- prev.value += value;- state.globstar = true;- state.output += prior.output + prev.output;- consume(value);- continue;- }-- if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {- const end = rest[1] !== void 0 ? '|$' : '';-- state.output = state.output.slice(0, -(prior.output + prev.output).length);- prior.output = `(?:${prior.output}`;-- prev.type = 'globstar';- prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;- prev.value += value;-- state.output += prior.output + prev.output;- state.globstar = true;-- consume(value + advance());-- push({ type: 'slash', value: '/', output: '' });- continue;- }-- if (prior.type === 'bos' && rest[0] === '/') {- prev.type = 'globstar';- prev.value += value;- prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;- state.output = prev.output;- state.globstar = true;- consume(value + advance());- push({ type: 'slash', value: '/', output: '' });- continue;- }-- // remove single star from output- state.output = state.output.slice(0, -prev.output.length);-- // reset previous token to globstar- prev.type = 'globstar';- prev.output = globstar(opts);- prev.value += value;-- // reset output with globstar- state.output += prev.output;- state.globstar = true;- consume(value);- continue;- }-- const token = { type: 'star', value, output: star };-- if (opts.bash === true) {- token.output = '.*?';- if (prev.type === 'bos' || prev.type === 'slash') {- token.output = nodot + token.output;- }- push(token);- continue;- }-- if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {- token.output = value;- push(token);- continue;- }-- if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {- if (prev.type === 'dot') {- state.output += NO_DOT_SLASH;- prev.output += NO_DOT_SLASH;-- } else if (opts.dot === true) {- state.output += NO_DOTS_SLASH;- prev.output += NO_DOTS_SLASH;-- } else {- state.output += nodot;- prev.output += nodot;- }-- if (peek() !== '*') {- state.output += ONE_CHAR;- prev.output += ONE_CHAR;- }- }-- push(token);- }-- while (state.brackets > 0) {- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']'));- state.output = utils$2.escapeLast(state.output, '[');- decrement('brackets');- }-- while (state.parens > 0) {- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')'));- state.output = utils$2.escapeLast(state.output, '(');- decrement('parens');- }-- while (state.braces > 0) {- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}'));- state.output = utils$2.escapeLast(state.output, '{');- decrement('braces');- }-- if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {- push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });- }-- // rebuild the output if we had to backtrack at any point- if (state.backtrack === true) {- state.output = '';-- for (const token of state.tokens) {- state.output += token.output != null ? token.output : token.value;-- if (token.suffix) {- state.output += token.suffix;- }- }- }-- return state;-};--/**- * Fast paths for creating regular expressions for common glob patterns.- * This can significantly speed up processing and has very little downside- * impact when none of the fast paths match.- */--parse$2.fastpaths = (input, options) => {- const opts = { ...options };- const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;- const len = input.length;- if (len > max) {- throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);- }-- input = REPLACEMENTS[input] || input;- const win32 = utils$2.isWindows(options);-- // create constants based on platform, for windows or posix- const {- DOT_LITERAL,- SLASH_LITERAL,- ONE_CHAR,- DOTS_SLASH,- NO_DOT,- NO_DOTS,- NO_DOTS_SLASH,- STAR,- START_ANCHOR- } = constants$1.globChars(win32);-- const nodot = opts.dot ? NO_DOTS : NO_DOT;- const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;- const capture = opts.capture ? '' : '?:';- const state = { negated: false, prefix: '' };- let star = opts.bash === true ? '.*?' : STAR;-- if (opts.capture) {- star = `(${star})`;- }-- const globstar = (opts) => {- if (opts.noglobstar === true) return star;- return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;- };-- const create = str => {- switch (str) {- case '*':- return `${nodot}${ONE_CHAR}${star}`;-- case '.*':- return `${DOT_LITERAL}${ONE_CHAR}${star}`;-- case '*.*':- return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;-- case '*/*':- return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;-- case '**':- return nodot + globstar(opts);-- case '**/*':- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;-- case '**/*.*':- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;-- case '**/.*':- return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;-- default: {- const match = /^(.*?)\.(\w+)$/.exec(str);- if (!match) return;-- const source = create(match[1]);- if (!source) return;-- return source + DOT_LITERAL + match[2];- }- }- };-- const output = utils$2.removePrefix(input, state);- let source = create(output);-- if (source && opts.strictSlashes !== true) {- source += `${SLASH_LITERAL}?`;- }-- return source;-};--var parse_1$1 = parse$2;--const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);--/**- * Creates a matcher function from one or more glob patterns. The- * returned function takes a string to match as its first argument,- * and returns true if the string is a match. The returned matcher- * function also takes a boolean as the second argument that, when true,- * returns an object with additional information.- *- * ```js- * const picomatch = require('picomatch');- * // picomatch(glob[, options]);- *- * const isMatch = picomatch('*.!(*a)');- * console.log(isMatch('a.a')); //=> false- * console.log(isMatch('a.b')); //=> true- * ```- * @name picomatch- * @param {String|Array} `globs` One or more glob patterns.- * @param {Object=} `options`- * @return {Function=} Returns a matcher function.- * @api public- */--const picomatch = (glob, options, returnState = false) => {- if (Array.isArray(glob)) {- const fns = glob.map(input => picomatch(input, options, returnState));- const arrayMatcher = str => {- for (const isMatch of fns) {- const state = isMatch(str);- if (state) return state;- }- return false;- };- return arrayMatcher;- }-- const isState = isObject$2(glob) && glob.tokens && glob.input;-- if (glob === '' || (typeof glob !== 'string' && !isState)) {- throw new TypeError('Expected pattern to be a non-empty string');- }-- const opts = options || {};- const posix = utils$2.isWindows(options);- const regex = isState- ? picomatch.compileRe(glob, options)- : picomatch.makeRe(glob, options, false, true);-- const state = regex.state;- delete regex.state;-- let isIgnored = () => false;- if (opts.ignore) {- const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };- isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);- }-- const matcher = (input, returnObject = false) => {- const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });- const result = { glob, state, regex, posix, input, output, match, isMatch };-- if (typeof opts.onResult === 'function') {- opts.onResult(result);- }-- if (isMatch === false) {- result.isMatch = false;- return returnObject ? result : false;- }-- if (isIgnored(input)) {- if (typeof opts.onIgnore === 'function') {- opts.onIgnore(result);- }- result.isMatch = false;- return returnObject ? result : false;- }-- if (typeof opts.onMatch === 'function') {- opts.onMatch(result);- }- return returnObject ? result : true;- };-- if (returnState) {- matcher.state = state;- }-- return matcher;-};--/**- * Test `input` with the given `regex`. This is used by the main- * `picomatch()` function to test the input string.- *- * ```js- * const picomatch = require('picomatch');- * // picomatch.test(input, regex[, options]);- *- * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));- * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }- * ```- * @param {String} `input` String to test.- * @param {RegExp} `regex`- * @return {Object} Returns an object with matching info.- * @api public- */--picomatch.test = (input, regex, options, { glob, posix } = {}) => {- if (typeof input !== 'string') {- throw new TypeError('Expected input to be a string');- }-- if (input === '') {- return { isMatch: false, output: '' };- }-- const opts = options || {};- const format = opts.format || (posix ? utils$2.toPosixSlashes : null);- let match = input === glob;- let output = (match && format) ? format(input) : input;-- if (match === false) {- output = format ? format(input) : input;- match = output === glob;- }-- if (match === false || opts.capture === true) {- if (opts.matchBase === true || opts.basename === true) {- match = picomatch.matchBase(input, regex, options, posix);- } else {- match = regex.exec(output);- }- }-- return { isMatch: Boolean(match), match, output };-};--/**- * Match the basename of a filepath.- *- * ```js- * const picomatch = require('picomatch');- * // picomatch.matchBase(input, glob[, options]);- * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true- * ```- * @param {String} `input` String to test.- * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).- * @return {Boolean}- * @api public- */--picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {- const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);- return regex.test(path__default.basename(input));-};--/**- * Returns true if **any** of the given glob `patterns` match the specified `string`.- *- * ```js- * const picomatch = require('picomatch');- * // picomatch.isMatch(string, patterns[, options]);- *- * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true- * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false- * ```- * @param {String|Array} str The string to test.- * @param {String|Array} patterns One or more glob patterns to use for matching.- * @param {Object} [options] See available [options](#options).- * @return {Boolean} Returns true if any patterns match `str`- * @api public- */--picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);--/**- * Parse a glob pattern to create the source string for a regular- * expression.- *- * ```js- * const picomatch = require('picomatch');- * const result = picomatch.parse(pattern[, options]);- * ```- * @param {String} `pattern`- * @param {Object} `options`- * @return {Object} Returns an object with useful properties and output to be used as a regex source string.- * @api public- */--picomatch.parse = (pattern, options) => {- if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));- return parse_1$1(pattern, { ...options, fastpaths: false });-};--/**- * Scan a glob pattern to separate the pattern into segments.- *- * ```js- * const picomatch = require('picomatch');- * // picomatch.scan(input[, options]);- *- * const result = picomatch.scan('!./foo/*.js');- * console.log(result);- * { prefix: '!./',- * input: '!./foo/*.js',- * start: 3,- * base: 'foo',- * glob: '*.js',- * isBrace: false,- * isBracket: false,- * isGlob: true,- * isExtglob: false,- * isGlobstar: false,- * negated: true }- * ```- * @param {String} `input` Glob pattern to scan.- * @param {Object} `options`- * @return {Object} Returns an object with- * @api public- */--picomatch.scan = (input, options) => scan_1(input, options);--/**- * Create a regular expression from a glob pattern.- *- * ```js- * const picomatch = require('picomatch');- * // picomatch.makeRe(input[, options]);- *- * console.log(picomatch.makeRe('*.js'));- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/- * ```- * @param {String} `input` A glob pattern to convert to regex.- * @param {Object} `options`- * @return {RegExp} Returns a regex created from the given pattern.- * @api public- */--picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {- if (returnOutput === true) {- return parsed.output;- }-- const opts = options || {};- const prepend = opts.contains ? '' : '^';- const append = opts.contains ? '' : '$';-- let source = `${prepend}(?:${parsed.output})${append}`;- if (parsed && parsed.negated === true) {- source = `^(?!${source}).*$`;- }-- const regex = picomatch.toRegex(source, options);- if (returnState === true) {- regex.state = parsed;- }-- return regex;-};--picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {- if (!input || typeof input !== 'string') {- throw new TypeError('Expected a non-empty string');- }-- const opts = options || {};- let parsed = { negated: false, fastpaths: true };- let prefix = '';- let output;-- if (input.startsWith('./')) {- input = input.slice(2);- prefix = parsed.prefix = './';- }-- if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {- output = parse_1$1.fastpaths(input, options);- }-- if (output === undefined) {- parsed = parse_1$1(input, options);- parsed.prefix = prefix + (parsed.prefix || '');- } else {- parsed.output = output;- }-- return picomatch.compileRe(parsed, options, returnOutput, returnState);-};--/**- * Create a regular expression from the given regex source string.- *- * ```js- * const picomatch = require('picomatch');- * // picomatch.toRegex(source[, options]);- *- * const { output } = picomatch.parse('*.js');- * console.log(picomatch.toRegex(output));- * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/- * ```- * @param {String} `source` Regular expression source string.- * @param {Object} `options`- * @return {RegExp}- * @api public- */--picomatch.toRegex = (source, options) => {- try {- const opts = options || {};- return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));- } catch (err) {- if (options && options.debug === true) throw err;- return /$^/;- }-};--/**- * Picomatch constants.- * @return {Object}- */--picomatch.constants = constants$1;--/**- * Expose "picomatch"- */--var picomatch_1 = picomatch;--var picomatch$1 = picomatch_1;--const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');--/**- * Returns an array of strings that match one or more glob patterns.- *- * ```js- * const mm = require('micromatch');- * // mm(list, patterns[, options]);- *- * console.log(mm(['a.js', 'a.txt'], ['*.js']));- * //=> [ 'a.js' ]- * ```- * @param {String|Array<string>} list List of strings to match.- * @param {String|Array<string>} patterns One or more glob patterns to use for matching.- * @param {Object} options See available [options](#options)- * @return {Array} Returns an array of matches- * @summary false- * @api public- */--const micromatch = (list, patterns, options) => {- patterns = [].concat(patterns);- list = [].concat(list);-- let omit = new Set();- let keep = new Set();- let items = new Set();- let negatives = 0;-- let onResult = state => {- items.add(state.output);- if (options && options.onResult) {- options.onResult(state);- }- };-- for (let i = 0; i < patterns.length; i++) {- let isMatch = picomatch$1(String(patterns[i]), { ...options, onResult }, true);- let negated = isMatch.state.negated || isMatch.state.negatedExtglob;- if (negated) negatives++;-- for (let item of list) {- let matched = isMatch(item, true);-- let match = negated ? !matched.isMatch : matched.isMatch;- if (!match) continue;-- if (negated) {- omit.add(matched.output);- } else {- omit.delete(matched.output);- keep.add(matched.output);- }- }- }-- let result = negatives === patterns.length ? [...items] : [...keep];- let matches = result.filter(item => !omit.has(item));-- if (options && matches.length === 0) {- if (options.failglob === true) {- throw new Error(`No matches found for "${patterns.join(', ')}"`);- }-- if (options.nonull === true || options.nullglob === true) {- return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;- }- }-- return matches;-};--/**- * Backwards compatibility- */--micromatch.match = micromatch;--/**- * Returns a matcher function from the given glob `pattern` and `options`.- * The returned function takes a string to match as its only argument and returns- * true if the string is a match.- *- * ```js- * const mm = require('micromatch');- * // mm.matcher(pattern[, options]);- *- * const isMatch = mm.matcher('*.!(*a)');- * console.log(isMatch('a.a')); //=> false- * console.log(isMatch('a.b')); //=> true- * ```- * @param {String} `pattern` Glob pattern- * @param {Object} `options`- * @return {Function} Returns a matcher function.- * @api public- */--micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);--/**- * Returns true if **any** of the given glob `patterns` match the specified `string`.- *- * ```js- * const mm = require('micromatch');- * // mm.isMatch(string, patterns[, options]);- *- * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true- * console.log(mm.isMatch('a.a', 'b.*')); //=> false- * ```- * @param {String} str The string to test.- * @param {String|Array} patterns One or more glob patterns to use for matching.- * @param {Object} [options] See available [options](#options).- * @return {Boolean} Returns true if any patterns match `str`- * @api public- */--micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);--/**- * Backwards compatibility- */--micromatch.any = micromatch.isMatch;--/**- * Returns a list of strings that _**do not match any**_ of the given `patterns`.- *- * ```js- * const mm = require('micromatch');- * // mm.not(list, patterns[, options]);- *- * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));- * //=> ['b.b', 'c.c']- * ```- * @param {Array} `list` Array of strings to match.- * @param {String|Array} `patterns` One or more glob pattern to use for matching.- * @param {Object} `options` See available [options](#options) for changing how matches are performed- * @return {Array} Returns an array of strings that **do not match** the given patterns.- * @api public- */--micromatch.not = (list, patterns, options = {}) => {- patterns = [].concat(patterns).map(String);- let result = new Set();- let items = [];-- let onResult = state => {- if (options.onResult) options.onResult(state);- items.push(state.output);- };-- let matches = micromatch(list, patterns, { ...options, onResult });-- for (let item of items) {- if (!matches.includes(item)) {- result.add(item);- }- }- return [...result];-};--/**- * Returns true if the given `string` contains the given pattern. Similar- * to [.isMatch](#isMatch) but the pattern can match any part of the string.- *- * ```js- * var mm = require('micromatch');- * // mm.contains(string, pattern[, options]);- *- * console.log(mm.contains('aa/bb/cc', '*b'));- * //=> true- * console.log(mm.contains('aa/bb/cc', '*d'));- * //=> false- * ```- * @param {String} `str` The string to match.- * @param {String|Array} `patterns` Glob pattern to use for matching.- * @param {Object} `options` See available [options](#options) for changing how matches are performed- * @return {Boolean} Returns true if the patter matches any part of `str`.- * @api public- */--micromatch.contains = (str, pattern, options) => {- if (typeof str !== 'string') {- throw new TypeError(`Expected a string: "${util.inspect(str)}"`);- }-- if (Array.isArray(pattern)) {- return pattern.some(p => micromatch.contains(str, p, options));- }-- if (typeof pattern === 'string') {- if (isEmptyString(str) || isEmptyString(pattern)) {- return false;- }-- if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {- return true;- }- }-- return micromatch.isMatch(str, pattern, { ...options, contains: true });-};--/**- * Filter the keys of the given object with the given `glob` pattern- * and `options`. Does not attempt to match nested keys. If you need this feature,- * use [glob-object][] instead.- *- * ```js- * const mm = require('micromatch');- * // mm.matchKeys(object, patterns[, options]);- *- * const obj = { aa: 'a', ab: 'b', ac: 'c' };- * console.log(mm.matchKeys(obj, '*b'));- * //=> { ab: 'b' }- * ```- * @param {Object} `object` The object with keys to filter.- * @param {String|Array} `patterns` One or more glob patterns to use for matching.- * @param {Object} `options` See available [options](#options) for changing how matches are performed- * @return {Object} Returns an object with only keys that match the given patterns.- * @api public- */--micromatch.matchKeys = (obj, patterns, options) => {- if (!utils$2.isObject(obj)) {- throw new TypeError('Expected the first argument to be an object');- }- let keys = micromatch(Object.keys(obj), patterns, options);- let res = {};- for (let key of keys) res[key] = obj[key];- return res;-};--/**- * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.- *- * ```js- * const mm = require('micromatch');- * // mm.some(list, patterns[, options]);- *- * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));- * // true- * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));- * // false- * ```- * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.- * @param {String|Array} `patterns` One or more glob patterns to use for matching.- * @param {Object} `options` See available [options](#options) for changing how matches are performed- * @return {Boolean} Returns true if any patterns match `str`- * @api public- */--micromatch.some = (list, patterns, options) => {- let items = [].concat(list);-- for (let pattern of [].concat(patterns)) {- let isMatch = picomatch$1(String(pattern), options);- if (items.some(item => isMatch(item))) {- return true;- }- }- return false;-};--/**- * Returns true if every string in the given `list` matches- * any of the given glob `patterns`.- *- * ```js- * const mm = require('micromatch');- * // mm.every(list, patterns[, options]);- *- * console.log(mm.every('foo.js', ['foo.js']));- * // true- * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));- * // true- * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));- * // false- * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));- * // false- * ```- * @param {String|Array} `list` The string or array of strings to test.- * @param {String|Array} `patterns` One or more glob patterns to use for matching.- * @param {Object} `options` See available [options](#options) for changing how matches are performed- * @return {Boolean} Returns true if any patterns match `str`- * @api public- */--micromatch.every = (list, patterns, options) => {- let items = [].concat(list);-- for (let pattern of [].concat(patterns)) {- let isMatch = picomatch$1(String(pattern), options);- if (!items.every(item => isMatch(item))) {- return false;- }- }- return true;-};--/**- * Returns true if **all** of the given `patterns` match- * the specified string.- *- * ```js- * const mm = require('micromatch');- * // mm.all(string, patterns[, options]);- *- * console.log(mm.all('foo.js', ['foo.js']));- * // true- *- * console.log(mm.all('foo.js', ['*.js', '!foo.js']));- * // false- *- * console.log(mm.all('foo.js', ['*.js', 'foo.js']));- * // true- *- * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));- * // true- * ```- * @param {String|Array} `str` The string to test.- * @param {String|Array} `patterns` One or more glob patterns to use for matching.- * @param {Object} `options` See available [options](#options) for changing how matches are performed- * @return {Boolean} Returns true if any patterns match `str`- * @api public- */--micromatch.all = (str, patterns, options) => {- if (typeof str !== 'string') {- throw new TypeError(`Expected a string: "${util.inspect(str)}"`);- }-- return [].concat(patterns).every(p => picomatch$1(p, options)(str));-};--/**- * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.- *- * ```js- * const mm = require('micromatch');- * // mm.capture(pattern, string[, options]);- *- * console.log(mm.capture('test/*.js', 'test/foo.js'));- * //=> ['foo']- * console.log(mm.capture('test/*.js', 'foo/bar.css'));- * //=> null- * ```- * @param {String} `glob` Glob pattern to use for matching.- * @param {String} `input` String to match- * @param {Object} `options` See available [options](#options) for changing how matches are performed- * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.- * @api public- */--micromatch.capture = (glob, input, options) => {- let posix = utils$2.isWindows(options);- let regex = picomatch$1.makeRe(String(glob), { ...options, capture: true });- let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input);-- if (match) {- return match.slice(1).map(v => v === void 0 ? '' : v);- }-};--/**- * Create a regular expression from the given glob `pattern`.- *- * ```js- * const mm = require('micromatch');- * // mm.makeRe(pattern[, options]);- *- * console.log(mm.makeRe('*.js'));- * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/- * ```- * @param {String} `pattern` A glob pattern to convert to regex.- * @param {Object} `options`- * @return {RegExp} Returns a regex created from the given pattern.- * @api public- */--micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);--/**- * Scan a glob pattern to separate the pattern into segments. Used- * by the [split](#split) method.- *- * ```js- * const mm = require('micromatch');- * const state = mm.scan(pattern[, options]);- * ```- * @param {String} `pattern`- * @param {Object} `options`- * @return {Object} Returns an object with- * @api public- */--micromatch.scan = (...args) => picomatch$1.scan(...args);--/**- * Parse a glob pattern to create the source string for a regular- * expression.- *- * ```js- * const mm = require('micromatch');- * const state = mm(pattern[, options]);- * ```- * @param {String} `glob`- * @param {Object} `options`- * @return {Object} Returns an object with useful properties and output to be used as regex source string.- * @api public- */--micromatch.parse = (patterns, options) => {- let res = [];- for (let pattern of [].concat(patterns || [])) {- for (let str of braces_1(String(pattern), options)) {- res.push(picomatch$1.parse(str, options));- }- }- return res;-};--/**- * Process the given brace `pattern`.- *- * ```js- * const { braces } = require('micromatch');- * console.log(braces('foo/{a,b,c}/bar'));- * //=> [ 'foo/(a|b|c)/bar' ]- *- * console.log(braces('foo/{a,b,c}/bar', { expand: true }));- * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]- * ```- * @param {String} `pattern` String with brace pattern to process.- * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.- * @return {Array}- * @api public- */--micromatch.braces = (pattern, options) => {- if (typeof pattern !== 'string') throw new TypeError('Expected a string');- if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {- return [pattern];- }- return braces_1(pattern, options);-};--/**- * Expand braces- */--micromatch.braceExpand = (pattern, options) => {- if (typeof pattern !== 'string') throw new TypeError('Expected a string');- return micromatch.braces(pattern, { ...options, expand: true });-};--/**- * Expose micromatch- */--var micromatch_1 = micromatch;--var pattern = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -const GLOBSTAR = '**'; -const ESCAPE_SYMBOL = '\\'; -const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; -const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; -const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^@!*?+])\(.*\|.*\)/; -const GLOB_EXTENSION_SYMBOLS_RE = /[@!*?+]\(.*\)/; -const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; -function isStaticPattern(pattern, options = {}) { - return !isDynamicPattern(pattern, options); -} -exports.isStaticPattern = isStaticPattern; -function isDynamicPattern(pattern, options = {}) { - /** - * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check - * filepath directly (without read directory). - */ - if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { - return true; - } - if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { - return true; - } - if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { - return true; - } - if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { - return true; - } - return false; -} -exports.isDynamicPattern = isDynamicPattern; -function convertToPositivePattern(pattern) { - return isNegativePattern(pattern) ? pattern.slice(1) : pattern; -} -exports.convertToPositivePattern = convertToPositivePattern; -function convertToNegativePattern(pattern) { - return '!' + pattern; -} -exports.convertToNegativePattern = convertToNegativePattern; -function isNegativePattern(pattern) { - return pattern.startsWith('!') && pattern[1] !== '('; -} -exports.isNegativePattern = isNegativePattern; -function isPositivePattern(pattern) { - return !isNegativePattern(pattern); -} -exports.isPositivePattern = isPositivePattern; -function getNegativePatterns(patterns) { - return patterns.filter(isNegativePattern); -} -exports.getNegativePatterns = getNegativePatterns; -function getPositivePatterns(patterns) { - return patterns.filter(isPositivePattern); -} -exports.getPositivePatterns = getPositivePatterns; -function getBaseDirectory(pattern) { - return globParent(pattern, { flipBackslashes: false }); -} -exports.getBaseDirectory = getBaseDirectory; -function hasGlobStar(pattern) { - return pattern.includes(GLOBSTAR); -} -exports.hasGlobStar = hasGlobStar; -function endsWithSlashGlobStar(pattern) { - return pattern.endsWith('/' + GLOBSTAR); -} -exports.endsWithSlashGlobStar = endsWithSlashGlobStar; -function isAffectDepthOfReadingPattern(pattern) { - const basename = path__default.basename(pattern); - return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); -} -exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; -function getNaiveDepth(pattern) { - const base = getBaseDirectory(pattern); - const patternDepth = pattern.split('/').length; - const patternBaseDepth = base.split('/').length; - /** - * This is a hack for pattern that has no base directory. - * - * This is related to the `*\something\*` pattern. - */ - if (base === '.') { - return patternDepth - patternBaseDepth; - } - return patternDepth - patternBaseDepth - 1; -} -exports.getNaiveDepth = getNaiveDepth; -function getMaxNaivePatternsDepth(patterns) { - return patterns.reduce((max, pattern) => { - const depth = getNaiveDepth(pattern); - return depth > max ? depth : max; - }, 0); -} -exports.getMaxNaivePatternsDepth = getMaxNaivePatternsDepth; -function makeRe(pattern, options) { - return micromatch_1.makeRe(pattern, options); -} -exports.makeRe = makeRe; -function convertPatternsToRe(patterns, options) { - return patterns.map((pattern) => makeRe(pattern, options)); -} -exports.convertPatternsToRe = convertPatternsToRe; -function matchAny(entry, patternsRe) { - const filepath = entry.replace(/^\.[\\/]/, ''); - return patternsRe.some((patternRe) => patternRe.test(filepath)); -} -exports.matchAny = matchAny;-});--var stream = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -function merge(streams) { - const mergedStream = merge2_1(streams); - streams.forEach((stream) => { - stream.once('error', (error) => mergedStream.emit('error', error)); - }); - mergedStream.once('close', () => propagateCloseEventToSources(streams)); - mergedStream.once('end', () => propagateCloseEventToSources(streams)); - return mergedStream; -} -exports.merge = merge; -function propagateCloseEventToSources(streams) { - streams.forEach((stream) => stream.emit('close')); -}-});--var utils$3 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -exports.array = array; - -exports.errno = errno; - -exports.fs = fs; - -exports.path = path_1; - -exports.pattern = pattern; - -exports.stream = stream;-});--var tasks = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -function generate(patterns, settings) { - const positivePatterns = getPositivePatterns(patterns); - const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); - const staticPatterns = positivePatterns.filter((pattern) => utils$3.pattern.isStaticPattern(pattern, settings)); - const dynamicPatterns = positivePatterns.filter((pattern) => utils$3.pattern.isDynamicPattern(pattern, settings)); - const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); - const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); - return staticTasks.concat(dynamicTasks); -} -exports.generate = generate; -function convertPatternsToTasks(positive, negative, dynamic) { - const positivePatternsGroup = groupPatternsByBaseDirectory(positive); - // When we have a global group – there is no reason to divide the patterns into independent tasks. - // In this case, the global task covers the rest. - if ('.' in positivePatternsGroup) { - const task = convertPatternGroupToTask('.', positive, negative, dynamic); - return [task]; - } - return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic); -} -exports.convertPatternsToTasks = convertPatternsToTasks; -function getPositivePatterns(patterns) { - return utils$3.pattern.getPositivePatterns(patterns); -} -exports.getPositivePatterns = getPositivePatterns; -function getNegativePatternsAsPositive(patterns, ignore) { - const negative = utils$3.pattern.getNegativePatterns(patterns).concat(ignore); - const positive = negative.map(utils$3.pattern.convertToPositivePattern); - return positive; -} -exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; -function groupPatternsByBaseDirectory(patterns) { - const group = {}; - return patterns.reduce((collection, pattern) => { - const base = utils$3.pattern.getBaseDirectory(pattern); - if (base in collection) { - collection[base].push(pattern); - } - else { - collection[base] = [pattern]; - } - return collection; - }, group); -} -exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; -function convertPatternGroupsToTasks(positive, negative, dynamic) { - return Object.keys(positive).map((base) => { - return convertPatternGroupToTask(base, positive[base], negative, dynamic); - }); -} -exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; -function convertPatternGroupToTask(base, positive, negative, dynamic) { - return { - dynamic, - positive, - negative, - base, - patterns: [].concat(positive, negative.map(utils$3.pattern.convertToNegativePattern)) - }; -} -exports.convertPatternGroupToTask = convertPatternGroupToTask;-});--var async = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); -function read(path, settings, callback) { - settings.fs.lstat(path, (lstatError, lstat) => { - if (lstatError !== null) { - return callFailureCallback(callback, lstatError); - } - if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { - return callSuccessCallback(callback, lstat); - } - settings.fs.stat(path, (statError, stat) => { - if (statError !== null) { - if (settings.throwErrorOnBrokenSymbolicLink) { - return callFailureCallback(callback, statError); - } - return callSuccessCallback(callback, lstat); - } - if (settings.markSymbolicLink) { - stat.isSymbolicLink = () => true; - } - callSuccessCallback(callback, stat); - }); - }); -} -exports.read = read; -function callFailureCallback(callback, error) { - callback(error); -} -function callSuccessCallback(callback, result) { - callback(null, result); -}-});--var sync = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); -function read(path, settings) { - const lstat = settings.fs.lstatSync(path); - if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { - return lstat; - } - try { - const stat = settings.fs.statSync(path); - if (settings.markSymbolicLink) { - stat.isSymbolicLink = () => true; - } - return stat; - } - catch (error) { - if (!settings.throwErrorOnBrokenSymbolicLink) { - return lstat; - } - throw error; - } -} -exports.read = read;-});--var fs_1$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -exports.FILE_SYSTEM_ADAPTER = { - lstat: fs$2__default.lstat, - stat: fs$2__default.stat, - lstatSync: fs$2__default.lstatSync, - statSync: fs$2__default.statSync -}; -function createFileSystemAdapter(fsMethods) { - if (fsMethods === undefined) { - return exports.FILE_SYSTEM_ADAPTER; - } - return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); -} -exports.createFileSystemAdapter = createFileSystemAdapter;-});--var settings = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -class Settings { - constructor(_options = {}) { - this._options = _options; - this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); - this.fs = fs_1$1.createFileSystemAdapter(this._options.fs); - this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); - } - _getValue(option, value) { - return option === undefined ? value : option; - } -} -exports.default = Settings;-});--var out = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -exports.Settings = settings.default; -function stat(path, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - return async.read(path, getSettings(), optionsOrSettingsOrCallback); - } - async.read(path, getSettings(optionsOrSettingsOrCallback), callback); -} -exports.stat = stat; -function statSync(path, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - return sync.read(path, settings); -} -exports.statSync = statSync; -function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings.default) { - return settingsOrOptions; - } - return new settings.default(settingsOrOptions); -}-});--var runParallel_1 = runParallel;--function runParallel (tasks, cb) {- var results, pending, keys;- var isSync = true;-- if (Array.isArray(tasks)) {- results = [];- pending = tasks.length;- } else {- keys = Object.keys(tasks);- results = {};- pending = keys.length;- }-- function done (err) {- function end () {- if (cb) cb(err, results);- cb = null;- }- if (isSync) process.nextTick(end);- else end();- }-- function each (i, err, result) {- results[i] = result;- if (--pending === 0 || err) {- done(err);- }- }-- if (!pending) {- // empty- done(null);- } else if (keys) {- // object- keys.forEach(function (key) {- tasks[key](function (err, result) { each(key, err, result); });- });- } else {- // array- tasks.forEach(function (task, i) {- task(function (err, result) { each(i, err, result); });- });- }-- isSync = false;-}--var constants$2 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); -const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); -const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); -const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); -const SUPPORTED_MAJOR_VERSION = 10; -const SUPPORTED_MINOR_VERSION = 10; -const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; -const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; -/** - * IS `true` for Node.js 10.10 and greater. - */ -exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;-});--var fs$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); -class DirentFromStats { - constructor(name, stats) { - this.name = name; - this.isBlockDevice = stats.isBlockDevice.bind(stats); - this.isCharacterDevice = stats.isCharacterDevice.bind(stats); - this.isDirectory = stats.isDirectory.bind(stats); - this.isFIFO = stats.isFIFO.bind(stats); - this.isFile = stats.isFile.bind(stats); - this.isSocket = stats.isSocket.bind(stats); - this.isSymbolicLink = stats.isSymbolicLink.bind(stats); - } -} -function createDirentFromStats(name, stats) { - return new DirentFromStats(name, stats); -} -exports.createDirentFromStats = createDirentFromStats;-});--var utils$4 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -exports.fs = fs$1;-});--var async$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - - -function read(directory, settings, callback) { - if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { - return readdirWithFileTypes(directory, settings, callback); - } - return readdir(directory, settings, callback); -} -exports.read = read; -function readdirWithFileTypes(directory, settings, callback) { - settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { - if (readdirError !== null) { - return callFailureCallback(callback, readdirError); - } - const entries = dirents.map((dirent) => ({ - dirent, - name: dirent.name, - path: `${directory}${settings.pathSegmentSeparator}${dirent.name}` - })); - if (!settings.followSymbolicLinks) { - return callSuccessCallback(callback, entries); - } - const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); - runParallel_1(tasks, (rplError, rplEntries) => { - if (rplError !== null) { - return callFailureCallback(callback, rplError); - } - callSuccessCallback(callback, rplEntries); - }); - }); -} -exports.readdirWithFileTypes = readdirWithFileTypes; -function makeRplTaskEntry(entry, settings) { - return (done) => { - if (!entry.dirent.isSymbolicLink()) { - return done(null, entry); - } - settings.fs.stat(entry.path, (statError, stats) => { - if (statError !== null) { - if (settings.throwErrorOnBrokenSymbolicLink) { - return done(statError); - } - return done(null, entry); - } - entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats); - return done(null, entry); - }); - }; -} -function readdir(directory, settings, callback) { - settings.fs.readdir(directory, (readdirError, names) => { - if (readdirError !== null) { - return callFailureCallback(callback, readdirError); - } - const filepaths = names.map((name) => `${directory}${settings.pathSegmentSeparator}${name}`); - const tasks = filepaths.map((filepath) => { - return (done) => out.stat(filepath, settings.fsStatSettings, done); - }); - runParallel_1(tasks, (rplError, results) => { - if (rplError !== null) { - return callFailureCallback(callback, rplError); - } - const entries = []; - names.forEach((name, index) => { - const stats = results[index]; - const entry = { - name, - path: filepaths[index], - dirent: utils$4.fs.createDirentFromStats(name, stats) - }; - if (settings.stats) { - entry.stats = stats; - } - entries.push(entry); - }); - callSuccessCallback(callback, entries); - }); - }); -} -exports.readdir = readdir; -function callFailureCallback(callback, error) { - callback(error); -} -function callSuccessCallback(callback, result) { - callback(null, result); -}-});--var sync$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -function read(directory, settings) { - if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { - return readdirWithFileTypes(directory, settings); - } - return readdir(directory, settings); -} -exports.read = read; -function readdirWithFileTypes(directory, settings) { - const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); - return dirents.map((dirent) => { - const entry = { - dirent, - name: dirent.name, - path: `${directory}${settings.pathSegmentSeparator}${dirent.name}` - }; - if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { - try { - const stats = settings.fs.statSync(entry.path); - entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats); - } - catch (error) { - if (settings.throwErrorOnBrokenSymbolicLink) { - throw error; - } - } - } - return entry; - }); -} -exports.readdirWithFileTypes = readdirWithFileTypes; -function readdir(directory, settings) { - const names = settings.fs.readdirSync(directory); - return names.map((name) => { - const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`; - const stats = out.statSync(entryPath, settings.fsStatSettings); - const entry = { - name, - path: entryPath, - dirent: utils$4.fs.createDirentFromStats(name, stats) - }; - if (settings.stats) { - entry.stats = stats; - } - return entry; - }); -} -exports.readdir = readdir;-});--var fs_1$2 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -exports.FILE_SYSTEM_ADAPTER = { - lstat: fs$2__default.lstat, - stat: fs$2__default.stat, - lstatSync: fs$2__default.lstatSync, - statSync: fs$2__default.statSync, - readdir: fs$2__default.readdir, - readdirSync: fs$2__default.readdirSync -}; -function createFileSystemAdapter(fsMethods) { - if (fsMethods === undefined) { - return exports.FILE_SYSTEM_ADAPTER; - } - return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); -} -exports.createFileSystemAdapter = createFileSystemAdapter;-});--var settings$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -class Settings { - constructor(_options = {}) { - this._options = _options; - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); - this.fs = fs_1$2.createFileSystemAdapter(this._options.fs); - this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default.sep); - this.stats = this._getValue(this._options.stats, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); - this.fsStatSettings = new out.Settings({ - followSymbolicLink: this.followSymbolicLinks, - fs: this.fs, - throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink - }); - } - _getValue(option, value) { - return option === undefined ? value : option; - } -} -exports.default = Settings;-});--var out$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -exports.Settings = settings$1.default; -function scandir(path, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - return async$1.read(path, getSettings(), optionsOrSettingsOrCallback); - } - async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback); -} -exports.scandir = scandir; -function scandirSync(path, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - return sync$1.read(path, settings); -} -exports.scandirSync = scandirSync; -function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings$1.default) { - return settingsOrOptions; - } - return new settings$1.default(settingsOrOptions); -}-});--function reusify (Constructor) {- var head = new Constructor();- var tail = head;-- function get () {- var current = head;-- if (current.next) {- head = current.next;- } else {- head = new Constructor();- tail = head;- }-- current.next = null;-- return current- }-- function release (obj) {- tail.next = obj;- tail = obj;- }-- return {- get: get,- release: release- }-}--var reusify_1 = reusify;--function fastqueue (context, worker, concurrency) {- if (typeof context === 'function') {- concurrency = worker;- worker = context;- context = null;- }-- var cache = reusify_1(Task);- var queueHead = null;- var queueTail = null;- var _running = 0;-- var self = {- push: push,- drain: noop,- saturated: noop,- pause: pause,- paused: false,- concurrency: concurrency,- running: running,- resume: resume,- idle: idle,- length: length,- unshift: unshift,- empty: noop,- kill: kill,- killAndDrain: killAndDrain- };-- return self-- function running () {- return _running- }-- function pause () {- self.paused = true;- }-- function length () {- var current = queueHead;- var counter = 0;-- while (current) {- current = current.next;- counter++;- }-- return counter- }-- function resume () {- if (!self.paused) return- self.paused = false;- for (var i = 0; i < self.concurrency; i++) {- _running++;- release();- }- }-- function idle () {- return _running === 0 && self.length() === 0- }-- function push (value, done) {- var current = cache.get();-- current.context = context;- current.release = release;- current.value = value;- current.callback = done || noop;-- if (_running === self.concurrency || self.paused) {- if (queueTail) {- queueTail.next = current;- queueTail = current;- } else {- queueHead = current;- queueTail = current;- self.saturated();- }- } else {- _running++;- worker.call(context, current.value, current.worked);- }- }-- function unshift (value, done) {- var current = cache.get();-- current.context = context;- current.release = release;- current.value = value;- current.callback = done || noop;-- if (_running === self.concurrency || self.paused) {- if (queueHead) {- current.next = queueHead;- queueHead = current;- } else {- queueHead = current;- queueTail = current;- self.saturated();- }- } else {- _running++;- worker.call(context, current.value, current.worked);- }- }-- function release (holder) {- if (holder) {- cache.release(holder);- }- var next = queueHead;- if (next) {- if (!self.paused) {- if (queueTail === queueHead) {- queueTail = null;- }- queueHead = next.next;- next.next = null;- worker.call(context, next.value, next.worked);- if (queueTail === null) {- self.empty();- }- } else {- _running--;- }- } else if (--_running === 0) {- self.drain();- }- }-- function kill () {- queueHead = null;- queueTail = null;- self.drain = noop;- }-- function killAndDrain () {- queueHead = null;- queueTail = null;- self.drain();- self.drain = noop;- }-}--function noop () {}--function Task () {- this.value = null;- this.callback = noop;- this.next = null;- this.release = noop;- this.context = null;-- var self = this;-- this.worked = function worked (err, result) {- var callback = self.callback;- self.value = null;- self.callback = noop;- callback.call(self.context, err, result);- self.release(self);- };-}--var queue = fastqueue;--var common = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); -function isFatalError(settings, error) { - if (settings.errorFilter === null) { - return true; - } - return !settings.errorFilter(error); -} -exports.isFatalError = isFatalError; -function isAppliedFilter(filter, value) { - return filter === null || filter(value); -} -exports.isAppliedFilter = isAppliedFilter; -function replacePathSegmentSeparator(filepath, separator) { - return filepath.split(/[\\/]/).join(separator); -} -exports.replacePathSegmentSeparator = replacePathSegmentSeparator; -function joinPathSegments(a, b, separator) { - if (a === '') { - return b; - } - return a + separator + b; -} -exports.joinPathSegments = joinPathSegments;-});--var reader = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -class Reader { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); - } -} -exports.default = Reader;-});--var async$2 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - - - -class AsyncReader extends reader.default { - constructor(_root, _settings) { - super(_root, _settings); - this._settings = _settings; - this._scandir = out$1.scandir; - this._emitter = new EventEmitter.EventEmitter(); - this._queue = queue(this._worker.bind(this), this._settings.concurrency); - this._isFatalError = false; - this._isDestroyed = false; - this._queue.drain = () => { - if (!this._isFatalError) { - this._emitter.emit('end'); - } - }; - } - read() { - this._isFatalError = false; - this._isDestroyed = false; - setImmediate(() => { - this._pushToQueue(this._root, this._settings.basePath); - }); - return this._emitter; - } - destroy() { - if (this._isDestroyed) { - throw new Error('The reader is already destroyed'); - } - this._isDestroyed = true; - this._queue.killAndDrain(); - } - onEntry(callback) { - this._emitter.on('entry', callback); - } - onError(callback) { - this._emitter.once('error', callback); - } - onEnd(callback) { - this._emitter.once('end', callback); - } - _pushToQueue(directory, base) { - const queueItem = { directory, base }; - this._queue.push(queueItem, (error) => { - if (error !== null) { - this._handleError(error); - } - }); - } - _worker(item, done) { - this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { - if (error !== null) { - return done(error, undefined); - } - for (const entry of entries) { - this._handleEntry(entry, item.base); - } - done(null, undefined); - }); - } - _handleError(error) { - if (!common.isFatalError(this._settings, error)) { - return; - } - this._isFatalError = true; - this._isDestroyed = true; - this._emitter.emit('error', error); - } - _handleEntry(entry, base) { - if (this._isDestroyed || this._isFatalError) { - return; - } - const fullpath = entry.path; - if (base !== undefined) { - entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); - } - if (common.isAppliedFilter(this._settings.entryFilter, entry)) { - this._emitEntry(entry); - } - if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { - this._pushToQueue(fullpath, entry.path); - } - } - _emitEntry(entry) { - this._emitter.emit('entry', entry); - } -} -exports.default = AsyncReader;-});--var async$3 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -class AsyncProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new async$2.default(this._root, this._settings); - this._storage = new Set(); - } - read(callback) { - this._reader.onError((error) => { - callFailureCallback(callback, error); - }); - this._reader.onEntry((entry) => { - this._storage.add(entry); - }); - this._reader.onEnd(() => { - callSuccessCallback(callback, [...this._storage]); - }); - this._reader.read(); - } -} -exports.default = AsyncProvider; -function callFailureCallback(callback, error) { - callback(error); -} -function callSuccessCallback(callback, entries) { - callback(null, entries); -}-});--var stream$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - -class StreamProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new async$2.default(this._root, this._settings); - this._stream = new Stream$2.Readable({ - objectMode: true, - read: () => { }, - destroy: this._reader.destroy.bind(this._reader) - }); - } - read() { - this._reader.onError((error) => { - this._stream.emit('error', error); - }); - this._reader.onEntry((entry) => { - this._stream.push(entry); - }); - this._reader.onEnd(() => { - this._stream.push(null); - }); - this._reader.read(); - return this._stream; - } -} -exports.default = StreamProvider;-});--var sync$2 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -class SyncReader extends reader.default { - constructor() { - super(...arguments); - this._scandir = out$1.scandirSync; - this._storage = new Set(); - this._queue = new Set(); - } - read() { - this._pushToQueue(this._root, this._settings.basePath); - this._handleQueue(); - return [...this._storage]; - } - _pushToQueue(directory, base) { - this._queue.add({ directory, base }); - } - _handleQueue() { - for (const item of this._queue.values()) { - this._handleDirectory(item.directory, item.base); - } - } - _handleDirectory(directory, base) { - try { - const entries = this._scandir(directory, this._settings.fsScandirSettings); - for (const entry of entries) { - this._handleEntry(entry, base); - } - } - catch (error) { - this._handleError(error); - } - } - _handleError(error) { - if (!common.isFatalError(this._settings, error)) { - return; - } - throw error; - } - _handleEntry(entry, base) { - const fullpath = entry.path; - if (base !== undefined) { - entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); - } - if (common.isAppliedFilter(this._settings.entryFilter, entry)) { - this._pushToStorage(entry); - } - if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { - this._pushToQueue(fullpath, entry.path); - } - } - _pushToStorage(entry) { - this._storage.add(entry); - } -} -exports.default = SyncReader;-});--var sync$3 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -class SyncProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new sync$2.default(this._root, this._settings); - } - read() { - return this._reader.read(); - } -} -exports.default = SyncProvider;-});--var settings$2 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - -class Settings { - constructor(_options = {}) { - this._options = _options; - this.basePath = this._getValue(this._options.basePath, undefined); - this.concurrency = this._getValue(this._options.concurrency, Infinity); - this.deepFilter = this._getValue(this._options.deepFilter, null); - this.entryFilter = this._getValue(this._options.entryFilter, null); - this.errorFilter = this._getValue(this._options.errorFilter, null); - this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default.sep); - this.fsScandirSettings = new out$1.Settings({ - followSymbolicLinks: this._options.followSymbolicLinks, - fs: this._options.fs, - pathSegmentSeparator: this._options.pathSegmentSeparator, - stats: this._options.stats, - throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink - }); - } - _getValue(option, value) { - return option === undefined ? value : option; - } -} -exports.default = Settings;-});--var out$2 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - - -exports.Settings = settings$2.default; -function walk(directory, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === 'function') { - return new async$3.default(directory, getSettings()).read(optionsOrSettingsOrCallback); - } - new async$3.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); -} -exports.walk = walk; -function walkSync(directory, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - const provider = new sync$3.default(directory, settings); - return provider.read(); -} -exports.walkSync = walkSync; -function walkStream(directory, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - const provider = new stream$1.default(directory, settings); - return provider.read(); -} -exports.walkStream = walkStream; -function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings$2.default) { - return settingsOrOptions; - } - return new settings$2.default(settingsOrOptions); -}-});--var reader$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -class Reader { - constructor(_settings) { - this._settings = _settings; - this._fsStatSettings = new out.Settings({ - followSymbolicLink: this._settings.followSymbolicLinks, - fs: this._settings.fs, - throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks - }); - } - _getFullEntryPath(filepath) { - return path__default.resolve(this._settings.cwd, filepath); - } - _makeEntry(stats, pattern) { - const entry = { - name: pattern, - path: pattern, - dirent: utils$3.fs.createDirentFromStats(pattern, stats) - }; - if (this._settings.stats) { - entry.stats = stats; - } - return entry; - } - _isFatalError(error) { - return !utils$3.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; - } -} -exports.default = Reader;-});--var stream$2 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - - -class ReaderStream extends reader$1.default { - constructor() { - super(...arguments); - this._walkStream = out$2.walkStream; - this._stat = out.stat; - } - dynamic(root, options) { - return this._walkStream(root, options); - } - static(patterns, options) { - const filepaths = patterns.map(this._getFullEntryPath, this); - const stream = new Stream$2.PassThrough({ objectMode: true }); - stream._write = (index, _enc, done) => { - return this._getEntry(filepaths[index], patterns[index], options) - .then((entry) => { - if (entry !== null && options.entryFilter(entry)) { - stream.push(entry); - } - if (index === filepaths.length - 1) { - stream.end(); - } - done(); - }) - .catch(done); - }; - for (let i = 0; i < filepaths.length; i++) { - stream.write(i); - } - return stream; - } - _getEntry(filepath, pattern, options) { - return this._getStat(filepath) - .then((stats) => this._makeEntry(stats, pattern)) - .catch((error) => { - if (options.errorFilter(error)) { - return null; - } - throw error; - }); - } - _getStat(filepath) { - return new Promise((resolve, reject) => { - this._stat(filepath, this._fsStatSettings, (error, stats) => { - return error === null ? resolve(stats) : reject(error); - }); - }); - } -} -exports.default = ReaderStream;-});--var deep = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -class DeepFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - } - getFilter(basePath, positive, negative) { - const maxPatternDepth = this._getMaxPatternDepth(positive); - const negativeRe = this._getNegativePatternsRe(negative); - return (entry) => this._filter(basePath, entry, negativeRe, maxPatternDepth); - } - _getMaxPatternDepth(patterns) { - const globstar = patterns.some(utils$3.pattern.hasGlobStar); - return globstar ? Infinity : utils$3.pattern.getMaxNaivePatternsDepth(patterns); - } - _getNegativePatternsRe(patterns) { - const affectDepthOfReadingPatterns = patterns.filter(utils$3.pattern.isAffectDepthOfReadingPattern); - return utils$3.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); - } - _filter(basePath, entry, negativeRe, maxPatternDepth) { - const depth = this._getEntryDepth(basePath, entry.path); - if (this._isSkippedByDeep(depth)) { - return false; - } - if (this._isSkippedByMaxPatternDepth(depth, maxPatternDepth)) { - return false; - } - if (this._isSkippedSymbolicLink(entry)) { - return false; - } - return this._isSkippedByNegativePatterns(entry, negativeRe); - } - _getEntryDepth(basePath, entryPath) { - const basePathDepth = basePath.split('/').length; - const entryPathDepth = entryPath.split('/').length; - return entryPathDepth - (basePath === '' ? 0 : basePathDepth); - } - _isSkippedByDeep(entryDepth) { - return entryDepth >= this._settings.deep; - } - _isSkippedByMaxPatternDepth(entryDepth, maxPatternDepth) { - return !this._settings.baseNameMatch && maxPatternDepth !== Infinity && entryDepth > maxPatternDepth; - } - _isSkippedSymbolicLink(entry) { - return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); - } - _isSkippedByNegativePatterns(entry, negativeRe) { - return !utils$3.pattern.matchAny(entry.path, negativeRe); - } -} -exports.default = DeepFilter;-});--var entry = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -class EntryFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this.index = new Map(); - } - getFilter(positive, negative) { - const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); - const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions); - return (entry) => this._filter(entry, positiveRe, negativeRe); - } - _filter(entry, positiveRe, negativeRe) { - if (this._settings.unique) { - if (this._isDuplicateEntry(entry)) { - return false; - } - this._createIndexRecord(entry); - } - if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { - return false; - } - if (this._isSkippedByAbsoluteNegativePatterns(entry, negativeRe)) { - return false; - } - const filepath = this._settings.baseNameMatch ? entry.name : entry.path; - return this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); - } - _isDuplicateEntry(entry) { - return this.index.has(entry.path); - } - _createIndexRecord(entry) { - this.index.set(entry.path, undefined); - } - _onlyFileFilter(entry) { - return this._settings.onlyFiles && !entry.dirent.isFile(); - } - _onlyDirectoryFilter(entry) { - return this._settings.onlyDirectories && !entry.dirent.isDirectory(); - } - _isSkippedByAbsoluteNegativePatterns(entry, negativeRe) { - if (!this._settings.absolute) { - return false; - } - const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entry.path); - return this._isMatchToPatterns(fullpath, negativeRe); - } - _isMatchToPatterns(filepath, patternsRe) { - return utils$3.pattern.matchAny(filepath, patternsRe); - } -} -exports.default = EntryFilter;-});--var error = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -class ErrorFilter { - constructor(_settings) { - this._settings = _settings; - } - getFilter() { - return (error) => this._isNonFatalError(error); - } - _isNonFatalError(error) { - return utils$3.errno.isEnoentCodeError(error) || this._settings.suppressErrors; - } -} -exports.default = ErrorFilter;-});--var entry$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - -class EntryTransformer { - constructor(_settings) { - this._settings = _settings; - } - getTransformer() { - return (entry) => this._transform(entry); - } - _transform(entry) { - let filepath = entry.path; - if (this._settings.absolute) { - filepath = utils$3.path.makeAbsolute(this._settings.cwd, filepath); - filepath = utils$3.path.unixify(filepath); - } - if (this._settings.markDirectories && entry.dirent.isDirectory()) { - filepath += '/'; - } - if (!this._settings.objectMode) { - return filepath; - } - return Object.assign(Object.assign({}, entry), { path: filepath }); - } -} -exports.default = EntryTransformer;-});--var provider = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - - - -class Provider { - constructor(_settings) { - this._settings = _settings; - this.errorFilter = new error.default(this._settings); - this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions()); - this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions()); - this.entryTransformer = new entry$1.default(this._settings); - } - _getRootDirectory(task) { - return path__default.resolve(this._settings.cwd, task.base); - } - _getReaderOptions(task) { - const basePath = task.base === '.' ? '' : task.base; - return { - basePath, - pathSegmentSeparator: '/', - concurrency: this._settings.concurrency, - deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), - entryFilter: this.entryFilter.getFilter(task.positive, task.negative), - errorFilter: this.errorFilter.getFilter(), - followSymbolicLinks: this._settings.followSymbolicLinks, - fs: this._settings.fs, - stats: this._settings.stats, - throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, - transform: this.entryTransformer.getTransformer() - }; - } - _getMicromatchOptions() { - return { - dot: this._settings.dot, - matchBase: this._settings.baseNameMatch, - nobrace: !this._settings.braceExpansion, - nocase: !this._settings.caseSensitiveMatch, - noext: !this._settings.extglob, - noglobstar: !this._settings.globstar, - posix: true, - strictSlashes: false - }; - } -} -exports.default = Provider;-});--var async$4 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - -class ProviderAsync extends provider.default { - constructor() { - super(...arguments); - this._reader = new stream$2.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const entries = []; - return new Promise((resolve, reject) => { - const stream = this.api(root, task, options); - stream.once('error', reject); - stream.on('data', (entry) => entries.push(options.transform(entry))); - stream.once('end', () => resolve(entries)); - }); - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } -} -exports.default = ProviderAsync;-});--var stream$3 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -class ProviderStream extends provider.default { - constructor() { - super(...arguments); - this._reader = new stream$2.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const source = this.api(root, task, options); - const destination = new Stream$2.Readable({ objectMode: true, read: () => { } }); - source - .once('error', (error) => destination.emit('error', error)) - .on('data', (entry) => destination.emit('data', options.transform(entry))) - .once('end', () => destination.emit('end')); - destination - .once('close', () => source.destroy()); - return destination; - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } -} -exports.default = ProviderStream;-});--var sync$4 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - - -class ReaderSync extends reader$1.default { - constructor() { - super(...arguments); - this._walkSync = out$2.walkSync; - this._statSync = out.statSync; - } - dynamic(root, options) { - return this._walkSync(root, options); - } - static(patterns, options) { - const entries = []; - for (const pattern of patterns) { - const filepath = this._getFullEntryPath(pattern); - const entry = this._getEntry(filepath, pattern, options); - if (entry === null || !options.entryFilter(entry)) { - continue; - } - entries.push(entry); - } - return entries; - } - _getEntry(filepath, pattern, options) { - try { - const stats = this._getStat(filepath); - return this._makeEntry(stats, pattern); - } - catch (error) { - if (options.errorFilter(error)) { - return null; - } - throw error; - } - } - _getStat(filepath) { - return this._statSync(filepath, this._fsStatSettings); - } -} -exports.default = ReaderSync;-});--var sync$5 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - -class ProviderSync extends provider.default { - constructor() { - super(...arguments); - this._reader = new sync$4.default(this._settings); - } - read(task) { - const root = this._getRootDirectory(task); - const options = this._getReaderOptions(task); - const entries = this.api(root, task, options); - return entries.map(options.transform); - } - api(root, task, options) { - if (task.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task.patterns, options); - } -} -exports.default = ProviderSync;-});--var settings$3 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true }); - - -const CPU_COUNT = require$$1.cpus().length; -exports.DEFAULT_FILE_SYSTEM_ADAPTER = { - lstat: fs$2__default.lstat, - lstatSync: fs$2__default.lstatSync, - stat: fs$2__default.stat, - statSync: fs$2__default.statSync, - readdir: fs$2__default.readdir, - readdirSync: fs$2__default.readdirSync -}; -class Settings { - constructor(_options = {}) { - this._options = _options; - this.absolute = this._getValue(this._options.absolute, false); - this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); - this.braceExpansion = this._getValue(this._options.braceExpansion, true); - this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); - this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); - this.cwd = this._getValue(this._options.cwd, process.cwd()); - this.deep = this._getValue(this._options.deep, Infinity); - this.dot = this._getValue(this._options.dot, false); - this.extglob = this._getValue(this._options.extglob, true); - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); - this.fs = this._getFileSystemMethods(this._options.fs); - this.globstar = this._getValue(this._options.globstar, true); - this.ignore = this._getValue(this._options.ignore, []); - this.markDirectories = this._getValue(this._options.markDirectories, false); - this.objectMode = this._getValue(this._options.objectMode, false); - this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); - this.onlyFiles = this._getValue(this._options.onlyFiles, true); - this.stats = this._getValue(this._options.stats, false); - this.suppressErrors = this._getValue(this._options.suppressErrors, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); - this.unique = this._getValue(this._options.unique, true); - if (this.onlyDirectories) { - this.onlyFiles = false; - } - if (this.stats) { - this.objectMode = true; - } - } - _getValue(option, value) { - return option === undefined ? value : option; - } - _getFileSystemMethods(methods = {}) { - return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); - } -} -exports.default = Settings;-});--function FastGlob(source, options) { - try { - assertPatternsInput(source); - } - catch (error) { - return Promise.reject(error); - } - const works = getWorks(source, async$4.default, options); - return Promise.all(works).then(utils$3.array.flatten); -} -// https://github.com/typescript-eslint/typescript-eslint/issues/60 -// eslint-disable-next-line no-redeclare -(function (FastGlob) { - function sync(source, options) { - assertPatternsInput(source); - const works = getWorks(source, sync$5.default, options); - return utils$3.array.flatten(works); - } - FastGlob.sync = sync; - function stream(source, options) { - assertPatternsInput(source); - const works = getWorks(source, stream$3.default, options); - /** - * The stream returned by the provider cannot work with an asynchronous iterator. - * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. - * This affects performance (+25%). I don't see best solution right now. - */ - return utils$3.stream.merge(works); - } - FastGlob.stream = stream; - function generateTasks(source, options) { - assertPatternsInput(source); - const patterns = [].concat(source); - const settings = new settings$3.default(options); - return tasks.generate(patterns, settings); - } - FastGlob.generateTasks = generateTasks; - function isDynamicPattern(source, options) { - assertPatternsInput(source); - const settings = new settings$3.default(options); - return utils$3.pattern.isDynamicPattern(source, settings); - } - FastGlob.isDynamicPattern = isDynamicPattern; - function escapePath(source) { - assertPatternsInput(source); - return utils$3.path.escape(source); - } - FastGlob.escapePath = escapePath; -})(FastGlob || (FastGlob = {})); -function getWorks(source, _Provider, options) { - const patterns = [].concat(source); - const settings = new settings$3.default(options); - const tasks$1 = tasks.generate(patterns, settings); - const provider = new _Provider(settings); - return tasks$1.map(provider.read, provider); -} -function assertPatternsInput(source) { - if ([].concat(source).every(isString)) { - return; - } - throw new TypeError('Patterns must be a string or an array of strings'); -} -function isString(source) { - return typeof source === 'string'; -} -var out$3 = FastGlob;--const {promisify} = util;---async function isType$1(fsStatType, statsMethodName, filePath) {- if (typeof filePath !== 'string') {- throw new TypeError(`Expected a string, got ${typeof filePath}`);- }-- try {- const stats = await promisify(fs$2__default[fsStatType])(filePath);- return stats[statsMethodName]();- } catch (error) {- if (error.code === 'ENOENT') {- return false;- }-- throw error;- }-}--function isTypeSync(fsStatType, statsMethodName, filePath) {- if (typeof filePath !== 'string') {- throw new TypeError(`Expected a string, got ${typeof filePath}`);- }-- try {- return fs$2__default[fsStatType](filePath)[statsMethodName]();- } catch (error) {- if (error.code === 'ENOENT') {- return false;- }-- throw error;- }-}--var isFile = isType$1.bind(null, 'stat', 'isFile');-var isDirectory = isType$1.bind(null, 'stat', 'isDirectory');-var isSymlink = isType$1.bind(null, 'lstat', 'isSymbolicLink');-var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');-var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');-var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');--var pathType = {- isFile: isFile,- isDirectory: isDirectory,- isSymlink: isSymlink,- isFileSync: isFileSync,- isDirectorySync: isDirectorySync,- isSymlinkSync: isSymlinkSync-};--const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];--const getPath = (filepath, cwd) => {- const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;- return path__default.isAbsolute(pth) ? pth : path__default.join(cwd, pth);-};--const addExtensions = (file, extensions) => {- if (path__default.extname(file)) {- return `**/${file}`;- }-- return `**/${file}.${getExtensions(extensions)}`;-};--const getGlob = (directory, options) => {- if (options.files && !Array.isArray(options.files)) {- throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);- }-- if (options.extensions && !Array.isArray(options.extensions)) {- throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);- }-- if (options.files && options.extensions) {- return options.files.map(x => path__default.posix.join(directory, addExtensions(x, options.extensions)));- }-- if (options.files) {- return options.files.map(x => path__default.posix.join(directory, `**/${x}`));- }-- if (options.extensions) {- return [path__default.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];- }-- return [path__default.posix.join(directory, '**')];-};--var dirGlob = async (input, options) => {- options = {- cwd: process.cwd(),- ...options- };-- if (typeof options.cwd !== 'string') {- throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);- }-- const globs = await Promise.all([].concat(input).map(async x => {- const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));- return isDirectory ? getGlob(x, options) : x;- }));-- return [].concat.apply([], globs); // eslint-disable-line prefer-spread-};--var sync$6 = (input, options) => {- options = {- cwd: process.cwd(),- ...options- };-- if (typeof options.cwd !== 'string') {- throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);- }-- const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);-- return [].concat.apply([], globs); // eslint-disable-line prefer-spread-};-dirGlob.sync = sync$6;--// A simple implementation of make-array-function makeArray (subject) {- return Array.isArray(subject)- ? subject- : [subject]-}--const REGEX_TEST_BLANK_LINE = /^\s+$/;-const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;-const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;-const REGEX_SPLITALL_CRLF = /\r?\n/g;-// /foo,-// ./foo,-// ../foo,-// .-// ..-const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;--const SLASH = '/';-const KEY_IGNORE = typeof Symbol !== 'undefined'- ? Symbol.for('node-ignore')- /* istanbul ignore next */- : 'node-ignore';--const define = (object, key, value) =>- Object.defineProperty(object, key, {value});--const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;--// Sanitize the range of a regular expression-// The cases are complicated, see test cases for details-const sanitizeRange = range => range.replace(- REGEX_REGEXP_RANGE,- (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)- ? match- // Invalid range (out of order) which is ok for gitignore rules but- // fatal for JavaScript regular expression, so eliminate it.- : ''-);--// > If the pattern ends with a slash,-// > it is removed for the purpose of the following description,-// > but it would only find a match with a directory.-// > In other words, foo/ will match a directory foo and paths underneath it,-// > but will not match a regular file or a symbolic link foo-// > (this is consistent with the way how pathspec works in general in Git).-// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'-// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call-// you could use option `mark: true` with `glob`--// '`foo/`' should not continue with the '`..`'-const REPLACERS = [-- // > Trailing spaces are ignored unless they are quoted with backslash ("\")- [- // (a\ ) -> (a )- // (a ) -> (a)- // (a \ ) -> (a )- /\\?\s+$/,- match => match.indexOf('\\') === 0- ? ' '- : ''- ],-- // replace (\ ) with ' '- [- /\\\s/g,- () => ' '- ],-- // Escape metacharacters- // which is written down by users but means special for regular expressions.-- // > There are 12 characters with special meanings:- // > - the backslash \,- // > - the caret ^,- // > - the dollar sign $,- // > - the period or dot .,- // > - the vertical bar or pipe symbol |,- // > - the question mark ?,- // > - the asterisk or star *,- // > - the plus sign +,- // > - the opening parenthesis (,- // > - the closing parenthesis ),- // > - and the opening square bracket [,- // > - the opening curly brace {,- // > These special characters are often called "metacharacters".- [- /[\\^$.|*+(){]/g,- match => `\\${match}`- ],-- [- // > [abc] matches any character inside the brackets- // > (in this case a, b, or c);- /\[([^\]/]*)($|\])/g,- (match, p1, p2) => p2 === ']'- ? `[${sanitizeRange(p1)}]`- : `\\${match}`- ],-- [- // > a question mark (?) matches a single character- /(?!\\)\?/g,- () => '[^/]'- ],-- // leading slash- [-- // > A leading slash matches the beginning of the pathname.- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".- // A leading slash matches the beginning of the pathname- /^\//,- () => '^'- ],-- // replace special metacharacter slash after the leading slash- [- /\//g,- () => '\\/'- ],-- [- // > A leading "**" followed by a slash means match in all directories.- // > For example, "**/foo" matches file or directory "foo" anywhere,- // > the same as pattern "foo".- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly- // > under directory "foo".- // Notice that the '*'s have been replaced as '\\*'- /^\^*\\\*\\\*\\\//,-- // '**/foo' <-> 'foo'- () => '^(?:.*\\/)?'- ],-- // ending- [- // 'js' will not match 'js.'- // 'ab' will not match 'abc'- /(?:[^*])$/,-- // WTF!- // https://git-scm.com/docs/gitignore- // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)- // which re-fixes #24, #38-- // > If there is a separator at the end of the pattern then the pattern- // > will only match directories, otherwise the pattern can match both- // > files and directories.-- // 'js*' will not match 'a.js'- // 'js/' will not match 'a.js'- // 'js' will match 'a.js' and 'a.js/'- match => /\/$/.test(match)- // foo/ will not match 'foo'- ? `${match}$`- // foo matches 'foo' and 'foo/'- : `${match}(?=$|\\/$)`- ],-- // starting- [- // there will be no leading '/'- // (which has been replaced by section "leading slash")- // If starts with '**', adding a '^' to the regular expression also works- /^(?=[^^])/,- function startingReplacer () {- // If has a slash `/` at the beginning or middle- return !/\/(?!$)/.test(this)- // > Prior to 2.22.1- // > If the pattern does not contain a slash /,- // > Git treats it as a shell glob pattern- // Actually, if there is only a trailing slash,- // git also treats it as a shell glob pattern-- // After 2.22.1 (compatible but clearer)- // > If there is a separator at the beginning or middle (or both)- // > of the pattern, then the pattern is relative to the directory- // > level of the particular .gitignore file itself.- // > Otherwise the pattern may also match at any level below- // > the .gitignore level.- ? '(?:^|\\/)'-- // > Otherwise, Git treats the pattern as a shell glob suitable for- // > consumption by fnmatch(3)- : '^'- }- ],-- // two globstars- [- // Use lookahead assertions so that we could match more than one `'/**'`- /\\\/\\\*\\\*(?=\\\/|$)/g,-- // Zero, one or several directories- // should not use '*', or it will be replaced by the next replacer-- // Check if it is not the last `'/**'`- (_, index, str) => index + 6 < str.length-- // case: /**/- // > A slash followed by two consecutive asterisks then a slash matches- // > zero or more directories.- // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.- // '/**/'- ? '(?:\\/[^\\/]+)*'-- // case: /**- // > A trailing `"/**"` matches everything inside.-- // #21: everything inside but it should not include the current folder- : '\\/.+'- ],-- // intermediate wildcards- [- // Never replace escaped '*'- // ignore rule '\*' will match the path '*'-- // 'abc.*/' -> go- // 'abc.*' -> skip this rule- /(^|[^\\]+)\\\*(?=.+)/g,-- // '*.js' matches '.js'- // '*.js' doesn't match 'abc'- (_, p1) => `${p1}[^\\/]*`- ],-- // trailing wildcard- [- /(\^|\\\/)?\\\*$/,- (_, p1) => {- const prefix = p1- // '\^':- // '/*' does not match ''- // '/*' does not match everything-- // '\\\/':- // 'abc/*' does not match 'abc/'- ? `${p1}[^/]+`-- // 'a*' matches 'a'- // 'a*' matches 'aa'- : '[^/]*';-- return `${prefix}(?=$|\\/$)`- }- ],-- [- // unescape- /\\\\\\/g,- () => '\\'- ]-];--// A simple cache, because an ignore rule only has only one certain meaning-const regexCache = Object.create(null);--// @param {pattern}-const makeRegex = (pattern, negative, ignorecase) => {- const r = regexCache[pattern];- if (r) {- return r- }-- // const replacers = negative- // ? NEGATIVE_REPLACERS- // : POSITIVE_REPLACERS-- const source = REPLACERS.reduce(- (prev, current) => prev.replace(current[0], current[1].bind(pattern)),- pattern- );-- return regexCache[pattern] = ignorecase- ? new RegExp(source, 'i')- : new RegExp(source)-};--const isString$1 = subject => typeof subject === 'string';--// > A blank line matches no files, so it can serve as a separator for readability.-const checkPattern = pattern => pattern- && isString$1(pattern)- && !REGEX_TEST_BLANK_LINE.test(pattern)-- // > A line starting with # serves as a comment.- && pattern.indexOf('#') !== 0;--const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);--class IgnoreRule {- constructor (- origin,- pattern,- negative,- regex- ) {- this.origin = origin;- this.pattern = pattern;- this.negative = negative;- this.regex = regex;- }-}--const createRule = (pattern, ignorecase) => {- const origin = pattern;- let negative = false;-- // > An optional prefix "!" which negates the pattern;- if (pattern.indexOf('!') === 0) {- negative = true;- pattern = pattern.substr(1);- }-- pattern = pattern- // > Put a backslash ("\") in front of the first "!" for patterns that- // > begin with a literal "!", for example, `"\!important!.txt"`.- .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')- // > Put a backslash ("\") in front of the first hash for patterns that- // > begin with a hash.- .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');-- const regex = makeRegex(pattern, negative, ignorecase);-- return new IgnoreRule(- origin,- pattern,- negative,- regex- )-};--const throwError = (message, Ctor) => {- throw new Ctor(message)-};--const checkPath$1 = (path, originalPath, doThrow) => {- if (!isString$1(path)) {- return doThrow(- `path must be a string, but got \`${originalPath}\``,- TypeError- )- }-- // We don't know if we should ignore '', so throw- if (!path) {- return doThrow(`path must not be empty`, TypeError)- }-- // Check if it is a relative path- if (checkPath$1.isNotRelative(path)) {- const r = '`path.relative()`d';- return doThrow(- `path should be a ${r} string, but got "${originalPath}"`,- RangeError- )- }-- return true-};--const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);--checkPath$1.isNotRelative = isNotRelative;-checkPath$1.convert = p => p;--class Ignore {- constructor ({- ignorecase = true- } = {}) {- this._rules = [];- this._ignorecase = ignorecase;- define(this, KEY_IGNORE, true);- this._initCache();- }-- _initCache () {- this._ignoreCache = Object.create(null);- this._testCache = Object.create(null);- }-- _addPattern (pattern) {- // #32- if (pattern && pattern[KEY_IGNORE]) {- this._rules = this._rules.concat(pattern._rules);- this._added = true;- return- }-- if (checkPattern(pattern)) {- const rule = createRule(pattern, this._ignorecase);- this._added = true;- this._rules.push(rule);- }- }-- // @param {Array<string> | string | Ignore} pattern- add (pattern) {- this._added = false;-- makeArray(- isString$1(pattern)- ? splitPattern(pattern)- : pattern- ).forEach(this._addPattern, this);-- // Some rules have just added to the ignore,- // making the behavior changed.- if (this._added) {- this._initCache();- }-- return this- }-- // legacy- addPattern (pattern) {- return this.add(pattern)- }-- // | ignored : unignored- // negative | 0:0 | 0:1 | 1:0 | 1:1- // -------- | ------- | ------- | ------- | --------- // 0 | TEST | TEST | SKIP | X- // 1 | TESTIF | SKIP | TEST | X-- // - SKIP: always skip- // - TEST: always test- // - TESTIF: only test if checkUnignored- // - X: that never happen-- // @param {boolean} whether should check if the path is unignored,- // setting `checkUnignored` to `false` could reduce additional- // path matching.-- // @returns {TestResult} true if a file is ignored- _testOne (path, checkUnignored) {- let ignored = false;- let unignored = false;-- this._rules.forEach(rule => {- const {negative} = rule;- if (- unignored === negative && ignored !== unignored- || negative && !ignored && !unignored && !checkUnignored- ) {- return- }-- const matched = rule.regex.test(path);-- if (matched) {- ignored = !negative;- unignored = negative;- }- });-- return {- ignored,- unignored- }- }-- // @returns {TestResult}- _test (originalPath, cache, checkUnignored, slices) {- const path = originalPath- // Supports nullable path- && checkPath$1.convert(originalPath);-- checkPath$1(path, originalPath, throwError);-- return this._t(path, cache, checkUnignored, slices)- }-- _t (path, cache, checkUnignored, slices) {- if (path in cache) {- return cache[path]- }-- if (!slices) {- // path/to/a.js- // ['path', 'to', 'a.js']- slices = path.split(SLASH);- }-- slices.pop();-- // If the path has no parent directory, just test it- if (!slices.length) {- return cache[path] = this._testOne(path, checkUnignored)- }-- const parent = this._t(- slices.join(SLASH) + SLASH,- cache,- checkUnignored,- slices- );-- // If the path contains a parent directory, check the parent first- return cache[path] = parent.ignored- // > It is not possible to re-include a file if a parent directory of- // > that file is excluded.- ? parent- : this._testOne(path, checkUnignored)- }-- ignores (path) {- return this._test(path, this._ignoreCache, false).ignored- }-- createFilter () {- return path => !this.ignores(path)- }-- filter (paths) {- return makeArray(paths).filter(this.createFilter())- }-- // @returns {TestResult}- test (path) {- return this._test(path, this._testCache, true)- }-}--const factory = options => new Ignore(options);--const returnFalse = () => false;--const isPathValid = path =>- checkPath$1(path && checkPath$1.convert(path), path, returnFalse);--factory.isPathValid = isPathValid;--// Fixes typescript-factory.default = factory;--var ignore = factory;--// Windows-// ---------------------------------------------------------------/* istanbul ignore if */-if (- // Detect `process` so that it can run in browsers.- typeof process !== 'undefined'- && (- process.env && process.env.IGNORE_TEST_WIN32- || process.platform === 'win32'- )-) {- /* eslint no-control-regex: "off" */- const makePosix = str => /^\\\\\?\\/.test(str)- || /["<>|\u0000-\u001F]+/u.test(str)- ? str- : str.replace(/\\/g, '/');-- checkPath$1.convert = makePosix;-- // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'- // 'd:\\foo'- const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;- checkPath$1.isNotRelative = path =>- REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path)- || isNotRelative(path);-}--var slash$1 = path => {- const isExtendedLengthPath = /^\\\\\?\\/.test(path);- const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex-- if (isExtendedLengthPath || hasNonAscii) {- return path;- }-- return path.replace(/\\/g, '/');-};--const {promisify: promisify$1} = util;-------const DEFAULT_IGNORE = [- '**/node_modules/**',- '**/flow-typed/**',- '**/coverage/**',- '**/.git'-];--const readFileP = promisify$1(fs$2__default.readFile);--const mapGitIgnorePatternTo = base => ignore => {- if (ignore.startsWith('!')) {- return '!' + path__default.posix.join(base, ignore.slice(1));- }-- return path__default.posix.join(base, ignore);-};--const parseGitIgnore = (content, options) => {- const base = slash$1(path__default.relative(options.cwd, path__default.dirname(options.fileName)));-- return content- .split(/\r?\n/)- .filter(Boolean)- .filter(line => !line.startsWith('#'))- .map(mapGitIgnorePatternTo(base));-};--const reduceIgnore = files => {- return files.reduce((ignores, file) => {- ignores.add(parseGitIgnore(file.content, {- cwd: file.cwd,- fileName: file.filePath- }));- return ignores;- }, ignore());-};--const ensureAbsolutePathForCwd = (cwd, p) => {- cwd = slash$1(cwd);- if (path__default.isAbsolute(p)) {- if (p.startsWith(cwd)) {- return p;- }-- throw new Error(`Path ${p} is not in cwd ${cwd}`);- }-- return path__default.join(cwd, p);-};--const getIsIgnoredPredecate = (ignores, cwd) => {- return p => ignores.ignores(slash$1(path__default.relative(cwd, ensureAbsolutePathForCwd(cwd, p))));-};--const getFile = async (file, cwd) => {- const filePath = path__default.join(cwd, file);- const content = await readFileP(filePath, 'utf8');-- return {- cwd,- filePath,- content- };-};--const getFileSync = (file, cwd) => {- const filePath = path__default.join(cwd, file);- const content = fs$2__default.readFileSync(filePath, 'utf8');-- return {- cwd,- filePath,- content- };-};--const normalizeOptions = ({- ignore = [],- cwd = slash$1(process.cwd())-} = {}) => {- return {ignore, cwd};-};--var gitignore = async options => {- options = normalizeOptions(options);-- const paths = await out$3('**/.gitignore', {- ignore: DEFAULT_IGNORE.concat(options.ignore),- cwd: options.cwd- });-- const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));- const ignores = reduceIgnore(files);-- return getIsIgnoredPredecate(ignores, options.cwd);-};--var sync$7 = options => {- options = normalizeOptions(options);-- const paths = out$3.sync('**/.gitignore', {- ignore: DEFAULT_IGNORE.concat(options.ignore),- cwd: options.cwd- });-- const files = paths.map(file => getFileSync(file, options.cwd));- const ignores = reduceIgnore(files);-- return getIsIgnoredPredecate(ignores, options.cwd);-};-gitignore.sync = sync$7;--const {Transform} = Stream$2;--class ObjectTransform extends Transform {- constructor() {- super({- objectMode: true- });- }-}--class FilterStream extends ObjectTransform {- constructor(filter) {- super();- this._filter = filter;- }-- _transform(data, encoding, callback) {- if (this._filter(data)) {- this.push(data);- }-- callback();- }-}--class UniqueStream extends ObjectTransform {- constructor() {- super();- this._pushed = new Set();- }-- _transform(data, encoding, callback) {- if (!this._pushed.has(data)) {- this.push(data);- this._pushed.add(data);- }-- callback();- }-}--var streamUtils = {- FilterStream,- UniqueStream-};--const {FilterStream: FilterStream$1, UniqueStream: UniqueStream$1} = streamUtils;--const DEFAULT_FILTER = () => false;--const isNegative = pattern => pattern[0] === '!';--const assertPatternsInput$1 = patterns => {- if (!patterns.every(pattern => typeof pattern === 'string')) {- throw new TypeError('Patterns must be a string or an array of strings');- }-};--const checkCwdOption = (options = {}) => {- if (!options.cwd) {- return;- }-- let stat;- try {- stat = fs$2__default.statSync(options.cwd);- } catch (_) {- return;- }-- if (!stat.isDirectory()) {- throw new Error('The `cwd` option must be a path to a directory');- }-};--const getPathString = p => p.stats instanceof fs$2__default.Stats ? p.path : p;--const generateGlobTasks = (patterns, taskOptions) => {- patterns = arrayUnion([].concat(patterns));- assertPatternsInput$1(patterns);- checkCwdOption(taskOptions);-- const globTasks = [];-- taskOptions = {- ignore: [],- expandDirectories: true,- ...taskOptions- };-- for (const [index, pattern] of patterns.entries()) {- if (isNegative(pattern)) {- continue;- }-- const ignore = patterns- .slice(index)- .filter(isNegative)- .map(pattern => pattern.slice(1));-- const options = {- ...taskOptions,- ignore: taskOptions.ignore.concat(ignore)- };-- globTasks.push({pattern, options});- }-- return globTasks;-};--const globDirs = (task, fn) => {- let options = {};- if (task.options.cwd) {- options.cwd = task.options.cwd;- }-- if (Array.isArray(task.options.expandDirectories)) {- options = {- ...options,- files: task.options.expandDirectories- };- } else if (typeof task.options.expandDirectories === 'object') {- options = {- ...options,- ...task.options.expandDirectories- };- }-- return fn(task.pattern, options);-};--const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];--const getFilterSync = options => {- return options && options.gitignore ?- gitignore.sync({cwd: options.cwd, ignore: options.ignore}) :- DEFAULT_FILTER;-};--const globToTask = task => glob => {- const {options} = task;- if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {- options.ignore = dirGlob.sync(options.ignore);- }-- return {- pattern: glob,- options- };-};--var globby$1 = async (patterns, options) => {- const globTasks = generateGlobTasks(patterns, options);-- const getFilter = async () => {- return options && options.gitignore ?- gitignore({cwd: options.cwd, ignore: options.ignore}) :- DEFAULT_FILTER;- };-- const getTasks = async () => {- const tasks = await Promise.all(globTasks.map(async task => {- const globs = await getPattern(task, dirGlob);- return Promise.all(globs.map(globToTask(task)));- }));-- return arrayUnion(...tasks);- };-- const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);- const paths = await Promise.all(tasks.map(task => out$3(task.pattern, task.options)));-- return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));-};--var sync$8 = (patterns, options) => {- const globTasks = generateGlobTasks(patterns, options);-- const tasks = globTasks.reduce((tasks, task) => {- const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));- return tasks.concat(newTask);- }, []);-- const filter = getFilterSync(options);-- return tasks.reduce(- (matches, task) => arrayUnion(matches, out$3.sync(task.pattern, task.options)),- []- ).filter(path_ => !filter(path_));-};--var stream$4 = (patterns, options) => {- const globTasks = generateGlobTasks(patterns, options);-- const tasks = globTasks.reduce((tasks, task) => {- const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));- return tasks.concat(newTask);- }, []);-- const filter = getFilterSync(options);- const filterStream = new FilterStream$1(p => !filter(p));- const uniqueStream = new UniqueStream$1();-- return merge2_1(tasks.map(task => out$3.stream(task.pattern, task.options)))- .pipe(filterStream)- .pipe(uniqueStream);-};--var generateGlobTasks_1 = generateGlobTasks;--var hasMagic = (patterns, options) => []- .concat(patterns)- .some(pattern => out$3.isDynamicPattern(pattern, options));--var gitignore_1 = gitignore;-globby$1.sync = sync$8;-globby$1.stream = stream$4;-globby$1.generateGlobTasks = generateGlobTasks_1;-globby$1.hasMagic = hasMagic;-globby$1.gitignore = gitignore_1;--/*- * fn: The function to decorate with the logger- * logger: an object instance of type Logger- * hint: an optional hint to add to the error's message- */-function decorateWithLogger(fn, logger, hint) {- const resolver = fn != null ? fn : defaultFieldResolver;- const logError = (e) => {- // TODO: clone the error properly- const newE = new Error();- newE.stack = e.stack;- /* istanbul ignore else: always get the hint from addErrorLoggingToSchema */- if (hint) {- newE['originalMessage'] = e.message;- newE.message = `Error in resolver ${hint}\n${e.message}`;- }- logger.log(newE);- };- return (root, args, ctx, info) => {- try {- const result = resolver(root, args, ctx, info);- // If the resolver returns a Promise log any Promise rejects.- if (result && typeof result.then === 'function' && typeof result.catch === 'function') {- result.catch((reason) => {- // make sure that it's an error we're logging.- const error = reason instanceof Error ? reason : new Error(reason);- logError(error);- // We don't want to leave an unhandled exception so pass on error.- return reason;- });- }- return result;- }- catch (e) {- logError(e);- // we want to pass on the error, just in case.- throw e;- }- };-}--// If we have any union or interface types throw if no there is no resolveType or isTypeOf resolvers-function checkForResolveTypeResolver(schema, requireResolversForResolveType) {- Object.keys(schema.getTypeMap())- .map(typeName => schema.getType(typeName))- .forEach((type) => {- if (!isAbstractType(type)) {- return;- }- if (!type.resolveType) {- if (!requireResolversForResolveType) {- return;- }- throw new Error(`Type "${type.name}" is missing a "__resolveType" resolver. Pass false into ` +- '"resolverValidationOptions.requireResolversForResolveType" to disable this error.');- }- });-}--function extendResolversFromInterfaces(schema, resolvers) {- const typeNames = Object.keys({- ...schema.getTypeMap(),- ...resolvers,- });- const extendedResolvers = {};- typeNames.forEach(typeName => {- const type = schema.getType(typeName);- if ('getInterfaces' in type) {- const allInterfaceResolvers = type- .getInterfaces()- .map(iFace => resolvers[iFace.name])- .filter(interfaceResolvers => interfaceResolvers != null);- extendedResolvers[typeName] = {};- allInterfaceResolvers.forEach(interfaceResolvers => {- Object.keys(interfaceResolvers).forEach(fieldName => {- if (fieldName === '__isTypeOf' || !fieldName.startsWith('__')) {- extendedResolvers[typeName][fieldName] = interfaceResolvers[fieldName];- }- });- });- const typeResolvers = resolvers[typeName];- extendedResolvers[typeName] = {- ...extendedResolvers[typeName],- ...typeResolvers,- };- }- else {- const typeResolvers = resolvers[typeName];- if (typeResolvers != null) {- extendedResolvers[typeName] = typeResolvers;- }- }- });- return extendedResolvers;-}--function addResolversToSchema(schemaOrOptions, legacyInputResolvers, legacyInputValidationOptions) {- const options = isSchema(schemaOrOptions)- ? {- schema: schemaOrOptions,- resolvers: legacyInputResolvers,- resolverValidationOptions: legacyInputValidationOptions,- }- : schemaOrOptions;- let { schema, resolvers: inputResolvers, defaultFieldResolver, resolverValidationOptions = {}, inheritResolversFromInterfaces = false, updateResolversInPlace = false, } = options;- const { allowResolversNotInSchema = false, requireResolversForResolveType } = resolverValidationOptions;- const resolvers = inheritResolversFromInterfaces- ? extendResolversFromInterfaces(schema, inputResolvers)- : inputResolvers;- Object.keys(resolvers).forEach(typeName => {- const resolverValue = resolvers[typeName];- const resolverType = typeof resolverValue;- if (typeName === '__schema') {- if (resolverType !== 'function') {- throw new Error(`"${typeName}" defined in resolvers, but has invalid value "${resolverValue}". A schema resolver's value must be of type object or function.`);- }- }- else {- if (resolverType !== 'object') {- throw new Error(`"${typeName}" defined in resolvers, but has invalid value "${resolverValue}". The resolver's value must be of type object.`);- }- const type = schema.getType(typeName);- if (type == null) {- if (allowResolversNotInSchema) {- return;- }- throw new Error(`"${typeName}" defined in resolvers, but not in schema`);- }- else if (isSpecifiedScalarType(type)) {- // allow -- without recommending -- overriding of specified scalar types- Object.keys(resolverValue).forEach(fieldName => {- if (fieldName.startsWith('__')) {- type[fieldName.substring(2)] = resolverValue[fieldName];- }- else {- type[fieldName] = resolverValue[fieldName];- }- });- }- else if (isEnumType(type)) {- const values = type.getValues();- Object.keys(resolverValue).forEach(fieldName => {- if (!fieldName.startsWith('__') &&- !values.some(value => value.name === fieldName) &&- !allowResolversNotInSchema) {- throw new Error(`${type.name}.${fieldName} was defined in resolvers, but not present within ${type.name}`);- }- });- }- else if (isUnionType(type)) {- Object.keys(resolverValue).forEach(fieldName => {- if (!fieldName.startsWith('__') && !allowResolversNotInSchema) {- throw new Error(`${type.name}.${fieldName} was defined in resolvers, but ${type.name} is not an object or interface type`);- }- });- }- else if (isObjectType(type) || isInterfaceType(type)) {- Object.keys(resolverValue).forEach(fieldName => {- if (!fieldName.startsWith('__')) {- const fields = type.getFields();- const field = fields[fieldName];- if (field == null && !allowResolversNotInSchema) {- throw new Error(`${typeName}.${fieldName} defined in resolvers, but not in schema`);- }- const fieldResolve = resolverValue[fieldName];- if (typeof fieldResolve !== 'function' && typeof fieldResolve !== 'object') {- throw new Error(`Resolver ${typeName}.${fieldName} must be object or function`);- }- }- });- }- }- });- schema = updateResolversInPlace- ? addResolversToExistingSchema(schema, resolvers, defaultFieldResolver)- : createNewSchemaWithResolvers(schema, resolvers, defaultFieldResolver);- checkForResolveTypeResolver(schema, requireResolversForResolveType);- return schema;-}-function addResolversToExistingSchema(schema, resolvers, defaultFieldResolver) {- const typeMap = schema.getTypeMap();- Object.keys(resolvers).forEach(typeName => {- if (typeName !== '__schema') {- const type = schema.getType(typeName);- const resolverValue = resolvers[typeName];- if (isScalarType(type)) {- Object.keys(resolverValue).forEach(fieldName => {- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;- if (fieldName.startsWith('__')) {- type[fieldName.substring(2)] = resolverValue[fieldName];- }- else if (fieldName === 'astNode' && type.astNode != null) {- type.astNode = {- ...type.astNode,- description: (_c = (_b = (_a = resolverValue) === null || _a === void 0 ? void 0 : _a.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : type.astNode.description,- directives: ((_d = type.astNode.directives) !== null && _d !== void 0 ? _d : []).concat((_g = (_f = (_e = resolverValue) === null || _e === void 0 ? void 0 : _e.astNode) === null || _f === void 0 ? void 0 : _f.directives) !== null && _g !== void 0 ? _g : []),- };- }- else if (fieldName === 'extensionASTNodes' && type.extensionASTNodes != null) {- type.extensionASTNodes = ((_h = []) !== null && _h !== void 0 ? _h : type.extensionASTNodes).concat((_k = (_j = resolverValue) === null || _j === void 0 ? void 0 : _j.extensionASTNodes) !== null && _k !== void 0 ? _k : []);- }- else if (fieldName === 'extensions' &&- type.extensions != null &&- resolverValue.extensions != null) {- type.extensions = Object.assign({}, type.extensions, resolverValue.extensions);- }- else {- type[fieldName] = resolverValue[fieldName];- }- });- }- else if (isEnumType(type)) {- const config = type.toConfig();- const enumValueConfigMap = config.values;- Object.keys(resolverValue).forEach(fieldName => {- var _a, _b, _c, _d, _e, _f, _g, _h, _j;- if (fieldName.startsWith('__')) {- config[fieldName.substring(2)] = resolverValue[fieldName];- }- else if (fieldName === 'astNode' && config.astNode != null) {- config.astNode = {- ...config.astNode,- description: (_c = (_b = (_a = resolverValue) === null || _a === void 0 ? void 0 : _a.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : config.astNode.description,- directives: ((_d = config.astNode.directives) !== null && _d !== void 0 ? _d : []).concat((_g = (_f = (_e = resolverValue) === null || _e === void 0 ? void 0 : _e.astNode) === null || _f === void 0 ? void 0 : _f.directives) !== null && _g !== void 0 ? _g : []),- };- }- else if (fieldName === 'extensionASTNodes' && config.extensionASTNodes != null) {- config.extensionASTNodes = config.extensionASTNodes.concat((_j = (_h = resolverValue) === null || _h === void 0 ? void 0 : _h.extensionASTNodes) !== null && _j !== void 0 ? _j : []);- }- else if (fieldName === 'extensions' &&- type.extensions != null &&- resolverValue.extensions != null) {- type.extensions = Object.assign({}, type.extensions, resolverValue.extensions);- }- else if (enumValueConfigMap[fieldName]) {- enumValueConfigMap[fieldName].value = resolverValue[fieldName];- }- });- typeMap[typeName] = new GraphQLEnumType(config);- }- else if (isUnionType(type)) {- Object.keys(resolverValue).forEach(fieldName => {- if (fieldName.startsWith('__')) {- type[fieldName.substring(2)] = resolverValue[fieldName];- }- });- }- else if (isObjectType(type) || isInterfaceType(type)) {- Object.keys(resolverValue).forEach(fieldName => {- if (fieldName.startsWith('__')) {- // this is for isTypeOf and resolveType and all the other stuff.- type[fieldName.substring(2)] = resolverValue[fieldName];- return;- }- const fields = type.getFields();- const field = fields[fieldName];- if (field != null) {- const fieldResolve = resolverValue[fieldName];- if (typeof fieldResolve === 'function') {- // for convenience. Allows shorter syntax in resolver definition file- field.resolve = fieldResolve;- }- else {- setFieldProperties(field, fieldResolve);- }- }- });- }- }- });- // serialize all default values prior to healing fields with new scalar/enum types.- forEachDefaultValue(schema, serializeInputValue);- // schema may have new scalar/enum types that require healing- healSchema(schema);- // reparse all default values with new parsing functions.- forEachDefaultValue(schema, parseInputValue);- if (defaultFieldResolver != null) {- forEachField(schema, field => {- if (!field.resolve) {- field.resolve = defaultFieldResolver;- }- });- }- return schema;-}-function createNewSchemaWithResolvers(schema, resolvers, defaultFieldResolver) {- schema = mapSchema(schema, {- [MapperKind.SCALAR_TYPE]: type => {- const config = type.toConfig();- const resolverValue = resolvers[type.name];- if (!isSpecifiedScalarType(type) && resolverValue != null) {- Object.keys(resolverValue).forEach(fieldName => {- var _a, _b, _c, _d, _e, _f, _g, _h, _j;- if (fieldName.startsWith('__')) {- config[fieldName.substring(2)] = resolverValue[fieldName];- }- else if (fieldName === 'astNode' && config.astNode != null) {- config.astNode = {- ...config.astNode,- description: (_c = (_b = (_a = resolverValue) === null || _a === void 0 ? void 0 : _a.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : config.astNode.description,- directives: ((_d = config.astNode.directives) !== null && _d !== void 0 ? _d : []).concat((_g = (_f = (_e = resolverValue) === null || _e === void 0 ? void 0 : _e.astNode) === null || _f === void 0 ? void 0 : _f.directives) !== null && _g !== void 0 ? _g : []),- };- }- else if (fieldName === 'extensionASTNodes' && config.extensionASTNodes != null) {- config.extensionASTNodes = config.extensionASTNodes.concat((_j = (_h = resolverValue) === null || _h === void 0 ? void 0 : _h.extensionASTNodes) !== null && _j !== void 0 ? _j : []);- }- else if (fieldName === 'extensions' &&- config.extensions != null &&- resolverValue.extensions != null) {- config.extensions = Object.assign({}, type.extensions, resolverValue.extensions);- }- else {- config[fieldName] = resolverValue[fieldName];- }- });- return new GraphQLScalarType(config);- }- },- [MapperKind.ENUM_TYPE]: type => {- const resolverValue = resolvers[type.name];- const config = type.toConfig();- const enumValueConfigMap = config.values;- if (resolverValue != null) {- Object.keys(resolverValue).forEach(fieldName => {- var _a, _b, _c, _d, _e, _f, _g, _h, _j;- if (fieldName.startsWith('__')) {- config[fieldName.substring(2)] = resolverValue[fieldName];- }- else if (fieldName === 'astNode' && config.astNode != null) {- config.astNode = {- ...config.astNode,- description: (_c = (_b = (_a = resolverValue) === null || _a === void 0 ? void 0 : _a.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : config.astNode.description,- directives: ((_d = config.astNode.directives) !== null && _d !== void 0 ? _d : []).concat((_g = (_f = (_e = resolverValue) === null || _e === void 0 ? void 0 : _e.astNode) === null || _f === void 0 ? void 0 : _f.directives) !== null && _g !== void 0 ? _g : []),- };- }- else if (fieldName === 'extensionASTNodes' && config.extensionASTNodes != null) {- config.extensionASTNodes = config.extensionASTNodes.concat((_j = (_h = resolverValue) === null || _h === void 0 ? void 0 : _h.extensionASTNodes) !== null && _j !== void 0 ? _j : []);- }- else if (fieldName === 'extensions' &&- config.extensions != null &&- resolverValue.extensions != null) {- config.extensions = Object.assign({}, type.extensions, resolverValue.extensions);- }- else if (enumValueConfigMap[fieldName]) {- enumValueConfigMap[fieldName].value = resolverValue[fieldName];- }- });- return new GraphQLEnumType(config);- }- },- [MapperKind.UNION_TYPE]: type => {- const resolverValue = resolvers[type.name];- if (resolverValue != null) {- const config = type.toConfig();- Object.keys(resolverValue).forEach(fieldName => {- if (fieldName.startsWith('__')) {- config[fieldName.substring(2)] = resolverValue[fieldName];- }- });- return new GraphQLUnionType(config);- }- },- [MapperKind.OBJECT_TYPE]: type => {- const resolverValue = resolvers[type.name];- if (resolverValue != null) {- const config = type.toConfig();- Object.keys(resolverValue).forEach(fieldName => {- if (fieldName.startsWith('__')) {- config[fieldName.substring(2)] = resolverValue[fieldName];- }- });- return new GraphQLObjectType(config);- }- },- [MapperKind.INTERFACE_TYPE]: type => {- const resolverValue = resolvers[type.name];- if (resolverValue != null) {- const config = type.toConfig();- Object.keys(resolverValue).forEach(fieldName => {- if (fieldName.startsWith('__')) {- config[fieldName.substring(2)] = resolverValue[fieldName];- }- });- return new GraphQLInterfaceType(config);- }- },- [MapperKind.COMPOSITE_FIELD]: (fieldConfig, fieldName, typeName) => {- const resolverValue = resolvers[typeName];- if (resolverValue != null) {- const fieldResolve = resolverValue[fieldName];- if (fieldResolve != null) {- const newFieldConfig = { ...fieldConfig };- if (typeof fieldResolve === 'function') {- // for convenience. Allows shorter syntax in resolver definition file- newFieldConfig.resolve = fieldResolve;- }- else {- setFieldProperties(newFieldConfig, fieldResolve);- }- return newFieldConfig;- }- }- },- });- if (defaultFieldResolver != null) {- schema = mapSchema(schema, {- [MapperKind.OBJECT_FIELD]: fieldConfig => ({- ...fieldConfig,- resolve: fieldConfig.resolve != null ? fieldConfig.resolve : defaultFieldResolver,- }),- });- }- return schema;-}-function setFieldProperties(field, propertiesObj) {- Object.keys(propertiesObj).forEach(propertyName => {- field[propertyName] = propertiesObj[propertyName];- });-}--function addErrorLoggingToSchema(schema, logger) {- if (!logger) {- throw new Error('Must provide a logger');- }- if (typeof logger.log !== 'function') {- throw new Error('Logger.log must be a function');- }- return mapSchema(schema, {- [MapperKind.OBJECT_FIELD]: (fieldConfig, fieldName, typeName) => ({- ...fieldConfig,- resolve: decorateWithLogger(fieldConfig.resolve, logger, `${typeName}.${fieldName}`),- }),- });-}--/**- * Deep merges multiple resolver definition objects into a single definition.- * @param resolversDefinitions Resolver definitions to be merged- * @param options Additional options- *- * ```js- * const { mergeResolvers } = require('@graphql-tools/merge');- * const clientResolver = require('./clientResolver');- * const productResolver = require('./productResolver');- *- * const resolvers = mergeResolvers([- * clientResolver,- * productResolver,- * ]);- * ```- *- * If you don't want to manually create the array of resolver objects, you can- * also use this function along with loadFiles:- *- * ```js- * const path = require('path');- * const { mergeResolvers } = require('@graphql-tools/merge');- * const { loadFilesSync } = require('@graphql-tools/load-files');- *- * const resolversArray = loadFilesSync(path.join(__dirname, './resolvers'));- *- * const resolvers = mergeResolvers(resolversArray)- * ```- */-function mergeResolvers(resolversDefinitions, options) {- if (!resolversDefinitions || resolversDefinitions.length === 0) {- return {};- }- if (resolversDefinitions.length === 1) {- const singleDefinition = resolversDefinitions[0];- if (Array.isArray(singleDefinition)) {- return mergeResolvers(singleDefinition);- }- return singleDefinition;- }- const resolversFactories = new Array();- const resolvers = new Array();- for (let resolversDefinition of resolversDefinitions) {- if (Array.isArray(resolversDefinition)) {- resolversDefinition = mergeResolvers(resolversDefinition);- }- if (typeof resolversDefinition === 'function') {- resolversFactories.push(resolversDefinition);- }- else if (typeof resolversDefinition === 'object') {- resolvers.push(resolversDefinition);- }- }- let result = {};- if (resolversFactories.length) {- result = ((...args) => {- const resultsOfFactories = resolversFactories.map(factory => factory(...args));- return resolvers.concat(resultsOfFactories).reduce(mergeDeep, {});- });- }- else {- result = resolvers.reduce(mergeDeep, {});- }- if (options && options.exclusions) {- for (const exclusion of options.exclusions) {- const [typeName, fieldName] = exclusion.split('.');- if (!fieldName || fieldName === '*') {- delete result[typeName];- }- else if (result[typeName]) {- delete result[typeName][fieldName];- }- }- }- return result;-}--function mergeArguments$2(args1, args2, config) {- const result = deduplicateArguments$1([].concat(args2, args1).filter(a => a));- if (config && config.sort) {- result.sort(compareNodes);- }- return result;-}-function deduplicateArguments$1(args) {- return args.reduce((acc, current) => {- const dup = acc.find(arg => arg.name.value === current.name.value);- if (!dup) {- return acc.concat([current]);- }- return acc;- }, []);-}--let commentsRegistry$1 = {};-function resetComments$1() {- commentsRegistry$1 = {};-}-function collectComment$1(node) {- const entityName = node.name.value;- pushComment$1(node, entityName);- switch (node.kind) {- case 'EnumTypeDefinition':- node.values.forEach(value => {- pushComment$1(value, entityName, value.name.value);- });- break;- case 'ObjectTypeDefinition':- case 'InputObjectTypeDefinition':- case 'InterfaceTypeDefinition':- if (node.fields) {- node.fields.forEach((field) => {- pushComment$1(field, entityName, field.name.value);- if (isFieldDefinitionNode$1(field) && field.arguments) {- field.arguments.forEach(arg => {- pushComment$1(arg, entityName, field.name.value, arg.name.value);- });- }- });- }- break;- }-}-function pushComment$1(node, entity, field, argument) {- const comment = getDescription(node, { commentDescriptions: true });- if (typeof comment !== 'string' || comment.length === 0) {- return;- }- const keys = [entity];- if (field) {- keys.push(field);- if (argument) {- keys.push(argument);- }- }- const path = keys.join('.');- if (!commentsRegistry$1[path]) {- commentsRegistry$1[path] = [];- }- commentsRegistry$1[path].push(comment);-}-function printComment$1(comment) {- return '\n# ' + comment.replace(/\n/g, '\n# ');-}-/**- * 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.- */-/**- * NOTE: ==> This file has been modified just to add comments to the printed AST- * This is a temp measure, we will move to using the original non modified printer.js ASAP.- */-// import { visit, VisitFn } from 'graphql/language/visitor';-/**- * Given maybeArray, print an empty string if it is null or empty, otherwise- * print all items together separated by separator if provided- */-function join$2(maybeArray, separator) {- return maybeArray ? maybeArray.filter(x => x).join(separator || '') : '';-}-function addDescription$2(cb) {- return (node, _key, _parent, path, ancestors) => {- const keys = [];- const parent = path.reduce((prev, key) => {- if (['fields', 'arguments', 'values'].includes(key)) {- keys.push(prev.name.value);- }- return prev[key];- }, ancestors[0]);- const key = [...keys, parent.name.value].join('.');- const items = [];- if (commentsRegistry$1[key]) {- items.push(...commentsRegistry$1[key]);- }- return join$2([...items.map(printComment$1), node.description, cb(node)], '\n');- };-}-function indent$2(maybeString) {- return maybeString && ` ${maybeString.replace(/\n/g, '\n ')}`;-}-/**- * Given array, print each item on its own line, wrapped in an- * indented "{ }" block.- */-function block$2(array) {- return array && array.length !== 0 ? `{\n${indent$2(join$2(array, '\n'))}\n}` : '';-}-/**- * If maybeString is not null or empty, then wrap with start and end, otherwise- * print an empty string.- */-function wrap$2(start, maybeString, end) {- return maybeString ? start + maybeString + (end || '') : '';-}-/**- * 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$2(value, isDescription) {- const escaped = value.replace(/"""/g, '\\"""');- return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1- ? `"""${escaped.replace(/"$/, '"\n')}"""`- : `"""\n${isDescription ? escaped : indent$2(escaped)}\n"""`;-}-/**- * Converts an AST into a string, using one set of reasonable- * formatting rules.- */-function printWithComments$1(ast) {- return visit(ast, {- leave: {- Name: node => node.value,- Variable: node => `$${node.name}`,- // Document- Document: node => `${node.definitions- .map(defNode => `${defNode}\n${defNode[0] === '#' ? '' : '\n'}`)- .join('')- .trim()}\n`,- OperationTypeDefinition: node => `${node.operation}: ${node.type}`,- VariableDefinition: ({ variable, type, defaultValue }) => `${variable}: ${type}${wrap$2(' = ', defaultValue)}`,- SelectionSet: ({ selections }) => block$2(selections),- Field: ({ alias, name, arguments: args, directives, selectionSet }) => join$2([wrap$2('', alias, ': ') + name + wrap$2('(', join$2(args, ', '), ')'), join$2(directives, ' '), selectionSet], ' '),- Argument: addDescription$2(({ name, value }) => `${name}: ${value}`),- // Value- IntValue: ({ value }) => value,- FloatValue: ({ value }) => value,- StringValue: ({ value, block: isBlockString }, key) => isBlockString ? printBlockString$2(value, key === 'description') : JSON.stringify(value),- BooleanValue: ({ value }) => (value ? 'true' : 'false'),- NullValue: () => 'null',- EnumValue: ({ value }) => value,- ListValue: ({ values }) => `[${join$2(values, ', ')}]`,- ObjectValue: ({ fields }) => `{${join$2(fields, ', ')}}`,- ObjectField: ({ name, value }) => `${name}: ${value}`,- // Directive- Directive: ({ name, arguments: args }) => `@${name}${wrap$2('(', join$2(args, ', '), ')')}`,- // Type- NamedType: ({ name }) => name,- ListType: ({ type }) => `[${type}]`,- NonNullType: ({ type }) => `${type}!`,- // Type System Definitions- SchemaDefinition: ({ directives, operationTypes }) => join$2(['schema', join$2(directives, ' '), block$2(operationTypes)], ' '),- ScalarTypeDefinition: addDescription$2(({ name, directives }) => join$2(['scalar', name, join$2(directives, ' ')], ' ')),- ObjectTypeDefinition: addDescription$2(({ name, interfaces, directives, fields }) => join$2(['type', name, wrap$2('implements ', join$2(interfaces, ' & ')), join$2(directives, ' '), block$2(fields)], ' ')),- FieldDefinition: addDescription$2(({ name, arguments: args, type, directives }) => `${name + wrap$2('(', join$2(args, ', '), ')')}: ${type}${wrap$2(' ', join$2(directives, ' '))}`),- InputValueDefinition: addDescription$2(({ name, type, defaultValue, directives }) => join$2([`${name}: ${type}`, wrap$2('= ', defaultValue), join$2(directives, ' ')], ' ')),- InterfaceTypeDefinition: addDescription$2(({ name, directives, fields }) => join$2(['interface', name, join$2(directives, ' '), block$2(fields)], ' ')),- UnionTypeDefinition: addDescription$2(({ name, directives, types }) => join$2(['union', name, join$2(directives, ' '), types && types.length !== 0 ? `= ${join$2(types, ' | ')}` : ''], ' ')),- EnumTypeDefinition: addDescription$2(({ name, directives, values }) => join$2(['enum', name, join$2(directives, ' '), block$2(values)], ' ')),- EnumValueDefinition: addDescription$2(({ name, directives }) => join$2([name, join$2(directives, ' ')], ' ')),- InputObjectTypeDefinition: addDescription$2(({ name, directives, fields }) => join$2(['input', name, join$2(directives, ' '), block$2(fields)], ' ')),- ScalarTypeExtension: ({ name, directives }) => join$2(['extend scalar', name, join$2(directives, ' ')], ' '),- ObjectTypeExtension: ({ name, interfaces, directives, fields }) => join$2(['extend type', name, wrap$2('implements ', join$2(interfaces, ' & ')), join$2(directives, ' '), block$2(fields)], ' '),- InterfaceTypeExtension: ({ name, directives, fields }) => join$2(['extend interface', name, join$2(directives, ' '), block$2(fields)], ' '),- UnionTypeExtension: ({ name, directives, types }) => join$2(['extend union', name, join$2(directives, ' '), types && types.length !== 0 ? `= ${join$2(types, ' | ')}` : ''], ' '),- EnumTypeExtension: ({ name, directives, values }) => join$2(['extend enum', name, join$2(directives, ' '), block$2(values)], ' '),- InputObjectTypeExtension: ({ name, directives, fields }) => join$2(['extend input', name, join$2(directives, ' '), block$2(fields)], ' '),- DirectiveDefinition: addDescription$2(({ name, arguments: args, locations }) => `directive @${name}${wrap$2('(', join$2(args, ', '), ')')} on ${join$2(locations, ' | ')}`),- },- });-}-function isFieldDefinitionNode$1(node) {- return node.kind === 'FieldDefinition';-}--function directiveAlreadyExists$1(directivesArr, otherDirective) {- return !!directivesArr.find(directive => directive.name.value === otherDirective.name.value);-}-function nameAlreadyExists$1(name, namesArr) {- return namesArr.some(({ value }) => value === name.value);-}-function mergeArguments$1$1(a1, a2) {- const result = [...a2];- for (const argument of a1) {- const existingIndex = result.findIndex(a => a.name.value === argument.name.value);- if (existingIndex > -1) {- const existingArg = result[existingIndex];- if (existingArg.value.kind === 'ListValue') {- const source = existingArg.value.values;- const target = argument.value.values;- // merge values of two lists- existingArg.value.values = deduplicateLists$1(source, target, (targetVal, source) => {- const value = targetVal.value;- return !value || !source.some((sourceVal) => sourceVal.value === value);- });- }- else {- existingArg.value = argument.value;- }- }- else {- result.push(argument);- }- }- return result;-}-function deduplicateDirectives$1(directives) {- return directives- .map((directive, i, all) => {- const firstAt = all.findIndex(d => d.name.value === directive.name.value);- if (firstAt !== i) {- const dup = all[firstAt];- directive.arguments = mergeArguments$1$1(directive.arguments, dup.arguments);- return null;- }- return directive;- })- .filter(d => d);-}-function mergeDirectives$1(d1 = [], d2 = [], config) {- const reverseOrder = config && config.reverseDirectives;- const asNext = reverseOrder ? d1 : d2;- const asFirst = reverseOrder ? d2 : d1;- const result = deduplicateDirectives$1([...asNext]);- for (const directive of asFirst) {- if (directiveAlreadyExists$1(result, directive)) {- const existingDirectiveIndex = result.findIndex(d => d.name.value === directive.name.value);- const existingDirective = result[existingDirectiveIndex];- result[existingDirectiveIndex].arguments = mergeArguments$1$1(directive.arguments || [], existingDirective.arguments || []);- }- else {- result.push(directive);- }- }- return result;-}-function validateInputs$1(node, existingNode) {- const printedNode = print(node);- const printedExistingNode = print(existingNode);- const leaveInputs = new RegExp('(directive @w*d*)|( on .*$)', 'g');- const sameArguments = printedNode.replace(leaveInputs, '') === printedExistingNode.replace(leaveInputs, '');- if (!sameArguments) {- throw new Error(`Unable to merge GraphQL directive "${node.name.value}". \nExisting directive: \n\t${printedExistingNode} \nReceived directive: \n\t${printedNode}`);- }-}-function mergeDirective$1(node, existingNode) {- if (existingNode) {- validateInputs$1(node, existingNode);- return {- ...node,- locations: [- ...existingNode.locations,- ...node.locations.filter(name => !nameAlreadyExists$1(name, existingNode.locations)),- ],- };- }- return node;-}-function deduplicateLists$1(source, target, filterFn) {- return source.concat(target.filter(val => filterFn(val, source)));-}--function mergeEnumValues$1(first, second, config) {- const enumValueMap = new Map();- for (const firstValue of first) {- enumValueMap.set(firstValue.name.value, firstValue);- }- for (const secondValue of second) {- const enumValue = secondValue.name.value;- if (enumValueMap.has(enumValue)) {- const firstValue = enumValueMap.get(enumValue);- firstValue.description = secondValue.description || firstValue.description;- firstValue.directives = mergeDirectives$1(secondValue.directives, firstValue.directives);- }- else {- enumValueMap.set(enumValue, secondValue);- }- }- const result = [...enumValueMap.values()];- if (config && config.sort) {- result.sort(compareNodes);- }- return result;-}--function mergeEnum$1(e1, e2, config) {- if (e2) {- return {- name: e1.name,- description: e1['description'] || e2['description'],- kind: (config && config.convertExtensions) || e1.kind === 'EnumTypeDefinition' || e2.kind === 'EnumTypeDefinition'- ? 'EnumTypeDefinition'- : 'EnumTypeExtension',- loc: e1.loc,- directives: mergeDirectives$1(e1.directives, e2.directives, config),- values: mergeEnumValues$1(e1.values, e2.values, config),- };- }- return config && config.convertExtensions- ? {- ...e1,- kind: 'EnumTypeDefinition',- }- : e1;-}--function isStringTypes$1(types) {- return typeof types === 'string';-}-function isSourceTypes$1(types) {- return types instanceof Source;-}-function isGraphQLType$1(definition) {- return definition.kind === 'ObjectTypeDefinition';-}-function isGraphQLTypeExtension$1(definition) {- return definition.kind === 'ObjectTypeExtension';-}-function isGraphQLEnum$1(definition) {- return definition.kind === 'EnumTypeDefinition';-}-function isGraphQLEnumExtension$1(definition) {- return definition.kind === 'EnumTypeExtension';-}-function isGraphQLUnion$1(definition) {- return definition.kind === 'UnionTypeDefinition';-}-function isGraphQLUnionExtension$1(definition) {- return definition.kind === 'UnionTypeExtension';-}-function isGraphQLScalar$1(definition) {- return definition.kind === 'ScalarTypeDefinition';-}-function isGraphQLScalarExtension$1(definition) {- return definition.kind === 'ScalarTypeExtension';-}-function isGraphQLInputType$1(definition) {- return definition.kind === 'InputObjectTypeDefinition';-}-function isGraphQLInputTypeExtension$1(definition) {- return definition.kind === 'InputObjectTypeExtension';-}-function isGraphQLInterface$1(definition) {- return definition.kind === 'InterfaceTypeDefinition';-}-function isGraphQLInterfaceExtension$1(definition) {- return definition.kind === 'InterfaceTypeExtension';-}-function isGraphQLDirective$1(definition) {- return definition.kind === 'DirectiveDefinition';-}-function extractType$1(type) {- let visitedType = type;- while (visitedType.kind === 'ListType' || visitedType.kind === 'NonNullType') {- visitedType = visitedType.type;- }- return visitedType;-}-function isSchemaDefinition$1(node) {- return node.kind === 'SchemaDefinition';-}-function isWrappingTypeNode$1(type) {- return type.kind !== Kind.NAMED_TYPE;-}-function isListTypeNode$1(type) {- return type.kind === Kind.LIST_TYPE;-}-function isNonNullTypeNode$1(type) {- return type.kind === Kind.NON_NULL_TYPE;-}-function printTypeNode$1(type) {- if (isListTypeNode$1(type)) {- return `[${printTypeNode$1(type.type)}]`;- }- if (isNonNullTypeNode$1(type)) {- return `${printTypeNode$1(type.type)}!`;- }- return type.name.value;-}--function fieldAlreadyExists$1(fieldsArr, otherField) {- const result = fieldsArr.find(field => field.name.value === otherField.name.value);- if (result) {- const t1 = extractType$1(result.type);- const t2 = extractType$1(otherField.type);- if (t1.name.value !== t2.name.value) {- throw new Error(`Field "${otherField.name.value}" already defined with a different type. Declared as "${t1.name.value}", but you tried to override with "${t2.name.value}"`);- }- }- return !!result;-}-function mergeFields$1(type, f1, f2, config) {- const result = [...f2];- for (const field of f1) {- if (fieldAlreadyExists$1(result, field)) {- const existing = result.find((f) => f.name.value === field.name.value);- if (config && config.throwOnConflict) {- preventConflicts$1(type, existing, field, false);- }- else {- preventConflicts$1(type, existing, field, true);- }- if (isNonNullTypeNode$1(field.type) && !isNonNullTypeNode$1(existing.type)) {- existing.type = field.type;- }- existing.arguments = mergeArguments$2(field['arguments'] || [], existing.arguments || [], config);- existing.directives = mergeDirectives$1(field.directives, existing.directives, config);- existing.description = field.description || existing.description;- }- else {- result.push(field);- }- }- if (config && config.sort) {- result.sort(compareNodes);- }- if (config && config.exclusions) {- return result.filter(field => !config.exclusions.includes(`${type.name.value}.${field.name.value}`));- }- return result;-}-function preventConflicts$1(type, a, b, ignoreNullability = false) {- const aType = printTypeNode$1(a.type);- const bType = printTypeNode$1(b.type);- if (isNotEqual(aType, bType)) {- if (safeChangeForFieldType$1(a.type, b.type, ignoreNullability) === false) {- throw new Error(`Field '${type.name.value}.${a.name.value}' changed type from '${aType}' to '${bType}'`);- }- }-}-function safeChangeForFieldType$1(oldType, newType, ignoreNullability = false) {- // both are named- if (!isWrappingTypeNode$1(oldType) && !isWrappingTypeNode$1(newType)) {- return oldType.toString() === newType.toString();- }- // new is non-null- if (isNonNullTypeNode$1(newType)) {- const ofType = isNonNullTypeNode$1(oldType) ? oldType.type : oldType;- return safeChangeForFieldType$1(ofType, newType.type);- }- // old is non-null- if (isNonNullTypeNode$1(oldType)) {- return safeChangeForFieldType$1(newType, oldType, ignoreNullability);- }- // old is list- if (isListTypeNode$1(oldType)) {- return ((isListTypeNode$1(newType) && safeChangeForFieldType$1(oldType.type, newType.type)) ||- (isNonNullTypeNode$1(newType) && safeChangeForFieldType$1(oldType, newType['type'])));- }- return false;-}--function mergeInputType$1(node, existingNode, config) {- if (existingNode) {- try {- return {- name: node.name,- description: node['description'] || existingNode['description'],- kind: (config && config.convertExtensions) ||- node.kind === 'InputObjectTypeDefinition' ||- existingNode.kind === 'InputObjectTypeDefinition'- ? 'InputObjectTypeDefinition'- : 'InputObjectTypeExtension',- loc: node.loc,- fields: mergeFields$1(node, node.fields, existingNode.fields, config),- directives: mergeDirectives$1(node.directives, existingNode.directives, config),- };- }- catch (e) {- throw new Error(`Unable to merge GraphQL input type "${node.name.value}": ${e.message}`);- }- }- return config && config.convertExtensions- ? {- ...node,- kind: 'InputObjectTypeDefinition',- }- : node;-}--function mergeInterface$1(node, existingNode, config) {- if (existingNode) {- try {- return {- name: node.name,- description: node['description'] || existingNode['description'],- kind: (config && config.convertExtensions) ||- node.kind === 'InterfaceTypeDefinition' ||- existingNode.kind === 'InterfaceTypeDefinition'- ? 'InterfaceTypeDefinition'- : 'InterfaceTypeExtension',- loc: node.loc,- fields: mergeFields$1(node, node.fields, existingNode.fields, config),- directives: mergeDirectives$1(node.directives, existingNode.directives, config),- };- }- catch (e) {- throw new Error(`Unable to merge GraphQL interface "${node.name.value}": ${e.message}`);- }- }- return config && config.convertExtensions- ? {- ...node,- kind: 'InterfaceTypeDefinition',- }- : node;-}--function alreadyExists$1(arr, other) {- return !!arr.find(i => i.name.value === other.name.value);-}-function mergeNamedTypeArray$1(first, second, config) {- const result = [...second, ...first.filter(d => !alreadyExists$1(second, d))];- if (config && config.sort) {- result.sort(compareNodes);- }- return result;-}--function mergeType$1(node, existingNode, config) {- if (existingNode) {- try {- return {- name: node.name,- description: node['description'] || existingNode['description'],- kind: (config && config.convertExtensions) ||- node.kind === 'ObjectTypeDefinition' ||- existingNode.kind === 'ObjectTypeDefinition'- ? 'ObjectTypeDefinition'- : 'ObjectTypeExtension',- loc: node.loc,- fields: mergeFields$1(node, node.fields, existingNode.fields, config),- directives: mergeDirectives$1(node.directives, existingNode.directives, config),- interfaces: mergeNamedTypeArray$1(node.interfaces, existingNode.interfaces, config),- };- }- catch (e) {- throw new Error(`Unable to merge GraphQL type "${node.name.value}": ${e.message}`);- }- }- return config && config.convertExtensions- ? {- ...node,- kind: 'ObjectTypeDefinition',- }- : node;-}--function mergeUnion$1(first, second, config) {- if (second) {- return {- name: first.name,- description: first['description'] || second['description'],- directives: mergeDirectives$1(first.directives, second.directives, config),- kind: (config && config.convertExtensions) ||- first.kind === 'UnionTypeDefinition' ||- second.kind === 'UnionTypeDefinition'- ? 'UnionTypeDefinition'- : 'UnionTypeExtension',- loc: first.loc,- types: mergeNamedTypeArray$1(first.types, second.types, config),- };- }- return config && config.convertExtensions- ? {- ...first,- kind: 'UnionTypeDefinition',- }- : first;-}--function mergeGraphQLNodes$1(nodes, config) {- return nodes.reduce((prev, nodeDefinition) => {- const node = nodeDefinition;- if (node && node.name && node.name.value) {- const name = node.name.value;- if (config && config.commentDescriptions) {- collectComment$1(node);- }- if (config &&- config.exclusions &&- (config.exclusions.includes(name + '.*') || config.exclusions.includes(name))) {- delete prev[name];- }- else if (isGraphQLType$1(nodeDefinition) || isGraphQLTypeExtension$1(nodeDefinition)) {- prev[name] = mergeType$1(nodeDefinition, prev[name], config);- }- else if (isGraphQLEnum$1(nodeDefinition) || isGraphQLEnumExtension$1(nodeDefinition)) {- prev[name] = mergeEnum$1(nodeDefinition, prev[name], config);- }- else if (isGraphQLUnion$1(nodeDefinition) || isGraphQLUnionExtension$1(nodeDefinition)) {- prev[name] = mergeUnion$1(nodeDefinition, prev[name], config);- }- else if (isGraphQLScalar$1(nodeDefinition) || isGraphQLScalarExtension$1(nodeDefinition)) {- prev[name] = nodeDefinition;- }- else if (isGraphQLInputType$1(nodeDefinition) || isGraphQLInputTypeExtension$1(nodeDefinition)) {- prev[name] = mergeInputType$1(nodeDefinition, prev[name], config);- }- else if (isGraphQLInterface$1(nodeDefinition) || isGraphQLInterfaceExtension$1(nodeDefinition)) {- prev[name] = mergeInterface$1(nodeDefinition, prev[name], config);- }- else if (isGraphQLDirective$1(nodeDefinition)) {- prev[name] = mergeDirective$1(nodeDefinition, prev[name]);- }- }- return prev;- }, {});-}--function mergeTypeDefs$1(types, config) {- resetComments$1();- const doc = {- kind: Kind.DOCUMENT,- definitions: mergeGraphQLTypes$1(types, {- useSchemaDefinition: true,- forceSchemaDefinition: false,- throwOnConflict: false,- commentDescriptions: false,- ...config,- }),- };- let result;- if (config && config.commentDescriptions) {- result = printWithComments$1(doc);- }- else {- result = doc;- }- resetComments$1();- return result;-}-function mergeGraphQLTypes$1(types, config) {- resetComments$1();- const allNodes = types- .map(type => {- if (Array.isArray(type)) {- type = mergeTypeDefs$1(type);- }- if (isSchema(type)) {- return parse(printSchemaWithDirectives(type));- }- else if (isStringTypes$1(type) || isSourceTypes$1(type)) {- return parse(type);- }- return type;- })- .map(ast => ast.definitions)- .reduce((defs, newDef = []) => [...defs, ...newDef], []);- // XXX: right now we don't handle multiple schema definitions- let schemaDef = allNodes.filter(isSchemaDefinition$1).reduce((def, node) => {- node.operationTypes- .filter(op => op.type.name.value)- .forEach(op => {- def[op.operation] = op.type.name.value;- });- return def;- }, {- query: null,- mutation: null,- subscription: null,- });- const mergedNodes = mergeGraphQLNodes$1(allNodes, config);- const allTypes = Object.keys(mergedNodes);- if (config && config.sort) {- allTypes.sort(typeof config.sort === 'function' ? config.sort : undefined);- }- if (config && config.useSchemaDefinition) {- const queryType = schemaDef.query ? schemaDef.query : allTypes.find(t => t === 'Query');- const mutationType = schemaDef.mutation ? schemaDef.mutation : allTypes.find(t => t === 'Mutation');- const subscriptionType = schemaDef.subscription ? schemaDef.subscription : allTypes.find(t => t === 'Subscription');- schemaDef = {- query: queryType,- mutation: mutationType,- subscription: subscriptionType,- };- }- const schemaDefinition = createSchemaDefinition(schemaDef, {- force: config.forceSchemaDefinition,- });- if (!schemaDefinition) {- return Object.values(mergedNodes);- }- return [...Object.values(mergedNodes), parse(schemaDefinition).definitions[0]];-}--function travelSchemaPossibleExtensions(schema, hooks) {- hooks.onSchema(schema);- const typesMap = schema.getTypeMap();- for (const [, type] of Object.entries(typesMap)) {- const isPredefinedScalar = isScalarType(type) && isSpecifiedScalarType(type);- const isIntrospection = isIntrospectionType(type);- if (isPredefinedScalar || isIntrospection) {- continue;- }- if (isObjectType(type)) {- hooks.onObjectType(type);- const fields = type.getFields();- for (const [, field] of Object.entries(fields)) {- hooks.onObjectField(type, field);- const args = field.args || [];- for (const arg of args) {- hooks.onObjectFieldArg(type, field, arg);- }- }- }- else if (isInterfaceType(type)) {- hooks.onInterface(type);- const fields = type.getFields();- for (const [, field] of Object.entries(fields)) {- hooks.onInterfaceField(type, field);- const args = field.args || [];- for (const arg of args) {- hooks.onInterfaceFieldArg(type, field, arg);- }- }- }- else if (isInputObjectType(type)) {- hooks.onInputType(type);- const fields = type.getFields();- for (const [, field] of Object.entries(fields)) {- hooks.onInputFieldType(type, field);- }- }- else if (isUnionType(type)) {- hooks.onUnion(type);- }- else if (isScalarType(type)) {- hooks.onScalar(type);- }- else if (isEnumType(type)) {- hooks.onEnum(type);- for (const value of type.getValues()) {- hooks.onEnumValue(type, value);- }- }- }-}-function mergeExtensions(extensions) {- return extensions.reduce((result, extensionObj) => [result, extensionObj].reduce(mergeDeep, {}), {});-}-function applyExtensionObject(obj, extensions) {- if (!obj) {- return;- }- obj.extensions = [obj.extensions || {}, extensions || {}].reduce(mergeDeep, {});-}-function applyExtensions(schema, extensions) {- applyExtensionObject(schema, extensions.schemaExtensions);- for (const [typeName, data] of Object.entries(extensions.types || {})) {- const type = schema.getType(typeName);- if (type) {- applyExtensionObject(type, data.extensions);- if (data.type === 'object' || data.type === 'interface') {- for (const [fieldName, fieldData] of Object.entries(data.fields)) {- const field = type.getFields()[fieldName];- if (field) {- applyExtensionObject(field, fieldData.extensions);- for (const [arg, argData] of Object.entries(fieldData.arguments)) {- applyExtensionObject(field.args.find(a => a.name === arg), argData);- }- }- }- }- else if (data.type === 'input') {- for (const [fieldName, fieldData] of Object.entries(data.fields)) {- const field = type.getFields()[fieldName];- applyExtensionObject(field, fieldData.extensions);- }- }- else if (data.type === 'enum') {- for (const [valueName, valueData] of Object.entries(data.values)) {- const value = type.getValue(valueName);- applyExtensionObject(value, valueData);- }- }- }- }- return schema;-}-function extractExtensionsFromSchema(schema) {- const result = {- schemaExtensions: {},- types: {},- };- travelSchemaPossibleExtensions(schema, {- onSchema: schema => (result.schemaExtensions = schema.extensions || {}),- onObjectType: type => (result.types[type.name] = { fields: {}, type: 'object', extensions: type.extensions || {} }),- onObjectField: (type, field) => (result.types[type.name].fields[field.name] = {- arguments: {},- extensions: field.extensions || {},- }),- onObjectFieldArg: (type, field, arg) => (result.types[type.name].fields[field.name].arguments[arg.name] = arg.extensions || {}),- onInterface: type => (result.types[type.name] = { fields: {}, type: 'interface', extensions: type.extensions || {} }),- onInterfaceField: (type, field) => (result.types[type.name].fields[field.name] = {- arguments: {},- extensions: field.extensions || {},- }),- onInterfaceFieldArg: (type, field, arg) => (result.types[type.name].fields[field.name].arguments[arg.name] =- arg.extensions || {}),- onEnum: type => (result.types[type.name] = { values: {}, type: 'enum', extensions: type.extensions || {} }),- onEnumValue: (type, value) => (result.types[type.name].values[value.name] = value.extensions || {}),- onScalar: type => (result.types[type.name] = { type: 'scalar', extensions: type.extensions || {} }),- onUnion: type => (result.types[type.name] = { type: 'union', extensions: type.extensions || {} }),- onInputType: type => (result.types[type.name] = { fields: {}, type: 'input', extensions: type.extensions || {} }),- onInputFieldType: (type, field) => (result.types[type.name].fields[field.name] = { extensions: field.extensions || {} }),- });- return result;-}--const defaultResolverValidationOptions = {- requireResolversForArgs: false,- requireResolversForNonScalar: false,- requireResolversForAllFields: false,- requireResolversForResolveType: false,- allowResolversNotInSchema: true,-};-/**- * Synchronously merges multiple schemas, typeDefinitions and/or resolvers into a single schema.- * @param config Configuration object- */-async function mergeSchemasAsync(config) {- const [typeDefs, resolvers, extensions] = await Promise.all([- mergeTypes(config),- Promise.all(config.schemas.map(async (schema) => getResolversFromSchema(schema))).then(extractedResolvers => mergeResolvers([...extractedResolvers, ...ensureResolvers(config)], config)),- Promise.all(config.schemas.map(async (schema) => extractExtensionsFromSchema(schema))).then(extractedExtensions => mergeExtensions(extractedExtensions)),- ]);- return makeSchema({ resolvers, typeDefs, extensions }, config);-}-function mergeTypes({ schemas, typeDefs, ...config }) {- return mergeTypeDefs$1([...schemas, ...(typeDefs ? asArray(typeDefs) : [])], config);-}-function ensureResolvers(config) {- return config.resolvers ? asArray(config.resolvers) : [];-}-function makeSchema({ resolvers, typeDefs, extensions, }, config) {- let schema = typeof typeDefs === 'string' ? buildSchema(typeDefs, config) : buildASTSchema(typeDefs, config);- // add resolvers- if (resolvers) {- schema = addResolversToSchema({- schema,- resolvers,- resolverValidationOptions: {- ...defaultResolverValidationOptions,- ...(config.resolverValidationOptions || {}),- },- });- }- // use logger- if (config.logger) {- schema = addErrorLoggingToSchema(schema, config.logger);- }- // use schema directives- if (config.schemaDirectives) {- SchemaDirectiveVisitor.visitSchemaDirectives(schema, config.schemaDirectives);- }- // extensions- applyExtensions(schema, extensions);- return schema;-}--function normalizePointers(unnormalizedPointerOrPointers) {- return asArray(unnormalizedPointerOrPointers).reduce((normalizedPointers, unnormalizedPointer) => {- if (typeof unnormalizedPointer === 'string') {- normalizedPointers[unnormalizedPointer] = {};- }- else if (typeof unnormalizedPointer === 'object') {- Object.assign(normalizedPointers, unnormalizedPointer);- }- else {- throw new Error(`Invalid pointer ${unnormalizedPointer}`);- }- return normalizedPointers;- }, {});-}--function applyDefaultOptions(options) {- options.cache = options.cache || {};- options.cwd = options.cwd || process$1.cwd();- options.sort = 'sort' in options ? options.sort : true;-}--async function loadFile(pointer, options) {- const cached = useCache({ pointer, options });- if (cached) {- return cached;- }- for await (const loader of options.loaders) {- try {- const canLoad = await loader.canLoad(pointer, options);- if (canLoad) {- return await loader.load(pointer, options);- }- }- catch (error) {- debugLog(`Failed to find any GraphQL type definitions in: ${pointer} - ${error.message}`);- throw error;- }- }- return undefined;-}-function useCache({ pointer, options }) {- if (options['cache']) {- return options['cache'][pointer];- }-}--/**- * Converts a string to 32bit integer- */-function stringToHash(str) {- let hash = 0;- if (str.length === 0) {- return hash;- }- let char;- for (let i = 0; i < str.length; i++) {- char = str.charCodeAt(i);- // tslint:disable-next-line: no-bitwise- hash = (hash << 5) - hash + char;- // tslint:disable-next-line: no-bitwise- hash = hash & hash;- }- return hash;-}-function useStack(...fns) {- return (input) => {- function createNext(i) {- if (i >= fns.length) {- return () => { };- }- return function next() {- fns[i](input, createNext(i + 1));- };- }- fns[0](input, createNext(1));- };-}-function useLimit(concurrency) {- return pLimit_1(concurrency);-}--function getCustomLoaderByPath(path, cwd) {- try {- const requiredModule = importFrom(cwd, path);- if (requiredModule) {- if (requiredModule.default && typeof requiredModule.default === 'function') {- return requiredModule.default;- }- if (typeof requiredModule === 'function') {- return requiredModule;- }- }- }- catch (e) { }- return null;-}-async function useCustomLoader(loaderPointer, cwd) {- let loader;- if (typeof loaderPointer === 'string') {- loader = await getCustomLoaderByPath(loaderPointer, cwd);- }- else if (typeof loaderPointer === 'function') {- loader = loaderPointer;- }- if (typeof loader !== 'function') {- throw new Error(`Failed to load custom loader: ${loaderPointer}`);- }- return loader;-}--function useQueue(options) {- const queue = [];- const limit = (options === null || options === void 0 ? void 0 : options.concurrency) ? pLimit_1(options.concurrency) : async (fn) => fn();- return {- add(fn) {- queue.push(() => limit(fn));- },- runAll() {- return Promise.all(queue.map(fn => fn()));- },- };-}--const CONCURRENCY_LIMIT = 50;-async function collectSources({ pointerOptionMap, options, }) {- var _a;- const sources = [];- const globs = [];- const globOptions = {};- const queue = useQueue({ concurrency: CONCURRENCY_LIMIT });- const { addSource, addGlob, collect } = createHelpers({- sources,- globs,- options,- globOptions,- stack: [collectDocumentString, collectGlob, collectCustomLoader, collectFallback],- });- for (const pointer in pointerOptionMap) {- const pointerOptions = {- ...((_a = pointerOptionMap[pointer]) !== null && _a !== void 0 ? _a : {}),- unixify,- };- collect({- pointer,- pointerOptions,- pointerOptionMap,- options,- addSource,- addGlob,- queue: queue.add,- });- }- if (globs.length) {- includeIgnored({- options,- globs,- });- const paths = await globby$1(globs, createGlobbyOptions(options));- collectSourcesFromGlobals({- filepaths: paths,- options,- globOptions,- pointerOptionMap,- addSource,- queue: queue.add,- });- }- await queue.runAll();- return sources;-}-//-function createHelpers({ sources, globs, options, globOptions, stack, }) {- const addSource = ({ pointer, source, noCache, }) => {- sources.push(source);- if (!noCache) {- options.cache[pointer] = source;- }- };- const collect = useStack(...stack);- const addGlob = ({ pointerOptions, pointer }) => {- globs.push(pointer);- Object.assign(globOptions, pointerOptions);- };- return {- addSource,- collect,- addGlob,- };-}-function includeIgnored({ options, globs }) {- if (options.ignore) {- const ignoreList = asArray(options.ignore)- .map(g => `!(${g})`)- .map(unixify);- if (ignoreList.length > 0) {- globs.push(...ignoreList);- }- }-}-function createGlobbyOptions(options) {- return { absolute: true, ...options, ignore: [] };-}-function collectSourcesFromGlobals({ filepaths, options, globOptions, pointerOptionMap, addSource, queue, }) {- const collectFromGlobs = useStack(collectCustomLoader, collectFallback);- for (let i = 0; i < filepaths.length; i++) {- const pointer = filepaths[i];- collectFromGlobs({- pointer,- pointerOptions: globOptions,- pointerOptionMap,- options,- addSource,- addGlob: () => {- throw new Error(`I don't accept any new globs!`);- },- queue,- });- }-}-function addResultOfCustomLoader({ pointer, result, addSource, }) {- if (isSchema(result)) {- addSource({- source: {- location: pointer,- schema: result,- document: parse(printSchemaWithDirectives(result)),- },- pointer,- noCache: true,- });- }- else if (result.kind && result.kind === Kind.DOCUMENT) {- addSource({- source: {- document: result,- location: pointer,- },- pointer,- });- }- else if (result.document) {- addSource({- source: {- location: pointer,- ...result,- },- pointer,- });- }-}-function collectDocumentString({ pointer, pointerOptions, options, addSource, queue }, next) {- if (isDocumentString(pointer)) {- return queue(() => {- const source = parseGraphQLSDL(`${stringToHash(pointer)}.graphql`, pointer, {- ...options,- ...pointerOptions,- });- addSource({- source,- pointer,- });- });- }- next();-}-function collectGlob({ pointer, pointerOptions, addGlob }, next) {- if (isGlob(pointerOptions.unixify(pointer))) {- return addGlob({- pointer: pointerOptions.unixify(pointer),- pointerOptions,- });- }- next();-}-function collectCustomLoader({ pointer, pointerOptions, queue, addSource, options, pointerOptionMap }, next) {- if (pointerOptions.loader) {- return queue(async () => {- const loader = await useCustomLoader(pointerOptions.loader, options.cwd);- const result = await loader(pointer, { ...options, ...pointerOptions }, pointerOptionMap);- if (!result) {- return;- }- addResultOfCustomLoader({ pointer, result, addSource });- });- }- next();-}-function collectFallback({ queue, pointer, options, pointerOptions, addSource }) {- return queue(async () => {- const source = await loadFile(pointer, {- ...options,- ...pointerOptions,- });- if (source) {- addSource({ source, pointer });- }- });-}--/**- * @internal- */-const filterKind = (content, filterKinds) => {- if (content && content.definitions && content.definitions.length && filterKinds && filterKinds.length > 0) {- const invalidDefinitions = [];- const validDefinitions = [];- for (const definitionNode of content.definitions) {- if (filterKinds.includes(definitionNode.kind)) {- invalidDefinitions.push(definitionNode);- }- else {- validDefinitions.push(definitionNode);- }- }- if (invalidDefinitions.length > 0) {- invalidDefinitions.forEach(d => {- debugLog(`Filtered document of kind ${d.kind} due to filter policy (${filterKinds.join(', ')})`);- });- }- return {- kind: Kind.DOCUMENT,- definitions: validDefinitions,- };- }- return content;-};--function parseSource({ partialSource, options, globOptions, pointerOptionMap, addValidSource }) {- if (partialSource) {- const input = prepareInput({- source: partialSource,- options,- globOptions,- pointerOptionMap,- });- parseSchema(input);- parseRawSDL(input);- if (input.source.document) {- useKindsFilter(input);- useComments(input);- collectValidSources(input, addValidSource);- }- }-}-//-function prepareInput({ source, options, globOptions, pointerOptionMap, }) {- const specificOptions = {- ...options,- ...(source.location in pointerOptionMap ? globOptions : pointerOptionMap[source.location]),- };- return { source: { ...source }, options: specificOptions };-}-function parseSchema(input) {- if (input.source.schema) {- input.source.schema = fixSchemaAst(input.source.schema, input.options);- input.source.rawSDL = printSchemaWithDirectives(input.source.schema, input.options);- }-}-function parseRawSDL(input) {- if (input.source.rawSDL) {- input.source.document = parseGraphQLSDL(input.source.location, input.source.rawSDL, input.options).document;- }-}-function useKindsFilter(input) {- if (input.options.filterKinds) {- input.source.document = filterKind(input.source.document, input.options.filterKinds);- }-}-function useComments(input) {- if (!input.source.rawSDL) {- input.source.rawSDL = printWithComments$1(input.source.document);- resetComments$1();- }-}-function collectValidSources(input, addValidSource) {- if (input.source.document.definitions && input.source.document.definitions.length > 0) {- addValidSource(input.source);- }-}--const CONCURRENCY_LIMIT$1 = 100;-/**- * Asynchronously loads any GraphQL documents (i.e. executable documents like- * operations and fragments as well as type system definitions) from the- * provided pointers.- * @param pointerOrPointers Pointers to the sources to load the documents from- * @param options Additional options- */-async function loadTypedefs(pointerOrPointers, options) {- const pointerOptionMap = normalizePointers(pointerOrPointers);- const globOptions = {};- applyDefaultOptions(options);- const sources = await collectSources({- pointerOptionMap,- options,- });- const validSources = [];- // If we have few k of files it may be an issue- const limit = useLimit(CONCURRENCY_LIMIT$1);- await Promise.all(sources.map(partialSource => limit(() => parseSource({- partialSource,- options,- globOptions,- pointerOptionMap,- addValidSource(source) {- validSources.push(source);- },- }))));- return prepareResult({ options, pointerOptionMap, validSources });-}-//-function prepareResult({ options, pointerOptionMap, validSources, }) {- const pointerList = Object.keys(pointerOptionMap);- if (pointerList.length > 0 && validSources.length === 0) {- throw new Error(`- Unable to find any GraphQL type definitions for the following pointers:- ${pointerList.map(p => `- - ${p}- `)}`);- }- return options.sort- ? validSources.sort((left, right) => compareStrings(left.location, right.location))- : validSources;-}--/**- * Kinds of AST nodes that are included in executable documents- */-const OPERATION_KINDS = [Kind.OPERATION_DEFINITION, Kind.FRAGMENT_DEFINITION];-/**- * Kinds of AST nodes that are included in type system definition documents- */-const NON_OPERATION_KINDS = Object.keys(Kind)- .reduce((prev, v) => [...prev, Kind[v]], [])- .filter(v => !OPERATION_KINDS.includes(v));-/**- * Asynchronously loads executable documents (i.e. operations and fragments) from- * the provided pointers. The pointers may be individual files or a glob pattern.- * The files themselves may be `.graphql` files or `.js` and `.ts` (in which- * case they will be parsed using graphql-tag-pluck).- * @param pointerOrPointers Pointers to the files to load the documents from- * @param options Additional options- */-function loadDocuments(pointerOrPointers, options) {- return loadTypedefs(pointerOrPointers, { noRequire: true, filterKinds: NON_OPERATION_KINDS, ...options });-}--/**- * Asynchronously loads a schema from the provided pointers.- * @param schemaPointers Pointers to the sources to load the schema from- * @param options Additional options- */-async function loadSchema(schemaPointers, options) {- const sources = await loadTypedefs(schemaPointers, {- filterKinds: OPERATION_KINDS,- ...options,- });- const { schemas, typeDefs } = collectSchemasAndTypeDefs(sources);- const mergeSchemasOptions = {- schemas,- typeDefs,- ...options,- };- const schema = await mergeSchemasAsync(mergeSchemasOptions);- if (options === null || options === void 0 ? void 0 : options.includeSources) {- includeSources(schema, sources);- }- return schema;-}-function includeSources(schema, sources) {- schema.extensions = {- ...schema.extensions,- sources: sources- .filter(source => source.rawSDL || source.document)- .map(source => new Source(source.rawSDL || print(source.document), source.location)),- };-}-function collectSchemasAndTypeDefs(sources) {- const schemas = [];- const typeDefs = [];- sources.forEach(source => {- if (source.schema) {- schemas.push(source.schema);- }- else {- typeDefs.push(source.document);- }- });- return {- schemas,- typeDefs,- };-}--var validUrl = createCommonjsModule(function (module) {-(function(module) {-- module.exports.is_uri = is_iri;- module.exports.is_http_uri = is_http_iri;- module.exports.is_https_uri = is_https_iri;- module.exports.is_web_uri = is_web_iri;- // Create aliases- module.exports.isUri = is_iri;- module.exports.isHttpUri = is_http_iri;- module.exports.isHttpsUri = is_https_iri;- module.exports.isWebUri = is_web_iri;--- // private function- // internal URI spitter method - direct from RFC 3986- var splitUri = function(uri) {- var splitted = uri.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);- return splitted;- };-- function is_iri(value) {- if (!value) {- return;- }-- // check for illegal characters- if (/[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i.test(value)) return;-- // check for hex escapes that aren't complete- if (/%[^0-9a-f]/i.test(value)) return;- if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return;-- var splitted = [];- var scheme = '';- var authority = '';- var path = '';- var query = '';- var fragment = '';- var out = '';-- // from RFC 3986- splitted = splitUri(value);- scheme = splitted[1]; - authority = splitted[2];- path = splitted[3];- query = splitted[4];- fragment = splitted[5];-- // scheme and path are required, though the path can be empty- if (!(scheme && scheme.length && path.length >= 0)) return;-- // if authority is present, the path must be empty or begin with a /- if (authority && authority.length) {- if (!(path.length === 0 || /^\//.test(path))) return;- } else {- // if authority is not present, the path must not start with //- if (/^\/\//.test(path)) return;- }-- // scheme must begin with a letter, then consist of letters, digits, +, ., or -- if (!/^[a-z][a-z0-9\+\-\.]*$/.test(scheme.toLowerCase())) return;-- // re-assemble the URL per section 5.3 in RFC 3986- out += scheme + ':';- if (authority && authority.length) {- out += '//' + authority;- }-- out += path;-- if (query && query.length) {- out += '?' + query;- }-- if (fragment && fragment.length) {- out += '#' + fragment;- }-- return out;- }-- function is_http_iri(value, allowHttps) {- if (!is_iri(value)) {- return;- }-- var splitted = [];- var scheme = '';- var authority = '';- var path = '';- var port = '';- var query = '';- var fragment = '';- var out = '';-- // from RFC 3986- splitted = splitUri(value);- scheme = splitted[1]; - authority = splitted[2];- path = splitted[3];- query = splitted[4];- fragment = splitted[5];-- if (!scheme) return;-- if(allowHttps) {- if (scheme.toLowerCase() != 'https') return;- } else {- if (scheme.toLowerCase() != 'http') return;- }-- // fully-qualified URIs must have an authority section that is- // a valid host- if (!authority) {- return;- }-- // enable port component- if (/:(\d+)$/.test(authority)) {- port = authority.match(/:(\d+)$/)[0];- authority = authority.replace(/:\d+$/, '');- }-- out += scheme + ':';- out += '//' + authority;- - if (port) {- out += port;- }- - out += path;- - if(query && query.length){- out += '?' + query;- }-- if(fragment && fragment.length){- out += '#' + fragment;- }- - return out;- }-- function is_https_iri(value) {- return is_http_iri(value, true);- }-- function is_web_iri(value) {- return (is_http_iri(value) || is_https_iri(value));- }--})(module);-});--// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js--// fix for "Readable" isn't a named export issue-const Readable = Stream$2.Readable;--const BUFFER = Symbol('buffer');-const TYPE = Symbol('type');--class Blob {- constructor() {- this[TYPE] = '';-- const blobParts = arguments[0];- const options = arguments[1];-- const buffers = [];- let size = 0;-- if (blobParts) {- const a = blobParts;- const length = Number(a.length);- for (let i = 0; i < length; i++) {- const element = a[i];- let buffer;- if (element instanceof Buffer) {- buffer = element;- } else if (ArrayBuffer.isView(element)) {- buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);- } else if (element instanceof ArrayBuffer) {- buffer = Buffer.from(element);- } else if (element instanceof Blob) {- buffer = element[BUFFER];- } else {- buffer = Buffer.from(typeof element === 'string' ? element : String(element));- }- size += buffer.length;- buffers.push(buffer);- }- }-- this[BUFFER] = Buffer.concat(buffers);-- let type = options && options.type !== undefined && String(options.type).toLowerCase();- if (type && !/[^\u0020-\u007E]/.test(type)) {- this[TYPE] = type;- }- }- get size() {- return this[BUFFER].length;- }- get type() {- return this[TYPE];- }- text() {- return Promise.resolve(this[BUFFER].toString());- }- arrayBuffer() {- const buf = this[BUFFER];- const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);- return Promise.resolve(ab);- }- stream() {- const readable = new Readable();- readable._read = function () {};- readable.push(this[BUFFER]);- readable.push(null);- return readable;- }- toString() {- return '[object Blob]';- }- slice() {- const size = this.size;-- const start = arguments[0];- const end = arguments[1];- let relativeStart, relativeEnd;- if (start === undefined) {- relativeStart = 0;- } else if (start < 0) {- relativeStart = Math.max(size + start, 0);- } else {- relativeStart = Math.min(start, size);- }- if (end === undefined) {- relativeEnd = size;- } else if (end < 0) {- relativeEnd = Math.max(size + end, 0);- } else {- relativeEnd = Math.min(end, size);- }- const span = Math.max(relativeEnd - relativeStart, 0);-- const buffer = this[BUFFER];- const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);- const blob = new Blob([], { type: arguments[2] });- blob[BUFFER] = slicedBuffer;- return blob;- }-}--Object.defineProperties(Blob.prototype, {- size: { enumerable: true },- type: { enumerable: true },- slice: { enumerable: true }-});--Object.defineProperty(Blob.prototype, Symbol.toStringTag, {- value: 'Blob',- writable: false,- enumerable: false,- configurable: true-});--/**- * fetch-error.js- *- * FetchError interface for operational errors- */--/**- * Create FetchError instance- *- * @param String message Error message for human- * @param String type Error type for machine- * @param String systemError For Node.js system error- * @return FetchError- */-function FetchError(message, type, systemError) {- Error.call(this, message);-- this.message = message;- this.type = type;-- // when err.type is `system`, err.code contains system error code- if (systemError) {- this.code = this.errno = systemError.code;- }-- // hide custom error implementation details from end-users- Error.captureStackTrace(this, this.constructor);-}--FetchError.prototype = Object.create(Error.prototype);-FetchError.prototype.constructor = FetchError;-FetchError.prototype.name = 'FetchError';--let convert;-try {- convert = require('encoding').convert;-} catch (e) {}--const INTERNALS = Symbol('Body internals');--// fix an issue where "PassThrough" isn't a named export for node <10-const PassThrough$1 = Stream$2.PassThrough;--/**- * Body mixin- *- * Ref: https://fetch.spec.whatwg.org/#body- *- * @param Stream body Readable stream- * @param Object opts Response options- * @return Void- */-function Body(body) {- var _this = this;-- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},- _ref$size = _ref.size;-- let size = _ref$size === undefined ? 0 : _ref$size;- var _ref$timeout = _ref.timeout;- let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;-- if (body == null) {- // body is undefined or null- body = null;- } else if (isURLSearchParams(body)) {- // body is a URLSearchParams- body = Buffer.from(body.toString());- } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {- // body is ArrayBuffer- body = Buffer.from(body);- } else if (ArrayBuffer.isView(body)) {- // body is ArrayBufferView- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);- } else if (body instanceof Stream$2) ; else {- // none of the above- // coerce to string then buffer- body = Buffer.from(String(body));- }- this[INTERNALS] = {- body,- disturbed: false,- error: null- };- this.size = size;- this.timeout = timeout;-- if (body instanceof Stream$2) {- body.on('error', function (err) {- const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);- _this[INTERNALS].error = error;- });- }-}--Body.prototype = {- get body() {- return this[INTERNALS].body;- },-- get bodyUsed() {- return this[INTERNALS].disturbed;- },-- /**- * Decode response as ArrayBuffer- *- * @return Promise- */- arrayBuffer() {- return consumeBody.call(this).then(function (buf) {- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);- });- },-- /**- * Return raw response as Blob- *- * @return Promise- */- blob() {- let ct = this.headers && this.headers.get('content-type') || '';- return consumeBody.call(this).then(function (buf) {- return Object.assign(- // Prevent copying- new Blob([], {- type: ct.toLowerCase()- }), {- [BUFFER]: buf- });- });- },-- /**- * Decode response as json- *- * @return Promise- */- json() {- var _this2 = this;-- return consumeBody.call(this).then(function (buffer) {- try {- return JSON.parse(buffer.toString());- } catch (err) {- return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));- }- });- },-- /**- * Decode response as text- *- * @return Promise- */- text() {- return consumeBody.call(this).then(function (buffer) {- return buffer.toString();- });- },-- /**- * Decode response as buffer (non-spec api)- *- * @return Promise- */- buffer() {- return consumeBody.call(this);- },-- /**- * Decode response as text, while automatically detecting the encoding and- * trying to decode to UTF-8 (non-spec api)- *- * @return Promise- */- textConverted() {- var _this3 = this;-- return consumeBody.call(this).then(function (buffer) {- return convertBody(buffer, _this3.headers);- });- }-};--// In browsers, all properties are enumerable.-Object.defineProperties(Body.prototype, {- body: { enumerable: true },- bodyUsed: { enumerable: true },- arrayBuffer: { enumerable: true },- blob: { enumerable: true },- json: { enumerable: true },- text: { enumerable: true }-});--Body.mixIn = function (proto) {- for (const name of Object.getOwnPropertyNames(Body.prototype)) {- // istanbul ignore else: future proof- if (!(name in proto)) {- const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);- Object.defineProperty(proto, name, desc);- }- }-};--/**- * Consume and convert an entire Body to a Buffer.- *- * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body- *- * @return Promise- */-function consumeBody() {- var _this4 = this;-- if (this[INTERNALS].disturbed) {- return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));- }-- this[INTERNALS].disturbed = true;-- if (this[INTERNALS].error) {- return Body.Promise.reject(this[INTERNALS].error);- }-- let body = this.body;-- // body is null- if (body === null) {- return Body.Promise.resolve(Buffer.alloc(0));- }-- // body is blob- if (isBlob(body)) {- body = body.stream();- }-- // body is buffer- if (Buffer.isBuffer(body)) {- return Body.Promise.resolve(body);- }-- // istanbul ignore if: should never happen- if (!(body instanceof Stream$2)) {- return Body.Promise.resolve(Buffer.alloc(0));- }-- // body is stream- // get ready to actually consume the body- let accum = [];- let accumBytes = 0;- let abort = false;-- return new Body.Promise(function (resolve, reject) {- let resTimeout;-- // allow timeout on slow response body- if (_this4.timeout) {- resTimeout = setTimeout(function () {- abort = true;- reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));- }, _this4.timeout);- }-- // handle stream errors- body.on('error', function (err) {- if (err.name === 'AbortError') {- // if the request was aborted, reject with this Error- abort = true;- reject(err);- } else {- // other errors, such as incorrect content-encoding- reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));- }- });-- body.on('data', function (chunk) {- if (abort || chunk === null) {- return;- }-- if (_this4.size && accumBytes + chunk.length > _this4.size) {- abort = true;- reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));- return;- }-- accumBytes += chunk.length;- accum.push(chunk);- });-- body.on('end', function () {- if (abort) {- return;- }-- clearTimeout(resTimeout);-- try {- resolve(Buffer.concat(accum, accumBytes));- } catch (err) {- // handle streams that have accumulated too much data (issue #414)- reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));- }- });- });-}--/**- * Detect buffer encoding and convert to target encoding- * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding- *- * @param Buffer buffer Incoming buffer- * @param String encoding Target encoding- * @return String- */-function convertBody(buffer, headers) {- if (typeof convert !== 'function') {- throw new Error('The package `encoding` must be installed to use the textConverted() function');- }-- const ct = headers.get('content-type');- let charset = 'utf-8';- let res, str;-- // header- if (ct) {- res = /charset=([^;]*)/i.exec(ct);- }-- // no charset in content type, peek at response body for at most 1024 bytes- str = buffer.slice(0, 1024).toString();-- // html5- if (!res && str) {- res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);- }-- // html4- if (!res && str) {- res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);-- if (res) {- res = /charset=(.*)/i.exec(res.pop());- }- }-- // xml- if (!res && str) {- res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);- }-- // found charset- if (res) {- charset = res.pop();-- // prevent decode issues when sites use incorrect encoding- // ref: https://hsivonen.fi/encoding-menu/- if (charset === 'gb2312' || charset === 'gbk') {- charset = 'gb18030';- }- }-- // turn raw buffers into a single utf-8 buffer- return convert(buffer, 'UTF-8', charset).toString();-}--/**- * Detect a URLSearchParams object- * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143- *- * @param Object obj Object to detect by type or brand- * @return String- */-function isURLSearchParams(obj) {- // Duck-typing as a necessary condition.- if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {- return false;- }-- // Brand-checking and more duck-typing as optional condition.- return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';-}--/**- * Check if `obj` is a W3C `Blob` object (which `File` inherits from)- * @param {*} obj- * @return {boolean}- */-function isBlob(obj) {- return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);-}--/**- * Clone body given Res/Req instance- *- * @param Mixed instance Response or Request instance- * @return Mixed- */-function clone$2(instance) {- let p1, p2;- let body = instance.body;-- // don't allow cloning a used body- if (instance.bodyUsed) {- throw new Error('cannot clone body after it is used');- }-- // check that body is a stream and not form-data object- // note: we can't clone the form-data object without having it as a dependency- if (body instanceof Stream$2 && typeof body.getBoundary !== 'function') {- // tee instance body- p1 = new PassThrough$1();- p2 = new PassThrough$1();- body.pipe(p1);- body.pipe(p2);- // set instance body to teed body and return the other teed body- instance[INTERNALS].body = p1;- body = p2;- }-- return body;-}--/**- * Performs the operation "extract a `Content-Type` value from |object|" as- * specified in the specification:- * https://fetch.spec.whatwg.org/#concept-bodyinit-extract- *- * This function assumes that instance.body is present.- *- * @param Mixed instance Any options.body input- */-function extractContentType(body) {- if (body === null) {- // body is null- return null;- } else if (typeof body === 'string') {- // body is string- return 'text/plain;charset=UTF-8';- } else if (isURLSearchParams(body)) {- // body is a URLSearchParams- return 'application/x-www-form-urlencoded;charset=UTF-8';- } else if (isBlob(body)) {- // body is blob- return body.type || null;- } else if (Buffer.isBuffer(body)) {- // body is buffer- return null;- } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {- // body is ArrayBuffer- return null;- } else if (ArrayBuffer.isView(body)) {- // body is ArrayBufferView- return null;- } else if (typeof body.getBoundary === 'function') {- // detect form data input from form-data module- return `multipart/form-data;boundary=${body.getBoundary()}`;- } else if (body instanceof Stream$2) {- // body is stream- // can't really do much about this- return null;- } else {- // Body constructor defaults other things to string- return 'text/plain;charset=UTF-8';- }-}--/**- * The Fetch Standard treats this as if "total bytes" is a property on the body.- * For us, we have to explicitly get it with a function.- *- * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes- *- * @param Body instance Instance of Body- * @return Number? Number of bytes, or null if not possible- */-function getTotalBytes(instance) {- const body = instance.body;--- if (body === null) {- // body is null- return 0;- } else if (isBlob(body)) {- return body.size;- } else if (Buffer.isBuffer(body)) {- // body is buffer- return body.length;- } else if (body && typeof body.getLengthSync === 'function') {- // detect form data input from form-data module- if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x- body.hasKnownLength && body.hasKnownLength()) {- // 2.x- return body.getLengthSync();- }- return null;- } else {- // body is stream- return null;- }-}--/**- * Write a Body to a Node.js WritableStream (e.g. http.Request) object.- *- * @param Body instance Instance of Body- * @return Void- */-function writeToStream(dest, instance) {- const body = instance.body;--- if (body === null) {- // body is null- dest.end();- } else if (isBlob(body)) {- body.stream().pipe(dest);- } else if (Buffer.isBuffer(body)) {- // body is buffer- dest.write(body);- dest.end();- } else {- // body is stream- body.pipe(dest);- }-}--// expose Promise-Body.Promise = global.Promise;--/**- * headers.js- *- * Headers class offers convenient helpers- */--const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;-const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;--function validateName$1(name) {- name = `${name}`;- if (invalidTokenRegex.test(name) || name === '') {- throw new TypeError(`${name} is not a legal HTTP header name`);- }-}--function validateValue(value) {- value = `${value}`;- if (invalidHeaderCharRegex.test(value)) {- throw new TypeError(`${value} is not a legal HTTP header value`);- }-}--/**- * Find the key in the map object given a header name.- *- * Returns undefined if not found.- *- * @param String name Header name- * @return String|Undefined- */-function find$1(map, name) {- name = name.toLowerCase();- for (const key in map) {- if (key.toLowerCase() === name) {- return key;- }- }- return undefined;-}--const MAP = Symbol('map');-class Headers {- /**- * Headers class- *- * @param Object headers Response headers- * @return Void- */- constructor() {- let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;-- this[MAP] = Object.create(null);-- if (init instanceof Headers) {- const rawHeaders = init.raw();- const headerNames = Object.keys(rawHeaders);-- for (const headerName of headerNames) {- for (const value of rawHeaders[headerName]) {- this.append(headerName, value);- }- }-- return;- }-- // We don't worry about converting prop to ByteString here as append()- // will handle it.- if (init == null) ; else if (typeof init === 'object') {- const method = init[Symbol.iterator];- if (method != null) {- if (typeof method !== 'function') {- throw new TypeError('Header pairs must be iterable');- }-- // sequence<sequence<ByteString>>- // Note: per spec we have to first exhaust the lists then process them- const pairs = [];- for (const pair of init) {- if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {- throw new TypeError('Each header pair must be iterable');- }- pairs.push(Array.from(pair));- }-- for (const pair of pairs) {- if (pair.length !== 2) {- throw new TypeError('Each header pair must be a name/value tuple');- }- this.append(pair[0], pair[1]);- }- } else {- // record<ByteString, ByteString>- for (const key of Object.keys(init)) {- const value = init[key];- this.append(key, value);- }- }- } else {- throw new TypeError('Provided initializer must be an object');- }- }-- /**- * Return combined header value given name- *- * @param String name Header name- * @return Mixed- */- get(name) {- name = `${name}`;- validateName$1(name);- const key = find$1(this[MAP], name);- if (key === undefined) {- return null;- }-- return this[MAP][key].join(', ');- }-- /**- * Iterate over all headers- *- * @param Function callback Executed for each item with parameters (value, name, thisArg)- * @param Boolean thisArg `this` context for callback function- * @return Void- */- forEach(callback) {- let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;-- let pairs = getHeaders(this);- let i = 0;- while (i < pairs.length) {- var _pairs$i = pairs[i];- const name = _pairs$i[0],- value = _pairs$i[1];-- callback.call(thisArg, value, name, this);- pairs = getHeaders(this);- i++;- }- }-- /**- * Overwrite header values given name- *- * @param String name Header name- * @param String value Header value- * @return Void- */- set(name, value) {- name = `${name}`;- value = `${value}`;- validateName$1(name);- validateValue(value);- const key = find$1(this[MAP], name);- this[MAP][key !== undefined ? key : name] = [value];- }-- /**- * Append a value onto existing header- *- * @param String name Header name- * @param String value Header value- * @return Void- */- append(name, value) {- name = `${name}`;- value = `${value}`;- validateName$1(name);- validateValue(value);- const key = find$1(this[MAP], name);- if (key !== undefined) {- this[MAP][key].push(value);- } else {- this[MAP][name] = [value];- }- }-- /**- * Check for header name existence- *- * @param String name Header name- * @return Boolean- */- has(name) {- name = `${name}`;- validateName$1(name);- return find$1(this[MAP], name) !== undefined;- }-- /**- * Delete all header values given name- *- * @param String name Header name- * @return Void- */- delete(name) {- name = `${name}`;- validateName$1(name);- const key = find$1(this[MAP], name);- if (key !== undefined) {- delete this[MAP][key];- }- }-- /**- * Return raw headers (non-spec api)- *- * @return Object- */- raw() {- return this[MAP];- }-- /**- * Get an iterator on keys.- *- * @return Iterator- */- keys() {- return createHeadersIterator(this, 'key');- }-- /**- * Get an iterator on values.- *- * @return Iterator- */- values() {- return createHeadersIterator(this, 'value');- }-- /**- * Get an iterator on entries.- *- * This is the default iterator of the Headers object.- *- * @return Iterator- */- [Symbol.iterator]() {- return createHeadersIterator(this, 'key+value');- }-}-Headers.prototype.entries = Headers.prototype[Symbol.iterator];--Object.defineProperty(Headers.prototype, Symbol.toStringTag, {- value: 'Headers',- writable: false,- enumerable: false,- configurable: true-});--Object.defineProperties(Headers.prototype, {- get: { enumerable: true },- forEach: { enumerable: true },- set: { enumerable: true },- append: { enumerable: true },- has: { enumerable: true },- delete: { enumerable: true },- keys: { enumerable: true },- values: { enumerable: true },- entries: { enumerable: true }-});--function getHeaders(headers) {- let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';-- const keys = Object.keys(headers[MAP]).sort();- return keys.map(kind === 'key' ? function (k) {- return k.toLowerCase();- } : kind === 'value' ? function (k) {- return headers[MAP][k].join(', ');- } : function (k) {- return [k.toLowerCase(), headers[MAP][k].join(', ')];- });-}--const INTERNAL = Symbol('internal');--function createHeadersIterator(target, kind) {- const iterator = Object.create(HeadersIteratorPrototype);- iterator[INTERNAL] = {- target,- kind,- index: 0- };- return iterator;-}--const HeadersIteratorPrototype = Object.setPrototypeOf({- next() {- // istanbul ignore if- if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {- throw new TypeError('Value of `this` is not a HeadersIterator');- }-- var _INTERNAL = this[INTERNAL];- const target = _INTERNAL.target,- kind = _INTERNAL.kind,- index = _INTERNAL.index;-- const values = getHeaders(target, kind);- const len = values.length;- if (index >= len) {- return {- value: undefined,- done: true- };- }-- this[INTERNAL].index = index + 1;-- return {- value: values[index],- done: false- };- }-}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));--Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {- value: 'HeadersIterator',- writable: false,- enumerable: false,- configurable: true-});--/**- * Export the Headers object in a form that Node.js can consume.- *- * @param Headers headers- * @return Object- */-function exportNodeCompatibleHeaders(headers) {- const obj = Object.assign({ __proto__: null }, headers[MAP]);-- // http.request() only supports string as Host header. This hack makes- // specifying custom Host header possible.- const hostHeaderKey = find$1(headers[MAP], 'Host');- if (hostHeaderKey !== undefined) {- obj[hostHeaderKey] = obj[hostHeaderKey][0];- }-- return obj;-}--/**- * Create a Headers object from an object of headers, ignoring those that do- * not conform to HTTP grammar productions.- *- * @param Object obj Object of headers- * @return Headers- */-function createHeadersLenient(obj) {- const headers = new Headers();- for (const name of Object.keys(obj)) {- if (invalidTokenRegex.test(name)) {- continue;- }- if (Array.isArray(obj[name])) {- for (const val of obj[name]) {- if (invalidHeaderCharRegex.test(val)) {- continue;- }- if (headers[MAP][name] === undefined) {- headers[MAP][name] = [val];- } else {- headers[MAP][name].push(val);- }- }- } else if (!invalidHeaderCharRegex.test(obj[name])) {- headers[MAP][name] = [obj[name]];- }- }- return headers;-}--const INTERNALS$1 = Symbol('Response internals');--// fix an issue where "STATUS_CODES" aren't a named export for node <10-const STATUS_CODES = http.STATUS_CODES;--/**- * Response class- *- * @param Stream body Readable stream- * @param Object opts Response options- * @return Void- */-class Response {- constructor() {- let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;- let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};-- Body.call(this, body, opts);-- const status = opts.status || 200;- const headers = new Headers(opts.headers);-- if (body != null && !headers.has('Content-Type')) {- const contentType = extractContentType(body);- if (contentType) {- headers.append('Content-Type', contentType);- }- }-- this[INTERNALS$1] = {- url: opts.url,- status,- statusText: opts.statusText || STATUS_CODES[status],- headers,- counter: opts.counter- };- }-- get url() {- return this[INTERNALS$1].url || '';- }-- get status() {- return this[INTERNALS$1].status;- }-- /**- * Convenience property representing if the request ended normally- */- get ok() {- return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;- }-- get redirected() {- return this[INTERNALS$1].counter > 0;- }-- get statusText() {- return this[INTERNALS$1].statusText;- }-- get headers() {- return this[INTERNALS$1].headers;- }-- /**- * Clone this response- *- * @return Response- */- clone() {- return new Response(clone$2(this), {- url: this.url,- status: this.status,- statusText: this.statusText,- headers: this.headers,- ok: this.ok,- redirected: this.redirected- });- }-}--Body.mixIn(Response.prototype);--Object.defineProperties(Response.prototype, {- url: { enumerable: true },- status: { enumerable: true },- ok: { enumerable: true },- redirected: { enumerable: true },- statusText: { enumerable: true },- headers: { enumerable: true },- clone: { enumerable: true }-});--Object.defineProperty(Response.prototype, Symbol.toStringTag, {- value: 'Response',- writable: false,- enumerable: false,- configurable: true-});--const INTERNALS$2 = Symbol('Request internals');--// fix an issue where "format", "parse" aren't a named export for node <10-const parse_url = Url.parse;-const format_url = Url.format;--const streamDestructionSupported = 'destroy' in Stream$2.Readable.prototype;--/**- * Check if a value is an instance of Request.- *- * @param Mixed input- * @return Boolean- */-function isRequest(input) {- return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';-}--function isAbortSignal(signal) {- const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);- return !!(proto && proto.constructor.name === 'AbortSignal');-}--/**- * Request class- *- * @param Mixed input Url or Request instance- * @param Object init Custom options- * @return Void- */-class Request {- constructor(input) {- let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};-- let parsedURL;-- // normalize input- if (!isRequest(input)) {- if (input && input.href) {- // in order to support Node.js' Url objects; though WHATWG's URL objects- // will fall into this branch also (since their `toString()` will return- // `href` property anyway)- parsedURL = parse_url(input.href);- } else {- // coerce input to a string before attempting to parse- parsedURL = parse_url(`${input}`);- }- input = {};- } else {- parsedURL = parse_url(input.url);- }-- let method = init.method || input.method || 'GET';- method = method.toUpperCase();-- if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {- throw new TypeError('Request with GET/HEAD method cannot have body');- }-- let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone$2(input) : null;-- Body.call(this, inputBody, {- timeout: init.timeout || input.timeout || 0,- size: init.size || input.size || 0- });-- const headers = new Headers(init.headers || input.headers || {});-- if (inputBody != null && !headers.has('Content-Type')) {- const contentType = extractContentType(inputBody);- if (contentType) {- headers.append('Content-Type', contentType);- }- }-- let signal = isRequest(input) ? input.signal : null;- if ('signal' in init) signal = init.signal;-- if (signal != null && !isAbortSignal(signal)) {- throw new TypeError('Expected signal to be an instanceof AbortSignal');- }-- this[INTERNALS$2] = {- method,- redirect: init.redirect || input.redirect || 'follow',- headers,- parsedURL,- signal- };-- // node-fetch-only options- this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;- this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;- this.counter = init.counter || input.counter || 0;- this.agent = init.agent || input.agent;- }-- get method() {- return this[INTERNALS$2].method;- }-- get url() {- return format_url(this[INTERNALS$2].parsedURL);- }-- get headers() {- return this[INTERNALS$2].headers;- }-- get redirect() {- return this[INTERNALS$2].redirect;- }-- get signal() {- return this[INTERNALS$2].signal;- }-- /**- * Clone this request- *- * @return Request- */- clone() {- return new Request(this);- }-}--Body.mixIn(Request.prototype);--Object.defineProperty(Request.prototype, Symbol.toStringTag, {- value: 'Request',- writable: false,- enumerable: false,- configurable: true-});--Object.defineProperties(Request.prototype, {- method: { enumerable: true },- url: { enumerable: true },- headers: { enumerable: true },- redirect: { enumerable: true },- clone: { enumerable: true },- signal: { enumerable: true }-});--/**- * Convert a Request to Node.js http request options.- *- * @param Request A Request instance- * @return Object The options object to be passed to http.request- */-function getNodeRequestOptions(request) {- const parsedURL = request[INTERNALS$2].parsedURL;- const headers = new Headers(request[INTERNALS$2].headers);-- // fetch step 1.3- if (!headers.has('Accept')) {- headers.set('Accept', '*/*');- }-- // Basic fetch- if (!parsedURL.protocol || !parsedURL.hostname) {- throw new TypeError('Only absolute URLs are supported');- }-- if (!/^https?:$/.test(parsedURL.protocol)) {- throw new TypeError('Only HTTP(S) protocols are supported');- }-- if (request.signal && request.body instanceof Stream$2.Readable && !streamDestructionSupported) {- throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');- }-- // HTTP-network-or-cache fetch steps 2.4-2.7- let contentLengthValue = null;- if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {- contentLengthValue = '0';- }- if (request.body != null) {- const totalBytes = getTotalBytes(request);- if (typeof totalBytes === 'number') {- contentLengthValue = String(totalBytes);- }- }- if (contentLengthValue) {- headers.set('Content-Length', contentLengthValue);- }-- // HTTP-network-or-cache fetch step 2.11- if (!headers.has('User-Agent')) {- headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');- }-- // HTTP-network-or-cache fetch step 2.15- if (request.compress && !headers.has('Accept-Encoding')) {- headers.set('Accept-Encoding', 'gzip,deflate');- }-- let agent = request.agent;- if (typeof agent === 'function') {- agent = agent(parsedURL);- }-- if (!headers.has('Connection') && !agent) {- headers.set('Connection', 'close');- }-- // HTTP-network fetch step 4.2- // chunked encoding is handled by Node.js-- return Object.assign({}, parsedURL, {- method: request.method,- headers: exportNodeCompatibleHeaders(headers),- agent- });-}--/**- * abort-error.js- *- * AbortError interface for cancelled requests- */--/**- * Create AbortError instance- *- * @param String message Error message for human- * @return AbortError- */-function AbortError(message) {- Error.call(this, message);-- this.type = 'aborted';- this.message = message;-- // hide custom error implementation details from end-users- Error.captureStackTrace(this, this.constructor);-}--AbortError.prototype = Object.create(Error.prototype);-AbortError.prototype.constructor = AbortError;-AbortError.prototype.name = 'AbortError';--// fix an issue where "PassThrough", "resolve" aren't a named export for node <10-const PassThrough$1$1 = Stream$2.PassThrough;-const resolve_url = Url.resolve;--/**- * Fetch function- *- * @param Mixed url Absolute url or Request instance- * @param Object opts Fetch options- * @return Promise- */-function fetch(url, opts) {-- // allow custom promise- if (!fetch.Promise) {- throw new Error('native promise missing, set fetch.Promise to your favorite alternative');- }-- Body.Promise = fetch.Promise;-- // wrap http.request into fetch- return new fetch.Promise(function (resolve, reject) {- // build request object- const request = new Request(url, opts);- const options = getNodeRequestOptions(request);-- const send = (options.protocol === 'https:' ? https : http).request;- const signal = request.signal;-- let response = null;-- const abort = function abort() {- let error = new AbortError('The user aborted a request.');- reject(error);- if (request.body && request.body instanceof Stream$2.Readable) {- request.body.destroy(error);- }- if (!response || !response.body) return;- response.body.emit('error', error);- };-- if (signal && signal.aborted) {- abort();- return;- }-- const abortAndFinalize = function abortAndFinalize() {- abort();- finalize();- };-- // send request- const req = send(options);- let reqTimeout;-- if (signal) {- signal.addEventListener('abort', abortAndFinalize);- }-- function finalize() {- req.abort();- if (signal) signal.removeEventListener('abort', abortAndFinalize);- clearTimeout(reqTimeout);- }-- if (request.timeout) {- req.once('socket', function (socket) {- reqTimeout = setTimeout(function () {- reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));- finalize();- }, request.timeout);- });- }-- req.on('error', function (err) {- reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));- finalize();- });-- req.on('response', function (res) {- clearTimeout(reqTimeout);-- const headers = createHeadersLenient(res.headers);-- // HTTP fetch step 5- if (fetch.isRedirect(res.statusCode)) {- // HTTP fetch step 5.2- const location = headers.get('Location');-- // HTTP fetch step 5.3- const locationURL = location === null ? null : resolve_url(request.url, location);-- // HTTP fetch step 5.5- switch (request.redirect) {- case 'error':- reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));- finalize();- return;- case 'manual':- // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.- if (locationURL !== null) {- // handle corrupted header- try {- headers.set('Location', locationURL);- } catch (err) {- // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request- reject(err);- }- }- break;- case 'follow':- // HTTP-redirect fetch step 2- if (locationURL === null) {- break;- }-- // HTTP-redirect fetch step 5- if (request.counter >= request.follow) {- reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));- finalize();- return;- }-- // HTTP-redirect fetch step 6 (counter increment)- // Create a new Request object.- const requestOpts = {- headers: new Headers(request.headers),- follow: request.follow,- counter: request.counter + 1,- agent: request.agent,- compress: request.compress,- method: request.method,- body: request.body,- signal: request.signal,- timeout: request.timeout- };-- // HTTP-redirect fetch step 9- if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {- reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));- finalize();- return;- }-- // HTTP-redirect fetch step 11- if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {- requestOpts.method = 'GET';- requestOpts.body = undefined;- requestOpts.headers.delete('content-length');- }-- // HTTP-redirect fetch step 15- resolve(fetch(new Request(locationURL, requestOpts)));- finalize();- return;- }- }-- // prepare response- res.once('end', function () {- if (signal) signal.removeEventListener('abort', abortAndFinalize);- });- let body = res.pipe(new PassThrough$1$1());-- const response_options = {- url: request.url,- status: res.statusCode,- statusText: res.statusMessage,- headers: headers,- size: request.size,- timeout: request.timeout,- counter: request.counter- };-- // HTTP-network fetch step 12.1.1.3- const codings = headers.get('Content-Encoding');-- // HTTP-network fetch step 12.1.1.4: handle content codings-- // in following scenarios we ignore compression support- // 1. compression support is disabled- // 2. HEAD request- // 3. no Content-Encoding header- // 4. no content response (204)- // 5. content not modified response (304)- if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {- response = new Response(body, response_options);- resolve(response);- return;- }-- // For Node v6+- // Be less strict when decoding compressed responses, since sometimes- // servers send slightly invalid responses that are still accepted- // by common browsers.- // Always using Z_SYNC_FLUSH is what cURL does.- const zlibOptions = {- flush: zlib.Z_SYNC_FLUSH,- finishFlush: zlib.Z_SYNC_FLUSH- };-- // for gzip- if (codings == 'gzip' || codings == 'x-gzip') {- body = body.pipe(zlib.createGunzip(zlibOptions));- response = new Response(body, response_options);- resolve(response);- return;- }-- // for deflate- if (codings == 'deflate' || codings == 'x-deflate') {- // handle the infamous raw deflate response from old servers- // a hack for old IIS and Apache servers- const raw = res.pipe(new PassThrough$1$1());- raw.once('data', function (chunk) {- // see http://stackoverflow.com/questions/37519828- if ((chunk[0] & 0x0F) === 0x08) {- body = body.pipe(zlib.createInflate());- } else {- body = body.pipe(zlib.createInflateRaw());- }- response = new Response(body, response_options);- resolve(response);- });- return;- }-- // for br- if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {- body = body.pipe(zlib.createBrotliDecompress());- response = new Response(body, response_options);- resolve(response);- return;- }-- // otherwise, use response as-is- response = new Response(body, response_options);- resolve(response);- });-- writeToStream(req, request);- });-}-/**- * Redirect code matching- *- * @param Number code Status code- * @return Boolean- */-fetch.isRedirect = function (code) {- return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;-};--// expose Promise-fetch.Promise = global.Promise;--var lib$1 = /*#__PURE__*/Object.freeze({- __proto__: null,- 'default': fetch,- Headers: Headers,- Request: Request,- Response: Response,- FetchError: FetchError-});--var nodePonyfill = createCommonjsModule(function (module, exports) {-var realFetch = lib$1.default || lib$1;--var fetch = function (url, options) {- // Support schemaless URIs on the server for parity with the browser.- // Ex: //github.com/ -> https://github.com/- if (/^\/\//.test(url)) {- url = 'https:' + url;- }- return realFetch.call(this, url, options)-};--module.exports = exports = fetch;-exports.fetch = fetch;-exports.Headers = lib$1.Headers;-exports.Request = lib$1.Request;-exports.Response = lib$1.Response;--// Needed for TypeScript consumers without esModuleInterop.-exports.default = fetch;-});--var isPromise_1 = isPromise$1;-var _default$1 = isPromise$1;--function isPromise$1(obj) {- return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';-}-isPromise_1.default = _default$1;--const OBJECT_SUBSCHEMA_SYMBOL = Symbol('initialSubschema');-const FIELD_SUBSCHEMA_MAP_SYMBOL = Symbol('subschemaMap');--function getSubschema(result, responseKey) {- const subschema = result[FIELD_SUBSCHEMA_MAP_SYMBOL] && result[FIELD_SUBSCHEMA_MAP_SYMBOL][responseKey];- return subschema || result[OBJECT_SUBSCHEMA_SYMBOL];-}-function setObjectSubschema(result, subschema) {- result[OBJECT_SUBSCHEMA_SYMBOL] = subschema;-}-function isSubschemaConfig(value) {- return Boolean(value.schema);-}--function getDelegatingOperation(parentType, schema) {- if (parentType === schema.getMutationType()) {- return 'mutation';- }- else if (parentType === schema.getSubscriptionType()) {- return 'subscription';- }- return 'query';-}-function createRequestFromInfo({ info, operationName, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, selectionSet, fieldNodes = info.fieldNodes, }) {- return createRequest({- sourceSchema: info.schema,- sourceParentType: info.parentType,- sourceFieldName: info.fieldName,- fragments: info.fragments,- variableDefinitions: info.operation.variableDefinitions,- variableValues: info.variableValues,- targetOperationName: operationName,- targetOperation: operation,- targetFieldName: fieldName,- selectionSet,- fieldNodes,- });-}-function createRequest({ sourceSchema, sourceParentType, sourceFieldName, fragments, variableDefinitions, variableValues, targetOperationName, targetOperation, targetFieldName, selectionSet, fieldNodes, }) {- var _a;- let newSelectionSet;- let argumentNodeMap;- if (selectionSet != null) {- newSelectionSet = selectionSet;- argumentNodeMap = Object.create(null);- }- else {- const selections = fieldNodes.reduce((acc, fieldNode) => (fieldNode.selectionSet != null ? acc.concat(fieldNode.selectionSet.selections) : acc), []);- newSelectionSet = selections.length- ? {- kind: Kind.SELECTION_SET,- selections,- }- : undefined;- argumentNodeMap = {};- const args = (_a = fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments;- if (args) {- argumentNodeMap = args.reduce((prev, curr) => ({- ...prev,- [curr.name.value]: curr,- }), argumentNodeMap);- }- }- const newVariables = Object.create(null);- const variableDefinitionMap = Object.create(null);- if (sourceSchema != null && variableDefinitions != null) {- variableDefinitions.forEach(def => {- const varName = def.variable.name.value;- variableDefinitionMap[varName] = def;- const varType = typeFromAST(sourceSchema, def.type);- const serializedValue = serializeInputValue(varType, variableValues[varName]);- if (serializedValue !== undefined) {- newVariables[varName] = serializedValue;- }- });- }- if (sourceParentType != null) {- updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, newVariables);- }- const rootfieldNode = {- kind: Kind.FIELD,- arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),- name: {- kind: Kind.NAME,- value: targetFieldName || fieldNodes[0].name.value,- },- selectionSet: newSelectionSet,- };- const operationName = targetOperationName- ? {- kind: Kind.NAME,- value: targetOperationName,- }- : undefined;- const operationDefinition = {- kind: Kind.OPERATION_DEFINITION,- name: operationName,- operation: targetOperation,- variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),- selectionSet: {- kind: Kind.SELECTION_SET,- selections: [rootfieldNode],- },- };- let definitions = [operationDefinition];- if (fragments != null) {- definitions = definitions.concat(Object.keys(fragments).map(fragmentName => fragments[fragmentName]));- }- const document = {- kind: Kind.DOCUMENT,- definitions,- };- return {- document,- variables: newVariables,- };-}-function updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, variableValues) {- const sourceField = sourceParentType.getFields()[sourceFieldName];- sourceField.args.forEach((argument) => {- const argName = argument.name;- const sourceArgType = argument.type;- if (argumentNodeMap[argName] === undefined) {- const defaultValue = argument.defaultValue;- if (defaultValue !== undefined) {- updateArgument(argName, sourceArgType, argumentNodeMap, variableDefinitionMap, variableValues, serializeInputValue(sourceArgType, defaultValue));- }- }- });-}--function memoizeInfoAnd2Objects(fn) {- let cache1;- function memoized(a1, a2, a3) {- if (!cache1) {- cache1 = new WeakMap();- const cache2 = new WeakMap();- cache1.set(a1.fieldNodes, cache2);- const cache3 = new WeakMap();- cache2.set(a2, cache3);- const newValue = fn(a1, a2, a3);- cache3.set(a3, newValue);- return newValue;- }- let cache2 = cache1.get(a1.fieldNodes);- if (!cache2) {- cache2 = new WeakMap();- cache1.set(a1.fieldNodes, cache2);- const cache3 = new WeakMap();- cache2.set(a2, cache3);- const newValue = fn(a1, a2, a3);- cache3.set(a3, newValue);- return newValue;- }- let cache3 = cache2.get(a2);- if (!cache3) {- cache3 = new WeakMap();- cache2.set(a2, cache3);- const newValue = fn(a1, a2, a3);- cache3.set(a3, newValue);- return newValue;- }- const cachedValue = cache3.get(a3);- if (cachedValue === undefined) {- const newValue = fn(a1, a2, a3);- cache3.set(a3, newValue);- return newValue;- }- return cachedValue;- }- return memoized;-}-function memoize4(fn) {- let cache1;- function memoized(a1, a2, a3, a4) {- if (!cache1) {- cache1 = new WeakMap();- const cache2 = new WeakMap();- cache1.set(a1, cache2);- const cache3 = new WeakMap();- cache2.set(a2, cache3);- const cache4 = new WeakMap();- cache3.set(a3, cache4);- const newValue = fn(a1, a2, a3, a4);- cache4.set(a4, newValue);- return newValue;- }- let cache2 = cache1.get(a1);- if (!cache2) {- cache2 = new WeakMap();- cache1.set(a1, cache2);- const cache3 = new WeakMap();- cache2.set(a2, cache3);- const cache4 = new WeakMap();- cache3.set(a3, cache4);- const newValue = fn(a1, a2, a3, a4);- cache4.set(a4, newValue);- return newValue;- }- let cache3 = cache2.get(a2);- if (!cache3) {- cache3 = new WeakMap();- cache2.set(a2, cache3);- const cache4 = new WeakMap();- cache3.set(a3, cache4);- const newValue = fn(a1, a2, a3, a4);- cache4.set(a4, newValue);- return newValue;- }- const cache4 = cache3.get(a3);- if (!cache4) {- const cache4 = new WeakMap();- cache3.set(a3, cache4);- const newValue = fn(a1, a2, a3, a4);- cache4.set(a4, newValue);- return newValue;- }- const cachedValue = cache4.get(a4);- if (cachedValue === undefined) {- const newValue = fn(a1, a2, a3, a4);- cache4.set(a4, newValue);- return newValue;- }- return cachedValue;- }- return memoized;-}-function memoize3$1(fn) {- let cache1;- function memoized(a1, a2, a3) {- if (!cache1) {- cache1 = new WeakMap();- const cache2 = new WeakMap();- cache1.set(a1, cache2);- const cache3 = new WeakMap();- cache2.set(a2, cache3);- const newValue = fn(a1, a2, a3);- cache3.set(a3, newValue);- return newValue;- }- let cache2 = cache1.get(a1);- if (!cache2) {- cache2 = new WeakMap();- cache1.set(a1, cache2);- const cache3 = new WeakMap();- cache2.set(a2, cache3);- const newValue = fn(a1, a2, a3);- cache3.set(a3, newValue);- return newValue;- }- let cache3 = cache2.get(a2);- if (!cache3) {- cache3 = new WeakMap();- cache2.set(a2, cache3);- const newValue = fn(a1, a2, a3);- cache3.set(a3, newValue);- return newValue;- }- const cachedValue = cache3.get(a3);- if (cachedValue === undefined) {- const newValue = fn(a1, a2, a3);- cache3.set(a3, newValue);- return newValue;- }- return cachedValue;- }- return memoized;-}-function memoize2(fn) {- let cache1;- function memoized(a1, a2) {- if (!cache1) {- cache1 = new WeakMap();- const cache2 = new WeakMap();- cache1.set(a1, cache2);- const newValue = fn(a1, a2);- cache2.set(a2, newValue);- return newValue;- }- let cache2 = cache1.get(a1);- if (!cache2) {- cache2 = new WeakMap();- cache1.set(a1, cache2);- const newValue = fn(a1, a2);- cache2.set(a2, newValue);- return newValue;- }- const cachedValue = cache2.get(a2);- if (cachedValue === undefined) {- const newValue = fn(a1, a2);- cache2.set(a2, newValue);- return newValue;- }- return cachedValue;- }- return memoized;-}--class VisitSelectionSets {- constructor(schema, initialType, visitor) {- this.schema = schema;- this.initialType = initialType;- this.visitor = visitor;- }- transformRequest(originalRequest) {- const document = visitSelectionSets(originalRequest, this.schema, this.initialType, this.visitor);- return {- ...originalRequest,- document,- };- }-}-function visitSelectionSets(request, schema, initialType, visitor) {- const { document, variables } = request;- const operations = [];- const fragments = Object.create(null);- document.definitions.forEach(def => {- if (def.kind === Kind.OPERATION_DEFINITION) {- operations.push(def);- }- else if (def.kind === Kind.FRAGMENT_DEFINITION) {- fragments[def.name.value] = def;- }- });- const partialExecutionContext = {- schema,- variableValues: variables,- fragments,- };- const typeInfo = new TypeInfo(schema, undefined, initialType);- const newDefinitions = operations.map(operation => {- const type = operation.operation === 'query'- ? schema.getQueryType()- : operation.operation === 'mutation'- ? schema.getMutationType()- : schema.getSubscriptionType();- const fields = collectFields$1(partialExecutionContext, type, operation.selectionSet, Object.create(null), Object.create(null));- const newSelections = [];- Object.keys(fields).forEach(responseKey => {- const fieldNodes = fields[responseKey];- fieldNodes.forEach(fieldNode => {- const selectionSet = fieldNode.selectionSet;- if (selectionSet == null) {- newSelections.push(fieldNode);- return;- }- const newSelectionSet = visit(selectionSet, visitWithTypeInfo(typeInfo, {- [Kind.SELECTION_SET]: node => visitor(node, typeInfo),- }));- if (newSelectionSet === selectionSet) {- newSelections.push(fieldNode);- return;- }- newSelections.push({- ...fieldNode,- selectionSet: newSelectionSet,- });- });- });- return {- ...operation,- selectionSet: {- kind: Kind.SELECTION_SET,- selections: newSelections,- },- };- });- Object.values(fragments).forEach(fragment => {- newDefinitions.push(visit(fragment, visitWithTypeInfo(typeInfo, {- [Kind.SELECTION_SET]: node => visitor(node, typeInfo),- })));- });- return {- ...document,- definitions: newDefinitions,- };-}--class AddSelectionSets {- constructor(sourceSchema, initialType, selectionSetsByType, selectionSetsByField, dynamicSelectionSetsByField) {- this.transformer = new VisitSelectionSets(sourceSchema, initialType, (node, typeInfo) => visitSelectionSet(node, typeInfo, selectionSetsByType, selectionSetsByField, dynamicSelectionSetsByField));- }- transformRequest(originalRequest) {- return this.transformer.transformRequest(originalRequest);- }-}-function visitSelectionSet(node, typeInfo, selectionSetsByType, selectionSetsByField, dynamicSelectionSetsByField) {- const parentType = typeInfo.getParentType();- const newSelections = new Map();- if (parentType != null) {- const parentTypeName = parentType.name;- addSelectionsToMap(newSelections, node);- if (parentTypeName in selectionSetsByType) {- const selectionSet = selectionSetsByType[parentTypeName];- addSelectionsToMap(newSelections, selectionSet);- }- if (parentTypeName in selectionSetsByField) {- node.selections.forEach(selection => {- if (selection.kind === Kind.FIELD) {- const name = selection.name.value;- const selectionSet = selectionSetsByField[parentTypeName][name];- if (selectionSet != null) {- addSelectionsToMap(newSelections, selectionSet);- }- }- });- }- if (parentTypeName in dynamicSelectionSetsByField) {- node.selections.forEach(selection => {- if (selection.kind === Kind.FIELD) {- const name = selection.name.value;- const dynamicSelectionSets = dynamicSelectionSetsByField[parentTypeName][name];- if (dynamicSelectionSets != null) {- dynamicSelectionSets.forEach(selectionSetFn => {- const selectionSet = selectionSetFn(selection);- if (selectionSet != null) {- addSelectionsToMap(newSelections, selectionSet);- }- });- }- }- });- }- return {- ...node,- selections: Array.from(newSelections.values()),- };- }-}-const addSelectionsToMap = memoize2(function (map, selectionSet) {- selectionSet.selections.forEach(selection => {- map.set(print(selection), selection);- });-});--class ExpandAbstractTypes {- constructor(sourceSchema, targetSchema) {- this.targetSchema = targetSchema;- this.mapping = extractPossibleTypes(sourceSchema, targetSchema);- this.reverseMapping = flipMapping(this.mapping);- }- transformRequest(originalRequest) {- const document = expandAbstractTypes(this.targetSchema, this.mapping, this.reverseMapping, originalRequest.document);- return {- ...originalRequest,- document,- };- }-}-function extractPossibleTypes(sourceSchema, targetSchema) {- const typeMap = sourceSchema.getTypeMap();- const mapping = Object.create(null);- Object.keys(typeMap).forEach(typeName => {- const type = typeMap[typeName];- if (isAbstractType(type)) {- const targetType = targetSchema.getType(typeName);- if (!isAbstractType(targetType)) {- const implementations = sourceSchema.getPossibleTypes(type);- mapping[typeName] = implementations.filter(impl => targetSchema.getType(impl.name)).map(impl => impl.name);- }- }- });- return mapping;-}-function flipMapping(mapping) {- const result = Object.create(null);- Object.keys(mapping).forEach(typeName => {- const toTypeNames = mapping[typeName];- toTypeNames.forEach(toTypeName => {- if (!(toTypeName in result)) {- result[toTypeName] = [];- }- result[toTypeName].push(typeName);- });- });- return result;-}-function expandAbstractTypes(targetSchema, mapping, reverseMapping, document) {- const operations = document.definitions.filter(def => def.kind === Kind.OPERATION_DEFINITION);- const fragments = document.definitions.filter(def => def.kind === Kind.FRAGMENT_DEFINITION);- const existingFragmentNames = fragments.map(fragment => fragment.name.value);- let fragmentCounter = 0;- const generateFragmentName = (typeName) => {- let fragmentName;- do {- fragmentName = `_${typeName}_Fragment${fragmentCounter.toString()}`;- fragmentCounter++;- } while (existingFragmentNames.indexOf(fragmentName) !== -1);- return fragmentName;- };- const newFragments = [];- const fragmentReplacements = Object.create(null);- fragments.forEach((fragment) => {- newFragments.push(fragment);- const possibleTypes = mapping[fragment.typeCondition.name.value];- if (possibleTypes != null) {- fragmentReplacements[fragment.name.value] = [];- possibleTypes.forEach(possibleTypeName => {- const name = generateFragmentName(possibleTypeName);- existingFragmentNames.push(name);- const newFragment = {- kind: Kind.FRAGMENT_DEFINITION,- name: {- kind: Kind.NAME,- value: name,- },- typeCondition: {- kind: Kind.NAMED_TYPE,- name: {- kind: Kind.NAME,- value: possibleTypeName,- },- },- selectionSet: fragment.selectionSet,- };- newFragments.push(newFragment);- fragmentReplacements[fragment.name.value].push({- fragmentName: name,- typeName: possibleTypeName,- });- });- }- });- const newDocument = {- ...document,- definitions: [...operations, ...newFragments],- };- const typeInfo = new TypeInfo(targetSchema);- return visit(newDocument, visitWithTypeInfo(typeInfo, {- [Kind.SELECTION_SET](node) {- const newSelections = [...node.selections];- const maybeType = typeInfo.getParentType();- if (maybeType != null) {- const parentType = getNamedType(maybeType);- node.selections.forEach((selection) => {- if (selection.kind === Kind.INLINE_FRAGMENT) {- if (selection.typeCondition != null) {- const possibleTypes = mapping[selection.typeCondition.name.value];- if (possibleTypes != null) {- possibleTypes.forEach(possibleType => {- const maybePossibleType = targetSchema.getType(possibleType);- if (maybePossibleType != null &&- implementsAbstractType(targetSchema, parentType, maybePossibleType)) {- newSelections.push({- kind: Kind.INLINE_FRAGMENT,- typeCondition: {- kind: Kind.NAMED_TYPE,- name: {- kind: Kind.NAME,- value: possibleType,- },- },- selectionSet: selection.selectionSet,- });- }- });- }- }- }- else if (selection.kind === Kind.FRAGMENT_SPREAD) {- const fragmentName = selection.name.value;- if (fragmentName in fragmentReplacements) {- fragmentReplacements[fragmentName].forEach(replacement => {- const typeName = replacement.typeName;- const maybeReplacementType = targetSchema.getType(typeName);- if (maybeReplacementType != null && implementsAbstractType(targetSchema, parentType, maybeType)) {- newSelections.push({- kind: Kind.FRAGMENT_SPREAD,- name: {- kind: Kind.NAME,- value: replacement.fragmentName,- },- });- }- });- }- }- });- if (parentType.name in reverseMapping) {- newSelections.push({- kind: Kind.FIELD,- name: {- kind: Kind.NAME,- value: '__typename',- },- });- }- }- if (newSelections.length !== node.selections.length) {- return {- ...node,- selections: newSelections,- };- }- },- }));-}--// For motivation, see https://github.com/ardatan/graphql-tools/issues/751-class WrapConcreteTypes {- constructor(returnType, targetSchema) {- this.returnType = returnType;- this.targetSchema = targetSchema;- }- transformRequest(originalRequest) {- const document = wrapConcreteTypes(this.returnType, this.targetSchema, originalRequest.document);- return {- ...originalRequest,- document,- };- }-}-function wrapConcreteTypes(returnType, targetSchema, document) {- const namedType = getNamedType(returnType);- if (!isObjectType(namedType)) {- return document;- }- const queryRootType = targetSchema.getQueryType();- const mutationRootType = targetSchema.getMutationType();- const subscriptionRootType = targetSchema.getSubscriptionType();- const typeInfo = new TypeInfo(targetSchema);- const newDocument = visit(document, visitWithTypeInfo(typeInfo, {- [Kind.FIELD](node) {- const maybeType = typeInfo.getParentType();- if (maybeType == null) {- return false;- }- const parentType = getNamedType(maybeType);- if (parentType !== queryRootType && parentType !== mutationRootType && parentType !== subscriptionRootType) {- return false;- }- if (!isAbstractType(getNamedType(typeInfo.getType()))) {- return false;- }- return {- ...node,- selectionSet: {- kind: Kind.SELECTION_SET,- selections: [- {- kind: Kind.INLINE_FRAGMENT,- typeCondition: {- kind: Kind.NAMED_TYPE,- name: {- kind: Kind.NAME,- value: namedType.name,- },- },- selectionSet: node.selectionSet,- },- ],- },- };- },- }));- return newDocument;-}--class FilterToSchema {- constructor(targetSchema) {- this.targetSchema = targetSchema;- }- transformRequest(originalRequest) {- return {- ...originalRequest,- ...filterToSchema(this.targetSchema, originalRequest.document, originalRequest.variables),- };- }-}-function filterToSchema(targetSchema, document, variables) {- const operations = document.definitions.filter(def => def.kind === Kind.OPERATION_DEFINITION);- const fragments = document.definitions.filter(def => def.kind === Kind.FRAGMENT_DEFINITION);- let usedVariables = [];- let usedFragments = [];- const newOperations = [];- let newFragments = [];- const validFragments = fragments.filter((fragment) => {- const typeName = fragment.typeCondition.name.value;- return Boolean(targetSchema.getType(typeName));- });- const validFragmentsWithType = validFragments.reduce((prev, fragment) => ({- ...prev,- [fragment.name.value]: targetSchema.getType(fragment.typeCondition.name.value),- }), {});- let fragmentSet = Object.create(null);- operations.forEach((operation) => {- let type;- if (operation.operation === 'subscription') {- type = targetSchema.getSubscriptionType();- }- else if (operation.operation === 'mutation') {- type = targetSchema.getMutationType();- }- else {- type = targetSchema.getQueryType();- }- const { selectionSet, usedFragments: operationUsedFragments, usedVariables: operationUsedVariables, } = filterSelectionSet(targetSchema, type, validFragmentsWithType, operation.selectionSet);- usedFragments = union(usedFragments, operationUsedFragments);- const { usedVariables: collectedUsedVariables, newFragments: collectedNewFragments, fragmentSet: collectedFragmentSet, } = collectFragmentVariables(targetSchema, fragmentSet, validFragments, validFragmentsWithType, usedFragments);- const operationOrFragmentVariables = union(operationUsedVariables, collectedUsedVariables);- usedVariables = union(usedVariables, operationOrFragmentVariables);- newFragments = collectedNewFragments;- fragmentSet = collectedFragmentSet;- const variableDefinitions = operation.variableDefinitions.filter((variable) => operationOrFragmentVariables.indexOf(variable.variable.name.value) !== -1);- newOperations.push({- kind: Kind.OPERATION_DEFINITION,- operation: operation.operation,- name: operation.name,- directives: operation.directives,- variableDefinitions,- selectionSet,- });- });- const newVariables = usedVariables.reduce((acc, variableName) => {- const variableValue = variables[variableName];- if (variableValue !== undefined) {- acc[variableName] = variableValue;- }- return acc;- }, {});- return {- document: {- kind: Kind.DOCUMENT,- definitions: [...newOperations, ...newFragments],- },- variables: newVariables,- };-}-function collectFragmentVariables(targetSchema, fragmentSet, validFragments, validFragmentsWithType, usedFragments) {- let remainingFragments = usedFragments.slice();- let usedVariables = [];- const newFragments = [];- while (remainingFragments.length !== 0) {- const nextFragmentName = remainingFragments.pop();- const fragment = validFragments.find(fr => fr.name.value === nextFragmentName);- if (fragment != null) {- const name = nextFragmentName;- const typeName = fragment.typeCondition.name.value;- const type = targetSchema.getType(typeName);- const { selectionSet, usedFragments: fragmentUsedFragments, usedVariables: fragmentUsedVariables, } = filterSelectionSet(targetSchema, type, validFragmentsWithType, fragment.selectionSet);- remainingFragments = union(remainingFragments, fragmentUsedFragments);- usedVariables = union(usedVariables, fragmentUsedVariables);- if (!(name in fragmentSet)) {- fragmentSet[name] = true;- newFragments.push({- kind: Kind.FRAGMENT_DEFINITION,- name: {- kind: Kind.NAME,- value: name,- },- typeCondition: fragment.typeCondition,- selectionSet,- });- }- }- }- return {- usedVariables,- newFragments,- fragmentSet,- };-}-function filterSelectionSet(schema, type, validFragments, selectionSet) {- const usedFragments = [];- const usedVariables = [];- const typeInfo = new TypeInfo(schema, undefined, type);- const filteredSelectionSet = visit(selectionSet, visitWithTypeInfo(typeInfo, {- [Kind.FIELD]: {- enter(node) {- const parentType = typeInfo.getParentType();- if (isObjectType(parentType) || isInterfaceType(parentType)) {- const fields = parentType.getFields();- const field = node.name.value === '__typename' ? TypeNameMetaFieldDef : fields[node.name.value];- if (!field) {- return null;- }- const argNames = (field.args != null ? field.args : []).map(arg => arg.name);- if (node.arguments != null) {- const args = node.arguments.filter((arg) => argNames.indexOf(arg.name.value) !== -1);- if (args.length !== node.arguments.length) {- return {- ...node,- arguments: args,- };- }- }- }- },- leave(node) {- const resolvedType = getNamedType(typeInfo.getType());- if (isObjectType(resolvedType) || isInterfaceType(resolvedType)) {- const selections = node.selectionSet != null ? node.selectionSet.selections : null;- if (selections == null || selections.length === 0) {- // need to remove any added variables. Is there a better way to do this?- visit(node, {- [Kind.VARIABLE](variableNode) {- const index = usedVariables.indexOf(variableNode.name.value);- if (index !== -1) {- usedVariables.splice(index, 1);- }- },- });- return null;- }- }- },- },- [Kind.FRAGMENT_SPREAD](node) {- if (node.name.value in validFragments) {- const parentType = typeInfo.getParentType();- const innerType = validFragments[node.name.value];- if (!implementsAbstractType(schema, parentType, innerType)) {- return null;- }- usedFragments.push(node.name.value);- return;- }- return null;- },- [Kind.INLINE_FRAGMENT]: {- enter(node) {- if (node.typeCondition != null) {- const parentType = typeInfo.getParentType();- const innerType = schema.getType(node.typeCondition.name.value);- if (!implementsAbstractType(schema, parentType, innerType)) {- return null;- }- }- },- },- [Kind.VARIABLE](node) {- usedVariables.push(node.name.value);- },- }));- return {- selectionSet: filteredSelectionSet,- usedFragments,- usedVariables,- };-}-function union(...arrays) {- const cache = Object.create(null);- const result = [];- arrays.forEach(array => {- array.forEach(item => {- if (!(item in cache)) {- cache[item] = true;- result.push(item);- }- });- });- return result;-}--class AddFragmentsByField {- constructor(targetSchema, mapping) {- this.targetSchema = targetSchema;- this.mapping = mapping;- }- transformRequest(originalRequest) {- const document = addFragmentsByField(this.targetSchema, originalRequest.document, this.mapping);- return {- ...originalRequest,- document,- };- }-}-function addFragmentsByField(targetSchema, document, mapping) {- const typeInfo = new TypeInfo(targetSchema);- return visit(document, visitWithTypeInfo(typeInfo, {- [Kind.SELECTION_SET](node) {- const parentType = typeInfo.getParentType();- if (parentType != null) {- const parentTypeName = parentType.name;- let selections = node.selections;- if (parentTypeName in mapping) {- node.selections.forEach(selection => {- if (selection.kind === Kind.FIELD) {- const name = selection.name.value;- const fragment = mapping[parentTypeName][name];- if (fragment != null) {- selections = selections.concat(fragment);- }- }- });- }- if (selections !== node.selections) {- return {- ...node,- selections,- };- }- }- },- }));-}--class AddTypenameToAbstract {- constructor(targetSchema) {- this.targetSchema = targetSchema;- }- transformRequest(originalRequest) {- const document = addTypenameToAbstract(this.targetSchema, originalRequest.document);- return {- ...originalRequest,- document,- };- }-}-function addTypenameToAbstract(targetSchema, document) {- const typeInfo = new TypeInfo(targetSchema);- return visit(document, visitWithTypeInfo(typeInfo, {- [Kind.SELECTION_SET](node) {- const parentType = typeInfo.getParentType();- let selections = node.selections;- if (parentType != null && isAbstractType(parentType)) {- selections = selections.concat({- kind: Kind.FIELD,- name: {- kind: Kind.NAME,- value: '__typename',- },- });- }- if (selections !== node.selections) {- return {- ...node,- selections,- };- }- },- }));-}--function handleNull(errors) {- if (errors.length) {- if (errors.some(error => !error.path || error.path.length < 2)) {- if (errors.length > 1) {- const combinedError = new AggregateError(errors);- return combinedError;- }- const error = errors[0];- return error.originalError || relocatedError(error, null);- }- else if (errors.some(error => typeof error.path[1] === 'string')) {- const childErrors = getErrorsByPathSegment(errors);- const result = {};- Object.keys(childErrors).forEach(pathSegment => {- result[pathSegment] = handleNull(childErrors[pathSegment]);- });- return result;- }- const childErrors = getErrorsByPathSegment(errors);- const result = [];- Object.keys(childErrors).forEach(pathSegment => {- result.push(handleNull(childErrors[pathSegment]));- });- return result;- }- return null;-}--function mergeProxiedResults(target, ...sources) {- const results = sources.filter(source => !(source instanceof Error));- const fieldSubschemaMap = results.reduce((acc, source) => {- const subschema = source[OBJECT_SUBSCHEMA_SYMBOL];- Object.keys(source).forEach(key => {- acc[key] = subschema;- });- return acc;- }, {});- const result = results.reduce(mergeDeep, target);- result[FIELD_SUBSCHEMA_MAP_SYMBOL] = target[FIELD_SUBSCHEMA_MAP_SYMBOL]- ? Object.assign({}, target[FIELD_SUBSCHEMA_MAP_SYMBOL], fieldSubschemaMap)- : fieldSubschemaMap;- const errors = sources.map((source) => (source instanceof Error ? source : source[ERROR_SYMBOL]));- result[ERROR_SYMBOL] = target[ERROR_SYMBOL].concat(...errors);- return result;-}--const sortSubschemasByProxiability = memoize4(function (mergedTypeInfo, sourceSubschemaOrSourceSubschemas, targetSubschemas, fieldNodes) {- // 1. calculate if possible to delegate to given subschema- const proxiableSubschemas = [];- const nonProxiableSubschemas = [];- const sourceSubschemas = Array.isArray(sourceSubschemaOrSourceSubschemas)- ? sourceSubschemaOrSourceSubschemas- : [sourceSubschemaOrSourceSubschemas];- const typeName = mergedTypeInfo.typeName;- const types = sourceSubschemas.map(sourceSubschema => sourceSubschema.schema.getType(typeName));- targetSubschemas.forEach(t => {- const selectionSet = mergedTypeInfo.selectionSets.get(t);- const fieldSelectionSets = mergedTypeInfo.fieldSelectionSets.get(t);- if (!typesContainSelectionSet(types, selectionSet)) {- nonProxiableSubschemas.push(t);- }- else if (fieldSelectionSets == null) {- proxiableSubschemas.push(t);- }- else if (fieldNodes.every(fieldNode => {- const fieldName = fieldNode.name.value;- const fieldSelectionSet = fieldSelectionSets[fieldName];- return fieldSelectionSet == null || typesContainSelectionSet(types, fieldSelectionSet);- })) {- proxiableSubschemas.push(t);- }- else {- nonProxiableSubschemas.push(t);- }- });- return {- proxiableSubschemas,- nonProxiableSubschemas,- };-});-const buildDelegationPlan = memoize3$1(function (mergedTypeInfo, fieldNodes, proxiableSubschemas) {- const { uniqueFields, nonUniqueFields } = mergedTypeInfo;- const unproxiableFieldNodes = [];- // 2. for each selection:- const delegationMap = new Map();- fieldNodes.forEach(fieldNode => {- if (fieldNode.name.value === '__typename') {- return;- }- // 2a. use uniqueFields map to assign fields to subschema if one of possible subschemas- const uniqueSubschema = uniqueFields[fieldNode.name.value];- if (uniqueSubschema != null) {- if (!proxiableSubschemas.includes(uniqueSubschema)) {- unproxiableFieldNodes.push(fieldNode);- return;- }- const existingSubschema = delegationMap.get(uniqueSubschema);- if (existingSubschema != null) {- existingSubschema.push(fieldNode);- }- else {- delegationMap.set(uniqueSubschema, [fieldNode]);- }- return;- }- // 2b. use nonUniqueFields to assign to a possible subschema,- // preferring one of the subschemas already targets of delegation- let nonUniqueSubschemas = nonUniqueFields[fieldNode.name.value];- if (nonUniqueSubschemas == null) {- unproxiableFieldNodes.push(fieldNode);- return;- }- nonUniqueSubschemas = nonUniqueSubschemas.filter(s => proxiableSubschemas.includes(s));- if (nonUniqueSubschemas == null) {- unproxiableFieldNodes.push(fieldNode);- return;- }- const subschemas = Array.from(delegationMap.keys());- const existingSubschema = nonUniqueSubschemas.find(s => subschemas.includes(s));- if (existingSubschema != null) {- delegationMap.get(existingSubschema).push(fieldNode);- }- else {- delegationMap.set(nonUniqueSubschemas[0], [fieldNode]);- }- });- const finalDelegationMap = new Map();- delegationMap.forEach((selections, subschema) => {- finalDelegationMap.set(subschema, {- kind: Kind.SELECTION_SET,- selections,- });- });- return {- delegationMap: finalDelegationMap,- unproxiableFieldNodes,- };-});-const combineSubschemas = memoize2(function (subschemaOrSubschemas, additionalSubschemas) {- return Array.isArray(subschemaOrSubschemas)- ? subschemaOrSubschemas.concat(additionalSubschemas)- : [subschemaOrSubschemas].concat(additionalSubschemas);-});-function mergeFields$2(mergedTypeInfo, typeName, object, fieldNodes, sourceSubschemaOrSourceSubschemas, targetSubschemas, context, info) {- if (!fieldNodes.length) {- return object;- }- const { proxiableSubschemas, nonProxiableSubschemas } = sortSubschemasByProxiability(mergedTypeInfo, sourceSubschemaOrSourceSubschemas, targetSubschemas, fieldNodes);- const { delegationMap, unproxiableFieldNodes } = buildDelegationPlan(mergedTypeInfo, fieldNodes, proxiableSubschemas);- if (!delegationMap.size) {- return object;- }- let containsPromises = false;- const maybePromises = [];- delegationMap.forEach((selectionSet, s) => {- const maybePromise = s.merge[typeName].resolve(object, context, info, s, selectionSet);- maybePromises.push(maybePromise);- if (!containsPromises && isPromise_1(maybePromise)) {- containsPromises = true;- }- });- return containsPromises- ? Promise.all(maybePromises).then(results => mergeFields$2(mergedTypeInfo, typeName, mergeProxiedResults(object, ...results), unproxiableFieldNodes, combineSubschemas(sourceSubschemaOrSourceSubschemas, proxiableSubschemas), nonProxiableSubschemas, context, info))- : mergeFields$2(mergedTypeInfo, typeName, mergeProxiedResults(object, ...maybePromises), unproxiableFieldNodes, combineSubschemas(sourceSubschemaOrSourceSubschemas, proxiableSubschemas), nonProxiableSubschemas, context, info);-}--function collectSubFields(info, typeName) {- let subFieldNodes = Object.create(null);- const visitedFragmentNames = Object.create(null);- const type = info.schema.getType(typeName);- const partialExecutionContext = {- schema: info.schema,- variableValues: info.variableValues,- fragments: info.fragments,- };- info.fieldNodes.forEach(fieldNode => {- subFieldNodes = collectFields$1(partialExecutionContext, type, fieldNode.selectionSet, subFieldNodes, visitedFragmentNames);- });- const stitchingInfo = info.schema.extensions.stitchingInfo;- const selectionSetsByField = stitchingInfo.selectionSetsByField;- Object.keys(subFieldNodes).forEach(responseName => {- var _a;- const fieldName = subFieldNodes[responseName][0].name.value;- const fieldSelectionSet = (_a = selectionSetsByField === null || selectionSetsByField === void 0 ? void 0 : selectionSetsByField[typeName]) === null || _a === void 0 ? void 0 : _a[fieldName];- if (fieldSelectionSet != null) {- subFieldNodes = collectFields$1(partialExecutionContext, type, fieldSelectionSet, subFieldNodes, visitedFragmentNames);- }- });- return subFieldNodes;-}-const getFieldsNotInSubschema = memoizeInfoAnd2Objects(function (info, subschema, mergedTypeInfo) {- const typeMap = isSubschemaConfig(subschema) ? mergedTypeInfo.typeMaps.get(subschema) : subschema.getTypeMap();- const typeName = mergedTypeInfo.typeName;- const fields = typeMap[typeName].getFields();- const subFieldNodes = collectSubFields(info, typeName);- let fieldsNotInSchema = [];- Object.keys(subFieldNodes).forEach(responseName => {- const fieldName = subFieldNodes[responseName][0].name.value;- if (!(fieldName in fields)) {- fieldsNotInSchema = fieldsNotInSchema.concat(subFieldNodes[responseName]);- }- });- return fieldsNotInSchema;-});--function handleObject(type, object, errors, subschema, context, info, skipTypeMerging) {- var _a;- const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;- setErrors(object, errors.map(error => slicedError(error)));- setObjectSubschema(object, subschema);- if (skipTypeMerging || !stitchingInfo) {- return object;- }- const typeName = isAbstractType(type) ? info.schema.getTypeMap()[object.__typename].name : type.name;- const mergedTypeInfo = stitchingInfo.mergedTypes[typeName];- let targetSubschemas;- if (mergedTypeInfo != null) {- targetSubschemas = mergedTypeInfo.targetSubschemas.get(subschema);- }- if (!targetSubschemas) {- return object;- }- const fieldNodes = getFieldsNotInSubschema(info, subschema, mergedTypeInfo);- return mergeFields$2(mergedTypeInfo, typeName, object, fieldNodes, subschema, targetSubschemas, context, info);-}--function handleList(type, list, errors, subschema, context, info, skipTypeMerging) {- const childErrors = getErrorsByPathSegment(errors);- return list.map((listMember, index) => handleListMember(getNullableType(type.ofType), listMember, index in childErrors ? childErrors[index] : [], subschema, context, info, skipTypeMerging));-}-function handleListMember(type, listMember, errors, subschema, context, info, skipTypeMerging) {- if (listMember == null) {- return handleNull(errors);- }- if (isLeafType(type)) {- return type.parseValue(listMember);- }- else if (isCompositeType(type)) {- return handleObject(type, listMember, errors, subschema, context, info, skipTypeMerging);- }- else if (isListType(type)) {- return handleList(type, listMember, errors, subschema, context, info, skipTypeMerging);- }-}--function handleResult(result, errors, subschema, context, info, returnType = info.returnType, skipTypeMerging) {- const type = getNullableType(returnType);- if (result == null) {- return handleNull(errors);- }- if (isLeafType(type)) {- return type.parseValue(result);- }- else if (isCompositeType(type)) {- return handleObject(type, result, errors, subschema, context, info, skipTypeMerging);- }- else if (isListType(type)) {- return handleList(type, result, errors, subschema, context, info, skipTypeMerging);- }-}--class CheckResultAndHandleErrors {- constructor(info, fieldName, subschema, context, returnType = info.returnType, typeMerge) {- this.context = context;- this.info = info;- this.fieldName = fieldName;- this.subschema = subschema;- this.returnType = returnType;- this.typeMerge = typeMerge;- }- transformResult(result) {- return checkResultAndHandleErrors(result, this.context != null ? this.context : {}, this.info, this.fieldName, this.subschema, this.returnType, this.typeMerge);- }-}-function checkResultAndHandleErrors(result, context, info, responseKey = getResponseKeyFromInfo(info), subschema, returnType = info.returnType, skipTypeMerging) {- const errors = result.errors != null ? result.errors : [];- const data = result.data != null ? result.data[responseKey] : undefined;- return handleResult(data, errors, subschema, context, info, returnType, skipTypeMerging);-}--class AddArgumentsAsVariables {- constructor(targetSchema, args) {- this.targetSchema = targetSchema;- this.args = Object.entries(args).reduce((prev, [key, val]) => ({- ...prev,- [key]: val,- }), {});- }- transformRequest(originalRequest) {- const { document, variables } = addVariablesToRootField(this.targetSchema, originalRequest, this.args);- return {- ...originalRequest,- document,- variables,- };- }-}-function addVariablesToRootField(targetSchema, originalRequest, args) {- const document = originalRequest.document;- const variableValues = originalRequest.variables;- const operations = document.definitions.filter(def => def.kind === Kind.OPERATION_DEFINITION);- const fragments = document.definitions.filter(def => def.kind === Kind.FRAGMENT_DEFINITION);- const newOperations = operations.map((operation) => {- const variableDefinitionMap = operation.variableDefinitions.reduce((prev, def) => ({- ...prev,- [def.variable.name.value]: def,- }), {});- let type;- if (operation.operation === 'subscription') {- type = targetSchema.getSubscriptionType();- }- else if (operation.operation === 'mutation') {- type = targetSchema.getMutationType();- }- else {- type = targetSchema.getQueryType();- }- const newSelectionSet = [];- operation.selectionSet.selections.forEach((selection) => {- if (selection.kind === Kind.FIELD) {- const argumentNodes = selection.arguments;- const argumentNodeMap = argumentNodes.reduce((prev, argument) => ({- ...prev,- [argument.name.value]: argument,- }), {});- const targetField = type.getFields()[selection.name.value];- // excludes __typename- if (targetField != null) {- updateArguments(targetField, argumentNodeMap, variableDefinitionMap, variableValues, args);- }- newSelectionSet.push({- ...selection,- arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),- });- }- else {- newSelectionSet.push(selection);- }- });- return {- ...operation,- variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),- selectionSet: {- kind: Kind.SELECTION_SET,- selections: newSelectionSet,- },- };- });- return {- document: {- ...document,- definitions: [...newOperations, ...fragments],- },- variables: variableValues,- };-}-function updateArguments(targetField, argumentNodeMap, variableDefinitionMap, variableValues, newArgs) {- targetField.args.forEach((argument) => {- const argName = argument.name;- const argType = argument.type;- if (argName in newArgs) {- updateArgument(argName, argType, argumentNodeMap, variableDefinitionMap, variableValues, serializeInputValue(argType, newArgs[argName]));- }- });-}--function defaultDelegationBinding(delegationContext) {- var _a;- const { subschema: schemaOrSubschemaConfig, targetSchema, fieldName, args, context, info, returnType, transforms = [], skipTypeMerging, } = delegationContext;- const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;- let transformedSchema = stitchingInfo === null || stitchingInfo === void 0 ? void 0 : stitchingInfo.transformedSchemas.get(schemaOrSubschemaConfig);- if (transformedSchema != null) {- delegationContext.transformedSchema = transformedSchema;- }- else {- transformedSchema = delegationContext.transformedSchema;- }- let delegationTransforms = [- new CheckResultAndHandleErrors(info, fieldName, schemaOrSubschemaConfig, context, returnType, skipTypeMerging),- ];- if (stitchingInfo != null) {- delegationTransforms = delegationTransforms.concat([- new AddSelectionSets(info.schema, returnType, {}, stitchingInfo.selectionSetsByField, stitchingInfo.dynamicSelectionSetsByField),- new WrapConcreteTypes(returnType, transformedSchema),- new ExpandAbstractTypes(info.schema, transformedSchema),- ]);- }- else if (info != null) {- delegationTransforms = delegationTransforms.concat([- new WrapConcreteTypes(returnType, transformedSchema),- new ExpandAbstractTypes(info.schema, transformedSchema),- ]);- }- else {- delegationTransforms.push(new WrapConcreteTypes(returnType, transformedSchema));- }- delegationTransforms = delegationTransforms.concat(transforms.slice().reverse());- if (stitchingInfo != null) {- delegationTransforms.push(new AddFragmentsByField(targetSchema, stitchingInfo.fragmentsByField));- }- if (args != null) {- delegationTransforms.push(new AddArgumentsAsVariables(targetSchema, args));- }- delegationTransforms = delegationTransforms.concat([- new FilterToSchema(targetSchema),- new AddTypenameToAbstract(targetSchema),- ]);- return delegationTransforms;-}--class Transformer {- constructor(context, binding = defaultDelegationBinding) {- this.transformations = [];- this.delegationContext = context;- const delegationTransforms = binding(this.delegationContext);- delegationTransforms.forEach(transform => this.addTransform(transform, {}));- }- addTransform(transform, context = {}) {- this.transformations.push({ transform, context });- }- transformRequest(originalRequest) {- return this.transformations.reduce((request, transformation) => transformation.transform.transformRequest != null- ? transformation.transform.transformRequest(request, this.delegationContext, transformation.context)- : request, originalRequest);- }- transformResult(originalResult) {- return this.transformations.reduceRight((result, transformation) => transformation.transform.transformResult != null- ? transformation.transform.transformResult(result, this.delegationContext, transformation.context)- : result, originalResult);- }-}--function delegateToSchema(options) {- if (isSchema(options)) {- throw new Error('Passing positional arguments to delegateToSchema is deprecated. ' + 'Please pass named parameters instead.');- }- const { info, operationName, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, returnType = info.returnType, selectionSet, fieldNodes, } = options;- const request = createRequestFromInfo({- info,- operation,- fieldName,- selectionSet,- fieldNodes,- operationName,- });- return delegateRequest({- ...options,- request,- operation,- fieldName,- returnType,- });-}-function getDelegationReturnType(targetSchema, operation, fieldName) {- let rootType;- if (operation === 'query') {- rootType = targetSchema.getQueryType();- }- else if (operation === 'mutation') {- rootType = targetSchema.getMutationType();- }- else {- rootType = targetSchema.getSubscriptionType();- }- return rootType.getFields()[fieldName].type;-}-function delegateRequest({ request, schema: subschemaOrSubschemaConfig, rootValue, info, operation, fieldName, args, returnType, context, transforms = [], transformedSchema, skipValidation, skipTypeMerging, binding, }) {- var _a, _b;- let operationDefinition;- let targetOperation;- let targetFieldName;- if (operation == null) {- operationDefinition = getOperationAST(request.document, undefined);- targetOperation = operationDefinition.operation;- }- else {- targetOperation = operation;- }- if (fieldName == null) {- operationDefinition = operationDefinition !== null && operationDefinition !== void 0 ? operationDefinition : getOperationAST(request.document, undefined);- targetFieldName = operationDefinition.selectionSet.selections[0].name.value;- }- else {- targetFieldName = fieldName;- }- let targetSchema;- let targetRootValue;- let subschemaConfig;- let allTransforms;- if (isSubschemaConfig(subschemaOrSubschemaConfig)) {- subschemaConfig = subschemaOrSubschemaConfig;- targetSchema = subschemaConfig.schema;- targetRootValue = (_a = rootValue !== null && rootValue !== void 0 ? rootValue : subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) !== null && _a !== void 0 ? _a : info === null || info === void 0 ? void 0 : info.rootValue;- allTransforms =- subschemaOrSubschemaConfig.transforms != null- ? subschemaOrSubschemaConfig.transforms.concat(transforms)- : transforms;- }- else {- targetSchema = subschemaOrSubschemaConfig;- targetRootValue = rootValue !== null && rootValue !== void 0 ? rootValue : info === null || info === void 0 ? void 0 : info.rootValue;- allTransforms = transforms;- }- const delegationContext = {- subschema: subschemaOrSubschemaConfig,- targetSchema,- operation: targetOperation,- fieldName: targetFieldName,- args,- context,- info,- returnType: (_b = returnType !== null && returnType !== void 0 ? returnType : info === null || info === void 0 ? void 0 : info.returnType) !== null && _b !== void 0 ? _b : getDelegationReturnType(targetSchema, targetOperation, targetFieldName),- transforms: allTransforms,- transformedSchema: transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : targetSchema,- skipTypeMerging,- };- const transformer = new Transformer(delegationContext, binding);- const processedRequest = transformer.transformRequest(request);- if (!skipValidation) {- validateRequest(targetSchema, processedRequest.document);- }- if (targetOperation === 'query' || targetOperation === 'mutation') {- const executor = (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.executor) || createDefaultExecutor(targetSchema, (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) || targetRootValue);- const executionResult = executor({- document: processedRequest.document,- variables: processedRequest.variables,- context,- info,- });- if (isPromise_1(executionResult)) {- return executionResult.then(originalResult => transformer.transformResult(originalResult));- }- return transformer.transformResult(executionResult);- }- const subscriber = (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.subscriber) || createDefaultSubscriber(targetSchema, (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) || targetRootValue);- return subscriber({- document: processedRequest.document,- variables: processedRequest.variables,- context,- info,- }).then((subscriptionResult) => {- if (Symbol.asyncIterator in subscriptionResult) {- // "subscribe" to the subscription result and map the result through the transforms- return mapAsyncIterator$1(subscriptionResult, originalResult => ({- [targetFieldName]: transformer.transformResult(originalResult),- }));- }- return transformer.transformResult(subscriptionResult);- });-}-function validateRequest(targetSchema, document) {- const errors = validate(targetSchema, document);- if (errors.length > 0) {- if (errors.length > 1) {- const combinedError = new AggregateError(errors);- throw combinedError;- }- const error = errors[0];- throw error.originalError || error;- }-}-function createDefaultExecutor(schema, rootValue) {- return ({ document, context, variables, info }) => execute({- schema,- document,- contextValue: context,- variableValues: variables,- rootValue: rootValue !== null && rootValue !== void 0 ? rootValue : info === null || info === void 0 ? void 0 : info.rootValue,- });-}-function createDefaultSubscriber(schema, rootValue) {- return ({ document, context, variables, info }) => subscribe({- schema,- document,- contextValue: context,- variableValues: variables,- rootValue: rootValue !== null && rootValue !== void 0 ? rootValue : info === null || info === void 0 ? void 0 : info.rootValue,- });-}--/**- * Resolver that knows how to:- * a) handle aliases for proxied schemas- * b) handle errors from proxied schemas- * c) handle external to internal enum coversion- */-function defaultMergedResolver(parent, args, context, info) {- if (!parent) {- return null;- }- const responseKey = getResponseKeyFromInfo(info);- const errors = getErrors(parent, responseKey);- // check to see if parent is not a proxied result, i.e. if parent resolver was manually overwritten- // See https://github.com/apollographql/graphql-tools/issues/967- if (!errors) {- return defaultFieldResolver(parent, args, context, info);- }- const result = parent[responseKey];- const subschema = getSubschema(parent, responseKey);- return handleResult(result, errors, subschema, context, info);-}--function generateProxyingResolvers(subschemaOrSubschemaConfig, transforms) {- var _a;- let targetSchema;- let schemaTransforms = [];- let createProxyingResolver;- if (isSubschemaConfig(subschemaOrSubschemaConfig)) {- targetSchema = subschemaOrSubschemaConfig.schema;- createProxyingResolver = (_a = subschemaOrSubschemaConfig.createProxyingResolver) !== null && _a !== void 0 ? _a : defaultCreateProxyingResolver;- if (subschemaOrSubschemaConfig.transforms != null) {- schemaTransforms = schemaTransforms.concat(subschemaOrSubschemaConfig.transforms);- }- }- else {- targetSchema = subschemaOrSubschemaConfig;- createProxyingResolver = defaultCreateProxyingResolver;- }- if (transforms != null) {- schemaTransforms = schemaTransforms.concat(transforms);- }- const transformedSchema = applySchemaTransforms(targetSchema, schemaTransforms);- const operationTypes = {- query: targetSchema.getQueryType(),- mutation: targetSchema.getMutationType(),- subscription: targetSchema.getSubscriptionType(),- };- const resolvers = {};- Object.keys(operationTypes).forEach((operation) => {- const rootType = operationTypes[operation];- if (rootType != null) {- const typeName = rootType.name;- const fields = rootType.getFields();- resolvers[typeName] = {};- Object.keys(fields).forEach(fieldName => {- const proxyingResolver = createProxyingResolver({- schema: subschemaOrSubschemaConfig,- transforms,- transformedSchema,- operation,- fieldName,- });- const finalResolver = createPossiblyNestedProxyingResolver(subschemaOrSubschemaConfig, proxyingResolver);- if (operation === 'subscription') {- resolvers[typeName][fieldName] = {- subscribe: finalResolver,- resolve: (payload, _, __, { fieldName: targetFieldName }) => payload[targetFieldName],- };- }- else {- resolvers[typeName][fieldName] = {- resolve: finalResolver,- };- }- });- }- });- return resolvers;-}-function createPossiblyNestedProxyingResolver(subschemaOrSubschemaConfig, proxyingResolver) {- return (parent, args, context, info) => {- if (parent != null) {- const responseKey = getResponseKeyFromInfo(info);- const errors = getErrors(parent, responseKey);- // Check to see if the parent contains a proxied result- if (errors != null) {- const subschema = getSubschema(parent, responseKey);- // If there is a proxied result from this subschema, return it- // This can happen even for a root field when the root type ia- // also nested as a field within a different type.- if (subschemaOrSubschemaConfig === subschema && parent[responseKey] !== undefined) {- return handleResult(parent[responseKey], errors, subschema, context, info);- }- }- }- return proxyingResolver(parent, args, context, info);- };-}-function defaultCreateProxyingResolver({ schema, operation, transforms, transformedSchema, }) {- return (_parent, _args, context, info) => delegateToSchema({- schema,- operation,- context,- info,- transforms,- transformedSchema,- });-}--function wrapSchema(subschemaOrSubschemaConfig, transforms) {- let targetSchema;- let schemaTransforms = [];- if (isSubschemaConfig(subschemaOrSubschemaConfig)) {- targetSchema = subschemaOrSubschemaConfig.schema;- if (subschemaOrSubschemaConfig.transforms != null) {- schemaTransforms = schemaTransforms.concat(subschemaOrSubschemaConfig.transforms);- }- }- else {- targetSchema = subschemaOrSubschemaConfig;- }- if (transforms != null) {- schemaTransforms = schemaTransforms.concat(transforms);- }- const proxyingResolvers = generateProxyingResolvers(subschemaOrSubschemaConfig, transforms);- const schema = createWrappingSchema(targetSchema, proxyingResolvers);- return applySchemaTransforms(schema, schemaTransforms);-}-function createWrappingSchema(schema, proxyingResolvers) {- return mapSchema(schema, {- [MapperKind.ROOT_OBJECT]: type => {- const config = type.toConfig();- const fieldConfigMap = config.fields;- Object.keys(fieldConfigMap).forEach(fieldName => {- fieldConfigMap[fieldName] = {- ...fieldConfigMap[fieldName],- ...proxyingResolvers[type.name][fieldName],- };- });- return new GraphQLObjectType(config);- },- [MapperKind.OBJECT_TYPE]: type => {- const config = type.toConfig();- config.isTypeOf = undefined;- Object.keys(config.fields).forEach(fieldName => {- config.fields[fieldName].resolve = defaultMergedResolver;- config.fields[fieldName].subscribe = null;- });- return new GraphQLObjectType(config);- },- [MapperKind.INTERFACE_TYPE]: type => {- const config = type.toConfig();- delete config.resolveType;- return new GraphQLInterfaceType(config);- },- [MapperKind.UNION_TYPE]: type => {- const config = type.toConfig();- delete config.resolveType;- return new GraphQLUnionType(config);- },- });-}--/** -Escape RegExp special characters. -You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class. -@example -``` -import escapeStringRegexp = require('escape-string-regexp'); -const escapedString = escapeStringRegexp('How much $ for a 🦄?'); -//=> 'How much \\$ for a 🦄\\?' -new RegExp(escapedString); -``` -*/ -const escapeStringRegexp$1 = (string) => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } - // Escape characters with special meaning either inside or outside character sets. - // Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. - return string - .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') - .replace(/-/g, '\\x2d'); -};--const extractPathRegex$1 = /\s+at.*[(\s](.*)\)?/; -const pathRegex$1 = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -/** -Clean up error stack traces. Removes the mostly unhelpful internal Node.js entries. -@param stack - The `stack` property of an `Error`. -@example -``` -import cleanStack = require('clean-stack'); -const error = new Error('Missing unicorn'); -console.log(error.stack); -// Error: Missing unicorn -// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15) -// at Module._compile (module.js:409:26) -// at Object.Module._extensions..js (module.js:416:10) -// at Module.load (module.js:343:32) -// at Function.Module._load (module.js:300:12) -// at Function.Module.runMain (module.js:441:10) -// at startup (node.js:139:18) -console.log(cleanStack(error.stack)); -// Error: Missing unicorn -// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15) -``` -*/ -const cleanStack$1 = (stack, basePath) => { - const basePathRegex = basePath && new RegExp(`(at | \\()${escapeStringRegexp$1(basePath)}`, 'g'); - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex$1); - if (pathMatches === null || !pathMatches[1]) { - return true; - } - const match = pathMatches[1]; - // Electron - if (match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar')) { - return false; - } - return !pathRegex$1.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (basePathRegex) { - line = line.replace(basePathRegex, '$1'); - } - return line; - }) - .join('\n'); -};--const cleanInternalStack$1 = (stack) => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, '');--/** -Indent each line in a string. -@param string - The string to indent. -@param count - How many times you want `options.indent` repeated. Default: `1`. -@example -``` -import indentString = require('indent-string'); -indentString('Unicorns\nRainbows', 4); -//=> ' Unicorns\n Rainbows' -indentString('Unicorns\nRainbows', 4, {indent: '♥'}); -//=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows' -``` -*/ -const indentString$1 = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; - if (typeof string !== 'string') { - throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``); - } - if (typeof count !== 'number') { - throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``); - } - if (count < 0) { - throw new RangeError(`Expected \`count\` to be at least 0, got \`${count}\``); - } - if (typeof options.indent !== 'string') { - throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\``); - } - if (count === 0) { - return string; - } - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; - return string.replace(regex, options.indent.repeat(count)); -};--class AggregateError$1 extends Error { - /** - @param errors - If a string, a new `Error` is created with the string as the error message. If a non-Error object, a new `Error` is created with all properties from the object copied over. - @returns An Error that is also an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables) for the individual errors. - @example - ``` - import AggregateError = require('aggregate-error'); - const error = new AggregateError([new Error('foo'), 'bar', {message: 'baz'}]); - throw error; - // AggregateError: - // Error: foo - // at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:33) - // Error: bar - // at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13) - // Error: baz - // at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13) - // at AggregateError (/Users/sindresorhus/dev/aggregate-error/index.js:19:3) - // at Object.<anonymous> (/Users/sindresorhus/dev/aggregate-error/example.js:3:13) - // at Module._compile (module.js:556:32) - // at Object.Module._extensions..js (module.js:565:10) - // at Module.load (module.js:473:32) - // at tryModuleLoad (module.js:432:12) - // at Function.Module._load (module.js:424:3) - // at Module.runMain (module.js:590:10) - // at run (bootstrap_node.js:394:7) - // at startup (bootstrap_node.js:149:9) - for (const individualError of error) { - console.log(individualError); - } - //=> [Error: foo] - //=> [Error: bar] - //=> [Error: baz] - ``` - */ - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } - const normalizedErrors = errors.map(error => { - if (error instanceof Error) { - return error; - } - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } - return new Error(error); - }); - let message = normalizedErrors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack$1(cleanStack$1(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString$1(message, 4); - super(message); - this.name = 'AggregateError'; - Object.defineProperty(this, '_errors', { value: normalizedErrors }); - } - *[Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } -}--function getSchemaFromIntrospection(introspectionResult) {- var _a, _b;- if ((_a = introspectionResult === null || introspectionResult === void 0 ? void 0 : introspectionResult.data) === null || _a === void 0 ? void 0 : _a.__schema) {- return buildClientSchema(introspectionResult.data);- }- else if ((_b = introspectionResult === null || introspectionResult === void 0 ? void 0 : introspectionResult.errors) === null || _b === void 0 ? void 0 : _b.length) {- if (introspectionResult.errors.length > 1) {- const combinedError = new AggregateError$1(introspectionResult.errors);- throw combinedError;- }- const error = introspectionResult.errors[0];- throw error.originalError || error;- }- else {- throw new Error('Could not obtain introspection result, received: ' + JSON.stringify(introspectionResult));- }-}-async function introspectSchema(executor, context, options) {- const parsedIntrospectionQuery = parse(getIntrospectionQuery(options));- const introspectionResult = await executor({- document: parsedIntrospectionQuery,- context,- });- return getSchemaFromIntrospection(introspectionResult);-}--/**- * Expose `Backoff`.- */--var backo2 = Backoff;--/**- * Initialize backoff timer with `opts`.- *- * - `min` initial timeout in milliseconds [100]- * - `max` max timeout [10000]- * - `jitter` [0]- * - `factor` [2]- *- * @param {Object} opts- * @api public- */--function Backoff(opts) {- opts = opts || {};- this.ms = opts.min || 100;- this.max = opts.max || 10000;- this.factor = opts.factor || 2;- this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;- this.attempts = 0;-}--/**- * Return the backoff duration.- *- * @return {Number}- * @api public- */--Backoff.prototype.duration = function(){- var ms = this.ms * Math.pow(this.factor, this.attempts++);- if (this.jitter) {- var rand = Math.random();- var deviation = Math.floor(rand * this.jitter * ms);- ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;- }- return Math.min(ms, this.max) | 0;-};--/**- * Reset the number of attempts.- *- * @api public- */--Backoff.prototype.reset = function(){- this.attempts = 0;-};--/**- * Set the minimum duration- *- * @api public- */--Backoff.prototype.setMin = function(min){- this.ms = min;-};--/**- * Set the maximum duration- *- * @api public- */--Backoff.prototype.setMax = function(max){- this.max = max;-};--/**- * Set the jitter- *- * @api public- */--Backoff.prototype.setJitter = function(jitter){- this.jitter = jitter;-};--var eventemitter3 = createCommonjsModule(function (module) {--var has = Object.prototype.hasOwnProperty- , prefix = '~';--/**- * Constructor to create a storage for our `EE` objects.- * An `Events` instance is a plain object whose properties are event names.- *- * @constructor- * @private- */-function Events() {}--//-// We try to not inherit from `Object.prototype`. In some engines creating an-// instance in this way is faster than calling `Object.create(null)` directly.-// If `Object.create(null)` is not supported we prefix the event names with a-// character to make sure that the built-in object properties are not-// overridden or used as an attack vector.-//-if (Object.create) {- Events.prototype = Object.create(null);-- //- // This hack is needed because the `__proto__` property is still inherited in- // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.- //- if (!new Events().__proto__) prefix = false;-}--/**- * Representation of a single event listener.- *- * @param {Function} fn The listener function.- * @param {*} context The context to invoke the listener with.- * @param {Boolean} [once=false] Specify if the listener is a one-time listener.- * @constructor- * @private- */-function EE(fn, context, once) {- this.fn = fn;- this.context = context;- this.once = once || false;-}--/**- * Add a listener for a given event.- *- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.- * @param {(String|Symbol)} event The event name.- * @param {Function} fn The listener function.- * @param {*} context The context to invoke the listener with.- * @param {Boolean} once Specify if the listener is a one-time listener.- * @returns {EventEmitter}- * @private- */-function addListener(emitter, event, fn, context, once) {- if (typeof fn !== 'function') {- throw new TypeError('The listener must be a function');- }-- var listener = new EE(fn, context || emitter, once)- , evt = prefix ? prefix + event : event;-- if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;- else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);- else emitter._events[evt] = [emitter._events[evt], listener];-- return emitter;-}--/**- * Clear event by name.- *- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.- * @param {(String|Symbol)} evt The Event name.- * @private- */-function clearEvent(emitter, evt) {- if (--emitter._eventsCount === 0) emitter._events = new Events();- else delete emitter._events[evt];-}--/**- * Minimal `EventEmitter` interface that is molded against the Node.js- * `EventEmitter` interface.- *- * @constructor- * @public- */-function EventEmitter() {- this._events = new Events();- this._eventsCount = 0;-}--/**- * Return an array listing the events for which the emitter has registered- * listeners.- *- * @returns {Array}- * @public- */-EventEmitter.prototype.eventNames = function eventNames() {- var names = []- , events- , name;-- if (this._eventsCount === 0) return names;-- for (name in (events = this._events)) {- if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);- }-- if (Object.getOwnPropertySymbols) {- return names.concat(Object.getOwnPropertySymbols(events));- }-- return names;-};--/**- * Return the listeners registered for a given event.- *- * @param {(String|Symbol)} event The event name.- * @returns {Array} The registered listeners.- * @public- */-EventEmitter.prototype.listeners = function listeners(event) {- var evt = prefix ? prefix + event : event- , handlers = this._events[evt];-- if (!handlers) return [];- if (handlers.fn) return [handlers.fn];-- for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {- ee[i] = handlers[i].fn;- }-- return ee;-};--/**- * Return the number of listeners listening to a given event.- *- * @param {(String|Symbol)} event The event name.- * @returns {Number} The number of listeners.- * @public- */-EventEmitter.prototype.listenerCount = function listenerCount(event) {- var evt = prefix ? prefix + event : event- , listeners = this._events[evt];-- if (!listeners) return 0;- if (listeners.fn) return 1;- return listeners.length;-};--/**- * Calls each of the listeners registered for a given event.- *- * @param {(String|Symbol)} event The event name.- * @returns {Boolean} `true` if the event had listeners, else `false`.- * @public- */-EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {- var evt = prefix ? prefix + event : event;-- if (!this._events[evt]) return false;-- var listeners = this._events[evt]- , len = arguments.length- , args- , i;-- if (listeners.fn) {- if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);-- switch (len) {- case 1: return listeners.fn.call(listeners.context), true;- case 2: return listeners.fn.call(listeners.context, a1), true;- case 3: return listeners.fn.call(listeners.context, a1, a2), true;- case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;- case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;- case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;- }-- for (i = 1, args = new Array(len -1); i < len; i++) {- args[i - 1] = arguments[i];- }-- listeners.fn.apply(listeners.context, args);- } else {- var length = listeners.length- , j;-- for (i = 0; i < length; i++) {- if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);-- switch (len) {- case 1: listeners[i].fn.call(listeners[i].context); break;- case 2: listeners[i].fn.call(listeners[i].context, a1); break;- case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;- case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;- default:- if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {- args[j - 1] = arguments[j];- }-- listeners[i].fn.apply(listeners[i].context, args);- }- }- }-- return true;-};--/**- * Add a listener for a given event.- *- * @param {(String|Symbol)} event The event name.- * @param {Function} fn The listener function.- * @param {*} [context=this] The context to invoke the listener with.- * @returns {EventEmitter} `this`.- * @public- */-EventEmitter.prototype.on = function on(event, fn, context) {- return addListener(this, event, fn, context, false);-};--/**- * Add a one-time listener for a given event.- *- * @param {(String|Symbol)} event The event name.- * @param {Function} fn The listener function.- * @param {*} [context=this] The context to invoke the listener with.- * @returns {EventEmitter} `this`.- * @public- */-EventEmitter.prototype.once = function once(event, fn, context) {- return addListener(this, event, fn, context, true);-};--/**- * Remove the listeners of a given event.- *- * @param {(String|Symbol)} event The event name.- * @param {Function} fn Only remove the listeners that match this function.- * @param {*} context Only remove the listeners that have this context.- * @param {Boolean} once Only remove one-time listeners.- * @returns {EventEmitter} `this`.- * @public- */-EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {- var evt = prefix ? prefix + event : event;-- if (!this._events[evt]) return this;- if (!fn) {- clearEvent(this, evt);- return this;- }-- var listeners = this._events[evt];-- if (listeners.fn) {- if (- listeners.fn === fn &&- (!once || listeners.once) &&- (!context || listeners.context === context)- ) {- clearEvent(this, evt);- }- } else {- for (var i = 0, events = [], length = listeners.length; i < length; i++) {- if (- listeners[i].fn !== fn ||- (once && !listeners[i].once) ||- (context && listeners[i].context !== context)- ) {- events.push(listeners[i]);- }- }-- //- // Reset the array, or remove it completely if we have no more listeners.- //- if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;- else clearEvent(this, evt);- }-- return this;-};--/**- * Remove all listeners, or those of the specified event.- *- * @param {(String|Symbol)} [event] The event name.- * @returns {EventEmitter} `this`.- * @public- */-EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {- var evt;-- if (event) {- evt = prefix ? prefix + event : event;- if (this._events[evt]) clearEvent(this, evt);- } else {- this._events = new Events();- this._eventsCount = 0;- }-- return this;-};--//-// Alias methods names because people roll like that.-//-EventEmitter.prototype.off = EventEmitter.prototype.removeListener;-EventEmitter.prototype.addListener = EventEmitter.prototype.on;--//-// Expose the prefix.-//-EventEmitter.prefixed = prefix;--//-// Allow `EventEmitter` to be imported as module namespace.-//-EventEmitter.EventEmitter = EventEmitter;--//-// Expose the module.-//-{- module.exports = EventEmitter;-}-});--var isString_1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true });-function isString(value) {- return typeof value === 'string';-}-exports.default = isString;--});--var isObject_1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true });-function isObject(value) {- return ((value !== null) && (typeof value === 'object'));-}-exports.default = isObject;--});--function symbolObservablePonyfill(root) {- var result;- var Symbol = root.Symbol;-- if (typeof Symbol === 'function') {- if (Symbol.observable) {- result = Symbol.observable;- } else {- result = Symbol('observable');- Symbol.observable = result;- }- } else {- result = '@@observable';- }-- return result;-}--/* global window */--var root;--if (typeof self !== 'undefined') {- root = self;-} else if (typeof window !== 'undefined') {- root = window;-} else if (typeof global !== 'undefined') {- root = global;-} else if (typeof module !== 'undefined') {- root = module;-} else {- root = Function('return this')();-}--var result = symbolObservablePonyfill(root);--var es = /*#__PURE__*/Object.freeze({- __proto__: null,- 'default': result-});--var protocol = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true });-exports.GRAPHQL_SUBSCRIPTIONS = exports.GRAPHQL_WS = void 0;-var GRAPHQL_WS = 'graphql-ws';-exports.GRAPHQL_WS = GRAPHQL_WS;-var GRAPHQL_SUBSCRIPTIONS = 'graphql-subscriptions';-exports.GRAPHQL_SUBSCRIPTIONS = GRAPHQL_SUBSCRIPTIONS;--});--var defaults$1 = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true });-exports.WS_TIMEOUT = void 0;-var WS_TIMEOUT = 30000;-exports.WS_TIMEOUT = WS_TIMEOUT;--});--var messageTypes = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true });-var MessageTypes = (function () {- function MessageTypes() {- throw new Error('Static Class');- }- MessageTypes.GQL_CONNECTION_INIT = 'connection_init';- MessageTypes.GQL_CONNECTION_ACK = 'connection_ack';- MessageTypes.GQL_CONNECTION_ERROR = 'connection_error';- MessageTypes.GQL_CONNECTION_KEEP_ALIVE = 'ka';- MessageTypes.GQL_CONNECTION_TERMINATE = 'connection_terminate';- MessageTypes.GQL_START = 'start';- MessageTypes.GQL_DATA = 'data';- MessageTypes.GQL_ERROR = 'error';- MessageTypes.GQL_COMPLETE = 'complete';- MessageTypes.GQL_STOP = 'stop';- MessageTypes.SUBSCRIPTION_START = 'subscription_start';- MessageTypes.SUBSCRIPTION_DATA = 'subscription_data';- MessageTypes.SUBSCRIPTION_SUCCESS = 'subscription_success';- MessageTypes.SUBSCRIPTION_FAIL = 'subscription_fail';- MessageTypes.SUBSCRIPTION_END = 'subscription_end';- MessageTypes.INIT = 'init';- MessageTypes.INIT_SUCCESS = 'init_success';- MessageTypes.INIT_FAIL = 'init_fail';- MessageTypes.KEEP_ALIVE = 'keepalive';- return MessageTypes;-}());-exports.default = MessageTypes;--});--var client = createCommonjsModule(function (module, exports) {-var __assign = (commonjsGlobal && commonjsGlobal.__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 __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }- return new (P || (P = Promise))(function (resolve, reject) {- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }- step((generator = generator.apply(thisArg, _arguments || [])).next());- });-};-var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;- function verb(n) { return function (v) { return step([n, v]); }; }- function step(op) {- if (f) throw new TypeError("Generator is already executing.");- while (_) try {- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;- if (y = 0, t) op = [op[0] & 2, t.value];- switch (op[0]) {- case 0: case 1: t = op; break;- case 4: _.label++; return { value: op[1], done: false };- case 5: _.label++; y = op[1]; op = [0]; continue;- case 7: op = _.ops.pop(); _.trys.pop(); continue;- default:- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }- if (t[2]) _.ops.pop();- _.trys.pop(); continue;- }- op = body.call(thisArg, _);- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };- }-};-var __spreadArrays = (commonjsGlobal && commonjsGlobal.__spreadArrays) || function () {- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;- for (var r = Array(s), k = 0, i = 0; i < il; i++)- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)- r[k] = a[j];- return r;-};-Object.defineProperty(exports, "__esModule", { value: true });-exports.SubscriptionClient = void 0;-var _global = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : (typeof window !== 'undefined' ? window : {});-var NativeWebSocket = _global.WebSocket || _global.MozWebSocket;-----------var SubscriptionClient = (function () {- function SubscriptionClient(url, options, webSocketImpl, webSocketProtocols) {- var _a = (options || {}), _b = _a.connectionCallback, connectionCallback = _b === void 0 ? undefined : _b, _c = _a.connectionParams, connectionParams = _c === void 0 ? {} : _c, _d = _a.timeout, timeout = _d === void 0 ? defaults$1.WS_TIMEOUT : _d, _e = _a.reconnect, reconnect = _e === void 0 ? false : _e, _f = _a.reconnectionAttempts, reconnectionAttempts = _f === void 0 ? Infinity : _f, _g = _a.lazy, lazy = _g === void 0 ? false : _g, _h = _a.inactivityTimeout, inactivityTimeout = _h === void 0 ? 0 : _h;- this.wsImpl = webSocketImpl || NativeWebSocket;- if (!this.wsImpl) {- throw new Error('Unable to find native implementation, or alternative implementation for WebSocket!');- }- this.wsProtocols = webSocketProtocols || protocol.GRAPHQL_WS;- this.connectionCallback = connectionCallback;- this.url = url;- this.operations = {};- this.nextOperationId = 0;- this.wsTimeout = timeout;- this.unsentMessagesQueue = [];- this.reconnect = reconnect;- this.reconnecting = false;- this.reconnectionAttempts = reconnectionAttempts;- this.lazy = !!lazy;- this.inactivityTimeout = inactivityTimeout;- this.closedByUser = false;- this.backoff = new backo2({ jitter: 0.5 });- this.eventEmitter = new eventemitter3.EventEmitter();- this.middlewares = [];- this.client = null;- this.maxConnectTimeGenerator = this.createMaxConnectTimeGenerator();- this.connectionParams = this.getConnectionParams(connectionParams);- if (!this.lazy) {- this.connect();- }- }- Object.defineProperty(SubscriptionClient.prototype, "status", {- get: function () {- if (this.client === null) {- return this.wsImpl.CLOSED;- }- return this.client.readyState;- },- enumerable: false,- configurable: true- });- SubscriptionClient.prototype.close = function (isForced, closedByUser) {- if (isForced === void 0) { isForced = true; }- if (closedByUser === void 0) { closedByUser = true; }- this.clearInactivityTimeout();- if (this.client !== null) {- this.closedByUser = closedByUser;- if (isForced) {- this.clearCheckConnectionInterval();- this.clearMaxConnectTimeout();- this.clearTryReconnectTimeout();- this.unsubscribeAll();- this.sendMessage(undefined, messageTypes.default.GQL_CONNECTION_TERMINATE, null);- }- this.client.close();- this.client = null;- this.eventEmitter.emit('disconnected');- if (!isForced) {- this.tryReconnect();- }- }- };- SubscriptionClient.prototype.request = function (request) {- var _a;- var getObserver = this.getObserver.bind(this);- var executeOperation = this.executeOperation.bind(this);- var unsubscribe = this.unsubscribe.bind(this);- var opId;- this.clearInactivityTimeout();- return _a = {},- _a[es.default] = function () {- return this;- },- _a.subscribe = function (observerOrNext, onError, onComplete) {- var observer = getObserver(observerOrNext, onError, onComplete);- opId = executeOperation(request, function (error, result) {- if (error === null && result === null) {- if (observer.complete) {- observer.complete();- }- }- else if (error) {- if (observer.error) {- observer.error(error[0]);- }- }- else {- if (observer.next) {- observer.next(result);- }- }- });- return {- unsubscribe: function () {- if (opId) {- unsubscribe(opId);- opId = null;- }- },- };- },- _a;- };- SubscriptionClient.prototype.on = function (eventName, callback, context) {- var handler = this.eventEmitter.on(eventName, callback, context);- return function () {- handler.off(eventName, callback, context);- };- };- SubscriptionClient.prototype.onConnected = function (callback, context) {- return this.on('connected', callback, context);- };- SubscriptionClient.prototype.onConnecting = function (callback, context) {- return this.on('connecting', callback, context);- };- SubscriptionClient.prototype.onDisconnected = function (callback, context) {- return this.on('disconnected', callback, context);- };- SubscriptionClient.prototype.onReconnected = function (callback, context) {- return this.on('reconnected', callback, context);- };- SubscriptionClient.prototype.onReconnecting = function (callback, context) {- return this.on('reconnecting', callback, context);- };- SubscriptionClient.prototype.onError = function (callback, context) {- return this.on('error', callback, context);- };- SubscriptionClient.prototype.unsubscribeAll = function () {- var _this = this;- Object.keys(this.operations).forEach(function (subId) {- _this.unsubscribe(subId);- });- };- SubscriptionClient.prototype.applyMiddlewares = function (options) {- var _this = this;- return new Promise(function (resolve, reject) {- var queue = function (funcs, scope) {- var next = function (error) {- if (error) {- reject(error);- }- else {- if (funcs.length > 0) {- var f = funcs.shift();- if (f) {- f.applyMiddleware.apply(scope, [options, next]);- }- }- else {- resolve(options);- }- }- };- next();- };- queue(__spreadArrays(_this.middlewares), _this);- });- };- SubscriptionClient.prototype.use = function (middlewares) {- var _this = this;- middlewares.map(function (middleware) {- if (typeof middleware.applyMiddleware === 'function') {- _this.middlewares.push(middleware);- }- else {- throw new Error('Middleware must implement the applyMiddleware function.');- }- });- return this;- };- SubscriptionClient.prototype.getConnectionParams = function (connectionParams) {- return function () { return new Promise(function (resolve, reject) {- if (typeof connectionParams === 'function') {- try {- return resolve(connectionParams.call(null));- }- catch (error) {- return reject(error);- }- }- resolve(connectionParams);- }); };- };- SubscriptionClient.prototype.executeOperation = function (options, handler) {- var _this = this;- if (this.client === null) {- this.connect();- }- var opId = this.generateOperationId();- this.operations[opId] = { options: options, handler: handler };- this.applyMiddlewares(options)- .then(function (processedOptions) {- _this.checkOperationOptions(processedOptions, handler);- if (_this.operations[opId]) {- _this.operations[opId] = { options: processedOptions, handler: handler };- _this.sendMessage(opId, messageTypes.default.GQL_START, processedOptions);- }- })- .catch(function (error) {- _this.unsubscribe(opId);- handler(_this.formatErrors(error));- });- return opId;- };- SubscriptionClient.prototype.getObserver = function (observerOrNext, error, complete) {- if (typeof observerOrNext === 'function') {- return {- next: function (v) { return observerOrNext(v); },- error: function (e) { return error && error(e); },- complete: function () { return complete && complete(); },- };- }- return observerOrNext;- };- SubscriptionClient.prototype.createMaxConnectTimeGenerator = function () {- var minValue = 1000;- var maxValue = this.wsTimeout;- return new backo2({- min: minValue,- max: maxValue,- factor: 1.2,- });- };- SubscriptionClient.prototype.clearCheckConnectionInterval = function () {- if (this.checkConnectionIntervalId) {- clearInterval(this.checkConnectionIntervalId);- this.checkConnectionIntervalId = null;- }- };- SubscriptionClient.prototype.clearMaxConnectTimeout = function () {- if (this.maxConnectTimeoutId) {- clearTimeout(this.maxConnectTimeoutId);- this.maxConnectTimeoutId = null;- }- };- SubscriptionClient.prototype.clearTryReconnectTimeout = function () {- if (this.tryReconnectTimeoutId) {- clearTimeout(this.tryReconnectTimeoutId);- this.tryReconnectTimeoutId = null;- }- };- SubscriptionClient.prototype.clearInactivityTimeout = function () {- if (this.inactivityTimeoutId) {- clearTimeout(this.inactivityTimeoutId);- this.inactivityTimeoutId = null;- }- };- SubscriptionClient.prototype.setInactivityTimeout = function () {- var _this = this;- if (this.inactivityTimeout > 0 && Object.keys(this.operations).length === 0) {- this.inactivityTimeoutId = setTimeout(function () {- if (Object.keys(_this.operations).length === 0) {- _this.close();- }- }, this.inactivityTimeout);- }- };- SubscriptionClient.prototype.checkOperationOptions = function (options, handler) {- var query = options.query, variables = options.variables, operationName = options.operationName;- if (!query) {- throw new Error('Must provide a query.');- }- if (!handler) {- throw new Error('Must provide an handler.');- }- if ((!isString_1.default(query) && !getOperationAST$1.getOperationAST(query, operationName)) ||- (operationName && !isString_1.default(operationName)) ||- (variables && !isObject_1.default(variables))) {- throw new Error('Incorrect option types. query must be a string or a document,' +- '`operationName` must be a string, and `variables` must be an object.');- }- };- SubscriptionClient.prototype.buildMessage = function (id, type, payload) {- var payloadToReturn = payload && payload.query ? __assign(__assign({}, payload), { query: typeof payload.query === 'string' ? payload.query : printer.print(payload.query) }) :- payload;- return {- id: id,- type: type,- payload: payloadToReturn,- };- };- SubscriptionClient.prototype.formatErrors = function (errors) {- if (Array.isArray(errors)) {- return errors;- }- if (errors && errors.errors) {- return this.formatErrors(errors.errors);- }- if (errors && errors.message) {- return [errors];- }- return [{- name: 'FormatedError',- message: 'Unknown error',- originalError: errors,- }];- };- SubscriptionClient.prototype.sendMessage = function (id, type, payload) {- this.sendMessageRaw(this.buildMessage(id, type, payload));- };- SubscriptionClient.prototype.sendMessageRaw = function (message) {- switch (this.status) {- case this.wsImpl.OPEN:- var serializedMessage = JSON.stringify(message);- try {- JSON.parse(serializedMessage);- }- catch (e) {- this.eventEmitter.emit('error', new Error("Message must be JSON-serializable. Got: " + message));- }- this.client.send(serializedMessage);- break;- case this.wsImpl.CONNECTING:- this.unsentMessagesQueue.push(message);- break;- default:- if (!this.reconnecting) {- this.eventEmitter.emit('error', new Error('A message was not sent because socket is not connected, is closing or ' +- 'is already closed. Message was: ' + JSON.stringify(message)));- }- }- };- SubscriptionClient.prototype.generateOperationId = function () {- return String(++this.nextOperationId);- };- SubscriptionClient.prototype.tryReconnect = function () {- var _this = this;- if (!this.reconnect || this.backoff.attempts >= this.reconnectionAttempts) {- return;- }- if (!this.reconnecting) {- Object.keys(this.operations).forEach(function (key) {- _this.unsentMessagesQueue.push(_this.buildMessage(key, messageTypes.default.GQL_START, _this.operations[key].options));- });- this.reconnecting = true;- }- this.clearTryReconnectTimeout();- var delay = this.backoff.duration();- this.tryReconnectTimeoutId = setTimeout(function () {- _this.connect();- }, delay);- };- SubscriptionClient.prototype.flushUnsentMessagesQueue = function () {- var _this = this;- this.unsentMessagesQueue.forEach(function (message) {- _this.sendMessageRaw(message);- });- this.unsentMessagesQueue = [];- };- SubscriptionClient.prototype.checkConnection = function () {- if (this.wasKeepAliveReceived) {- this.wasKeepAliveReceived = false;- return;- }- if (!this.reconnecting) {- this.close(false, true);- }- };- SubscriptionClient.prototype.checkMaxConnectTimeout = function () {- var _this = this;- this.clearMaxConnectTimeout();- this.maxConnectTimeoutId = setTimeout(function () {- if (_this.status !== _this.wsImpl.OPEN) {- _this.reconnecting = true;- _this.close(false, true);- }- }, this.maxConnectTimeGenerator.duration());- };- SubscriptionClient.prototype.connect = function () {- var _this = this;- this.client = new this.wsImpl(this.url, this.wsProtocols);- this.checkMaxConnectTimeout();- this.client.onopen = function () { return __awaiter(_this, void 0, void 0, function () {- var connectionParams, error_1;- return __generator(this, function (_a) {- switch (_a.label) {- case 0:- if (!(this.status === this.wsImpl.OPEN)) return [3, 4];- this.clearMaxConnectTimeout();- this.closedByUser = false;- this.eventEmitter.emit(this.reconnecting ? 'reconnecting' : 'connecting');- _a.label = 1;- case 1:- _a.trys.push([1, 3, , 4]);- return [4, this.connectionParams()];- case 2:- connectionParams = _a.sent();- this.sendMessage(undefined, messageTypes.default.GQL_CONNECTION_INIT, connectionParams);- this.flushUnsentMessagesQueue();- return [3, 4];- case 3:- error_1 = _a.sent();- this.sendMessage(undefined, messageTypes.default.GQL_CONNECTION_ERROR, error_1);- this.flushUnsentMessagesQueue();- return [3, 4];- case 4: return [2];- }- });- }); };- this.client.onclose = function () {- if (!_this.closedByUser) {- _this.close(false, false);- }- };- this.client.onerror = function (err) {- _this.eventEmitter.emit('error', err);- };- this.client.onmessage = function (_a) {- var data = _a.data;- _this.processReceivedData(data);- };- };- SubscriptionClient.prototype.processReceivedData = function (receivedData) {- var parsedMessage;- var opId;- try {- parsedMessage = JSON.parse(receivedData);- opId = parsedMessage.id;- }- catch (e) {- throw new Error("Message must be JSON-parseable. Got: " + receivedData);- }- if ([messageTypes.default.GQL_DATA,- messageTypes.default.GQL_COMPLETE,- messageTypes.default.GQL_ERROR,- ].indexOf(parsedMessage.type) !== -1 && !this.operations[opId]) {- this.unsubscribe(opId);- return;- }- switch (parsedMessage.type) {- case messageTypes.default.GQL_CONNECTION_ERROR:- if (this.connectionCallback) {- this.connectionCallback(parsedMessage.payload);- }- break;- case messageTypes.default.GQL_CONNECTION_ACK:- this.eventEmitter.emit(this.reconnecting ? 'reconnected' : 'connected');- this.reconnecting = false;- this.backoff.reset();- this.maxConnectTimeGenerator.reset();- if (this.connectionCallback) {- this.connectionCallback();- }- break;- case messageTypes.default.GQL_COMPLETE:- this.operations[opId].handler(null, null);- delete this.operations[opId];- break;- case messageTypes.default.GQL_ERROR:- this.operations[opId].handler(this.formatErrors(parsedMessage.payload), null);- delete this.operations[opId];- break;- case messageTypes.default.GQL_DATA:- var parsedPayload = !parsedMessage.payload.errors ?- parsedMessage.payload : __assign(__assign({}, parsedMessage.payload), { errors: this.formatErrors(parsedMessage.payload.errors) });- this.operations[opId].handler(null, parsedPayload);- break;- case messageTypes.default.GQL_CONNECTION_KEEP_ALIVE:- var firstKA = typeof this.wasKeepAliveReceived === 'undefined';- this.wasKeepAliveReceived = true;- if (firstKA) {- this.checkConnection();- }- if (this.checkConnectionIntervalId) {- clearInterval(this.checkConnectionIntervalId);- this.checkConnection();- }- this.checkConnectionIntervalId = setInterval(this.checkConnection.bind(this), this.wsTimeout);- break;- default:- throw new Error('Invalid message type!');- }- };- SubscriptionClient.prototype.unsubscribe = function (opId) {- if (this.operations[opId]) {- delete this.operations[opId];- this.setInactivityTimeout();- this.sendMessage(opId, messageTypes.default.GQL_STOP, undefined);- }- };- return SubscriptionClient;-}());-exports.SubscriptionClient = SubscriptionClient;--});--function Queue(options) {- if (!(this instanceof Queue)) {- return new Queue(options);- }-- options = options || {};- this.concurrency = options.concurrency || Infinity;- this.pending = 0;- this.jobs = [];- this.cbs = [];- this._done = done.bind(this);-}--var arrayAddMethods = [- 'push',- 'unshift',- 'splice'-];--arrayAddMethods.forEach(function(method) {- Queue.prototype[method] = function() {- var methodResult = Array.prototype[method].apply(this.jobs, arguments);- this._run();- return methodResult;- };-});--Object.defineProperty(Queue.prototype, 'length', {- get: function() {- return this.pending + this.jobs.length;- }-});--Queue.prototype._run = function() {- if (this.pending === this.concurrency) {- return;- }- if (this.jobs.length) {- var job = this.jobs.shift();- this.pending++;- job(this._done);- this._run();- }-- if (this.pending === 0) {- while (this.cbs.length !== 0) {- var cb = this.cbs.pop();- process.nextTick(cb);- }- }-};--Queue.prototype.onDone = function(cb) {- if (typeof cb === 'function') {- this.cbs.push(cb);- this._run();- }-};--function done() {- this.pending--;- this._run();-}--var asyncLimiter = Queue;--var bufferUtil = createCommonjsModule(function (module) {--/**- * Merges an array of buffers into a new buffer.- *- * @param {Buffer[]} list The array of buffers to concat- * @param {Number} totalLength The total length of buffers in the list- * @return {Buffer} The resulting buffer- * @public- */-function concat (list, totalLength) {- const target = Buffer.allocUnsafe(totalLength);- var offset = 0;-- for (var i = 0; i < list.length; i++) {- const buf = list[i];- buf.copy(target, offset);- offset += buf.length;- }-- return target;-}--/**- * Masks a buffer using the given mask.- *- * @param {Buffer} source The buffer to mask- * @param {Buffer} mask The mask to use- * @param {Buffer} output The buffer where to store the result- * @param {Number} offset The offset at which to start writing- * @param {Number} length The number of bytes to mask.- * @public- */-function _mask (source, mask, output, offset, length) {- for (var i = 0; i < length; i++) {- output[offset + i] = source[i] ^ mask[i & 3];- }-}--/**- * Unmasks a buffer using the given mask.- *- * @param {Buffer} buffer The buffer to unmask- * @param {Buffer} mask The mask to use- * @public- */-function _unmask (buffer, mask) {- // Required until https://github.com/nodejs/node/issues/9006 is resolved.- const length = buffer.length;- for (var i = 0; i < length; i++) {- buffer[i] ^= mask[i & 3];- }-}--try {- const bufferUtil = require('bufferutil');- const bu = bufferUtil.BufferUtil || bufferUtil;-- module.exports = {- mask (source, mask, output, offset, length) {- if (length < 48) _mask(source, mask, output, offset, length);- else bu.mask(source, mask, output, offset, length);- },- unmask (buffer, mask) {- if (buffer.length < 32) _unmask(buffer, mask);- else bu.unmask(buffer, mask);- },- concat- };-} catch (e) /* istanbul ignore next */ {- module.exports = { concat, mask: _mask, unmask: _unmask };-}-});--var constants$3 = {- BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],- GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',- kStatusCode: Symbol('status-code'),- kWebSocket: Symbol('websocket'),- EMPTY_BUFFER: Buffer.alloc(0),- NOOP: () => {}-};--const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);-const EMPTY_BLOCK = Buffer.from([0x00]);--const kPerMessageDeflate = Symbol('permessage-deflate');-const kWriteInProgress = Symbol('write-in-progress');-const kPendingClose = Symbol('pending-close');-const kTotalLength = Symbol('total-length');-const kCallback = Symbol('callback');-const kBuffers = Symbol('buffers');-const kError = Symbol('error');--//-// We limit zlib concurrency, which prevents severe memory fragmentation-// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913-// and https://github.com/websockets/ws/issues/1202-//-// Intentionally global; it's the global thread pool that's an issue.-//-let zlibLimiter;--/**- * permessage-deflate implementation.- */-class PerMessageDeflate {- /**- * Creates a PerMessageDeflate instance.- *- * @param {Object} options Configuration options- * @param {Boolean} options.serverNoContextTakeover Request/accept disabling- * of server context takeover- * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge- * disabling of client context takeover- * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the- * use of a custom server window size- * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support- * for, or request, a custom client window size- * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate- * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate- * @param {Number} options.threshold Size (in bytes) below which messages- * should not be compressed- * @param {Number} options.concurrencyLimit The number of concurrent calls to- * zlib- * @param {Boolean} isServer Create the instance in either server or client- * mode- * @param {Number} maxPayload The maximum allowed message length- */- constructor (options, isServer, maxPayload) {- this._maxPayload = maxPayload | 0;- this._options = options || {};- this._threshold = this._options.threshold !== undefined- ? this._options.threshold- : 1024;- this._isServer = !!isServer;- this._deflate = null;- this._inflate = null;-- this.params = null;-- if (!zlibLimiter) {- const concurrency = this._options.concurrencyLimit !== undefined- ? this._options.concurrencyLimit- : 10;- zlibLimiter = new asyncLimiter({ concurrency });- }- }-- /**- * @type {String}- */- static get extensionName () {- return 'permessage-deflate';- }-- /**- * Create an extension negotiation offer.- *- * @return {Object} Extension parameters- * @public- */- offer () {- const params = {};-- if (this._options.serverNoContextTakeover) {- params.server_no_context_takeover = true;- }- if (this._options.clientNoContextTakeover) {- params.client_no_context_takeover = true;- }- if (this._options.serverMaxWindowBits) {- params.server_max_window_bits = this._options.serverMaxWindowBits;- }- if (this._options.clientMaxWindowBits) {- params.client_max_window_bits = this._options.clientMaxWindowBits;- } else if (this._options.clientMaxWindowBits == null) {- params.client_max_window_bits = true;- }-- return params;- }-- /**- * Accept an extension negotiation offer/response.- *- * @param {Array} configurations The extension negotiation offers/reponse- * @return {Object} Accepted configuration- * @public- */- accept (configurations) {- configurations = this.normalizeParams(configurations);-- this.params = this._isServer- ? this.acceptAsServer(configurations)- : this.acceptAsClient(configurations);-- return this.params;- }-- /**- * Releases all resources used by the extension.- *- * @public- */- cleanup () {- if (this._inflate) {- if (this._inflate[kWriteInProgress]) {- this._inflate[kPendingClose] = true;- } else {- this._inflate.close();- this._inflate = null;- }- }- if (this._deflate) {- if (this._deflate[kWriteInProgress]) {- this._deflate[kPendingClose] = true;- } else {- this._deflate.close();- this._deflate = null;- }- }- }-- /**- * Accept an extension negotiation offer.- *- * @param {Array} offers The extension negotiation offers- * @return {Object} Accepted configuration- * @private- */- acceptAsServer (offers) {- const opts = this._options;- const accepted = offers.find((params) => {- if (- (opts.serverNoContextTakeover === false &&- params.server_no_context_takeover) ||- (params.server_max_window_bits &&- (opts.serverMaxWindowBits === false ||- (typeof opts.serverMaxWindowBits === 'number' &&- opts.serverMaxWindowBits > params.server_max_window_bits))) ||- (typeof opts.clientMaxWindowBits === 'number' &&- !params.client_max_window_bits)- ) {- return false;- }-- return true;- });-- if (!accepted) {- throw new Error('None of the extension offers can be accepted');- }-- if (opts.serverNoContextTakeover) {- accepted.server_no_context_takeover = true;- }- if (opts.clientNoContextTakeover) {- accepted.client_no_context_takeover = true;- }- if (typeof opts.serverMaxWindowBits === 'number') {- accepted.server_max_window_bits = opts.serverMaxWindowBits;- }- if (typeof opts.clientMaxWindowBits === 'number') {- accepted.client_max_window_bits = opts.clientMaxWindowBits;- } else if (- accepted.client_max_window_bits === true ||- opts.clientMaxWindowBits === false- ) {- delete accepted.client_max_window_bits;- }-- return accepted;- }-- /**- * Accept the extension negotiation response.- *- * @param {Array} response The extension negotiation response- * @return {Object} Accepted configuration- * @private- */- acceptAsClient (response) {- const params = response[0];-- if (- this._options.clientNoContextTakeover === false &&- params.client_no_context_takeover- ) {- throw new Error('Unexpected parameter "client_no_context_takeover"');- }-- if (!params.client_max_window_bits) {- if (typeof this._options.clientMaxWindowBits === 'number') {- params.client_max_window_bits = this._options.clientMaxWindowBits;- }- } else if (- this._options.clientMaxWindowBits === false ||- (typeof this._options.clientMaxWindowBits === 'number' &&- params.client_max_window_bits > this._options.clientMaxWindowBits)- ) {- throw new Error(- 'Unexpected or invalid parameter "client_max_window_bits"'- );- }-- return params;- }-- /**- * Normalize parameters.- *- * @param {Array} configurations The extension negotiation offers/reponse- * @return {Array} The offers/response with normalized parameters- * @private- */- normalizeParams (configurations) {- configurations.forEach((params) => {- Object.keys(params).forEach((key) => {- var value = params[key];-- if (value.length > 1) {- throw new Error(`Parameter "${key}" must have only a single value`);- }-- value = value[0];-- if (key === 'client_max_window_bits') {- if (value !== true) {- const num = +value;- if (!Number.isInteger(num) || num < 8 || num > 15) {- throw new TypeError(- `Invalid value for parameter "${key}": ${value}`- );- }- value = num;- } else if (!this._isServer) {- throw new TypeError(- `Invalid value for parameter "${key}": ${value}`- );- }- } else if (key === 'server_max_window_bits') {- const num = +value;- if (!Number.isInteger(num) || num < 8 || num > 15) {- throw new TypeError(- `Invalid value for parameter "${key}": ${value}`- );- }- value = num;- } else if (- key === 'client_no_context_takeover' ||- key === 'server_no_context_takeover'- ) {- if (value !== true) {- throw new TypeError(- `Invalid value for parameter "${key}": ${value}`- );- }- } else {- throw new Error(`Unknown parameter "${key}"`);- }-- params[key] = value;- });- });-- return configurations;- }-- /**- * Decompress data. Concurrency limited by async-limiter.- *- * @param {Buffer} data Compressed data- * @param {Boolean} fin Specifies whether or not this is the last fragment- * @param {Function} callback Callback- * @public- */- decompress (data, fin, callback) {- zlibLimiter.push((done) => {- this._decompress(data, fin, (err, result) => {- done();- callback(err, result);- });- });- }-- /**- * Compress data. Concurrency limited by async-limiter.- *- * @param {Buffer} data Data to compress- * @param {Boolean} fin Specifies whether or not this is the last fragment- * @param {Function} callback Callback- * @public- */- compress (data, fin, callback) {- zlibLimiter.push((done) => {- this._compress(data, fin, (err, result) => {- done();- callback(err, result);- });- });- }-- /**- * Decompress data.- *- * @param {Buffer} data Compressed data- * @param {Boolean} fin Specifies whether or not this is the last fragment- * @param {Function} callback Callback- * @private- */- _decompress (data, fin, callback) {- const endpoint = this._isServer ? 'client' : 'server';-- if (!this._inflate) {- const key = `${endpoint}_max_window_bits`;- const windowBits = typeof this.params[key] !== 'number'- ? zlib.Z_DEFAULT_WINDOWBITS- : this.params[key];-- this._inflate = zlib.createInflateRaw(- Object.assign({}, this._options.zlibInflateOptions, { windowBits })- );- this._inflate[kPerMessageDeflate] = this;- this._inflate[kTotalLength] = 0;- this._inflate[kBuffers] = [];- this._inflate.on('error', inflateOnError);- this._inflate.on('data', inflateOnData);- }-- this._inflate[kCallback] = callback;- this._inflate[kWriteInProgress] = true;-- this._inflate.write(data);- if (fin) this._inflate.write(TRAILER);-- this._inflate.flush(() => {- const err = this._inflate[kError];-- if (err) {- this._inflate.close();- this._inflate = null;- callback(err);- return;- }-- const data = bufferUtil.concat(- this._inflate[kBuffers],- this._inflate[kTotalLength]- );-- if (- (fin && this.params[`${endpoint}_no_context_takeover`]) ||- this._inflate[kPendingClose]- ) {- this._inflate.close();- this._inflate = null;- } else {- this._inflate[kWriteInProgress] = false;- this._inflate[kTotalLength] = 0;- this._inflate[kBuffers] = [];- }-- callback(null, data);- });- }-- /**- * Compress data.- *- * @param {Buffer} data Data to compress- * @param {Boolean} fin Specifies whether or not this is the last fragment- * @param {Function} callback Callback- * @private- */- _compress (data, fin, callback) {- if (!data || data.length === 0) {- process.nextTick(callback, null, EMPTY_BLOCK);- return;- }-- const endpoint = this._isServer ? 'server' : 'client';-- if (!this._deflate) {- const key = `${endpoint}_max_window_bits`;- const windowBits = typeof this.params[key] !== 'number'- ? zlib.Z_DEFAULT_WINDOWBITS- : this.params[key];-- this._deflate = zlib.createDeflateRaw(- Object.assign(- // TODO deprecate memLevel/level and recommend zlibDeflateOptions instead- {- memLevel: this._options.memLevel,- level: this._options.level- },- this._options.zlibDeflateOptions,- { windowBits }- )- );-- this._deflate[kTotalLength] = 0;- this._deflate[kBuffers] = [];-- //- // `zlib.DeflateRaw` emits an `'error'` event only when an attempt to use- // it is made after it has already been closed. This cannot happen here,- // so we only add a listener for the `'data'` event.- //- this._deflate.on('data', deflateOnData);- }-- this._deflate[kWriteInProgress] = true;-- this._deflate.write(data);- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {- var data = bufferUtil.concat(- this._deflate[kBuffers],- this._deflate[kTotalLength]- );-- if (fin) data = data.slice(0, data.length - 4);-- if (- (fin && this.params[`${endpoint}_no_context_takeover`]) ||- this._deflate[kPendingClose]- ) {- this._deflate.close();- this._deflate = null;- } else {- this._deflate[kWriteInProgress] = false;- this._deflate[kTotalLength] = 0;- this._deflate[kBuffers] = [];- }-- callback(null, data);- });- }-}--var permessageDeflate = PerMessageDeflate;--/**- * The listener of the `zlib.DeflateRaw` stream `'data'` event.- *- * @param {Buffer} chunk A chunk of data- * @private- */-function deflateOnData (chunk) {- this[kBuffers].push(chunk);- this[kTotalLength] += chunk.length;-}--/**- * The listener of the `zlib.InflateRaw` stream `'data'` event.- *- * @param {Buffer} chunk A chunk of data- * @private- */-function inflateOnData (chunk) {- this[kTotalLength] += chunk.length;-- if (- this[kPerMessageDeflate]._maxPayload < 1 ||- this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload- ) {- this[kBuffers].push(chunk);- return;- }-- this[kError] = new RangeError('Max payload size exceeded');- this[kError][constants$3.kStatusCode] = 1009;- this.removeListener('data', inflateOnData);- this.reset();-}--/**- * The listener of the `zlib.InflateRaw` stream `'error'` event.- *- * @param {Error} err The emitted error- * @private- */-function inflateOnError (err) {- //- // There is no need to call `Zlib#close()` as the handle is automatically- // closed when an error is emitted.- //- this[kPerMessageDeflate]._inflate = null;- err[constants$3.kStatusCode] = 1007;- this[kCallback](err);-}--/**- * Class representing an event.- *- * @private- */-class Event {- /**- * Create a new `Event`.- *- * @param {String} type The name of the event- * @param {Object} target A reference to the target to which the event was dispatched- */- constructor (type, target) {- this.target = target;- this.type = type;- }-}--/**- * Class representing a message event.- *- * @extends Event- * @private- */-class MessageEvent extends Event {- /**- * Create a new `MessageEvent`.- *- * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data- * @param {WebSocket} target A reference to the target to which the event was dispatched- */- constructor (data, target) {- super('message', target);-- this.data = data;- }-}--/**- * Class representing a close event.- *- * @extends Event- * @private- */-class CloseEvent extends Event {- /**- * Create a new `CloseEvent`.- *- * @param {Number} code The status code explaining why the connection is being closed- * @param {String} reason A human-readable string explaining why the connection is closing- * @param {WebSocket} target A reference to the target to which the event was dispatched- */- constructor (code, reason, target) {- super('close', target);-- this.wasClean = target._closeFrameReceived && target._closeFrameSent;- this.reason = reason;- this.code = code;- }-}--/**- * Class representing an open event.- *- * @extends Event- * @private- */-class OpenEvent extends Event {- /**- * Create a new `OpenEvent`.- *- * @param {WebSocket} target A reference to the target to which the event was dispatched- */- constructor (target) {- super('open', target);- }-}--/**- * Class representing an error event.- *- * @extends Event- * @private- */-class ErrorEvent extends Event {- /**- * Create a new `ErrorEvent`.- *- * @param {Object} error The error that generated this event- * @param {WebSocket} target A reference to the target to which the event was dispatched- */- constructor (error, target) {- super('error', target);-- this.message = error.message;- this.error = error;- }-}--/**- * This provides methods for emulating the `EventTarget` interface. It's not- * meant to be used directly.- *- * @mixin- */-const EventTarget = {- /**- * Register an event listener.- *- * @param {String} method A string representing the event type to listen for- * @param {Function} listener The listener to add- * @public- */- addEventListener (method, listener) {- if (typeof listener !== 'function') return;-- function onMessage (data) {- listener.call(this, new MessageEvent(data, this));- }-- function onClose (code, message) {- listener.call(this, new CloseEvent(code, message, this));- }-- function onError (error) {- listener.call(this, new ErrorEvent(error, this));- }-- function onOpen () {- listener.call(this, new OpenEvent(this));- }-- if (method === 'message') {- onMessage._listener = listener;- this.on(method, onMessage);- } else if (method === 'close') {- onClose._listener = listener;- this.on(method, onClose);- } else if (method === 'error') {- onError._listener = listener;- this.on(method, onError);- } else if (method === 'open') {- onOpen._listener = listener;- this.on(method, onOpen);- } else {- this.on(method, listener);- }- },-- /**- * Remove an event listener.- *- * @param {String} method A string representing the event type to remove- * @param {Function} listener The listener to remove- * @public- */- removeEventListener (method, listener) {- const listeners = this.listeners(method);-- for (var i = 0; i < listeners.length; i++) {- if (listeners[i] === listener || listeners[i]._listener === listener) {- this.removeListener(method, listeners[i]);- }- }- }-};--var eventTarget = EventTarget;--//-// Allowed token characters:-//-// '!', '#', '$', '%', '&', ''', '*', '+', '-',-// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'-//-// tokenChars[32] === 0 // ' '-// tokenChars[33] === 1 // '!'-// tokenChars[34] === 0 // '"'-// ...-//-const tokenChars = [- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31- 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63- 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127-];--/**- * Adds an offer to the map of extension offers or a parameter to the map of- * parameters.- *- * @param {Object} dest The map of extension offers or parameters- * @param {String} name The extension or parameter name- * @param {(Object|Boolean|String)} elem The extension parameters or the- * parameter value- * @private- */-function push (dest, name, elem) {- if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem);- else dest[name] = [elem];-}--/**- * Parses the `Sec-WebSocket-Extensions` header into an object.- *- * @param {String} header The field value of the header- * @return {Object} The parsed object- * @public- */-function parse$3 (header) {- const offers = {};-- if (header === undefined || header === '') return offers;-- var params = {};- var mustUnescape = false;- var isEscaping = false;- var inQuotes = false;- var extensionName;- var paramName;- var start = -1;- var end = -1;-- for (var i = 0; i < header.length; i++) {- const code = header.charCodeAt(i);-- if (extensionName === undefined) {- if (end === -1 && tokenChars[code] === 1) {- if (start === -1) start = i;- } else if (code === 0x20/* ' ' */|| code === 0x09/* '\t' */) {- if (end === -1 && start !== -1) end = i;- } else if (code === 0x3b/* ';' */ || code === 0x2c/* ',' */) {- if (start === -1) {- throw new SyntaxError(`Unexpected character at index ${i}`);- }-- if (end === -1) end = i;- const name = header.slice(start, end);- if (code === 0x2c) {- push(offers, name, params);- params = {};- } else {- extensionName = name;- }-- start = end = -1;- } else {- throw new SyntaxError(`Unexpected character at index ${i}`);- }- } else if (paramName === undefined) {- if (end === -1 && tokenChars[code] === 1) {- if (start === -1) start = i;- } else if (code === 0x20 || code === 0x09) {- if (end === -1 && start !== -1) end = i;- } else if (code === 0x3b || code === 0x2c) {- if (start === -1) {- throw new SyntaxError(`Unexpected character at index ${i}`);- }-- if (end === -1) end = i;- push(params, header.slice(start, end), true);- if (code === 0x2c) {- push(offers, extensionName, params);- params = {};- extensionName = undefined;- }-- start = end = -1;- } else if (code === 0x3d/* '=' */&& start !== -1 && end === -1) {- paramName = header.slice(start, i);- start = end = -1;- } else {- throw new SyntaxError(`Unexpected character at index ${i}`);- }- } else {- //- // The value of a quoted-string after unescaping must conform to the- // token ABNF, so only token characters are valid.- // Ref: https://tools.ietf.org/html/rfc6455#section-9.1- //- if (isEscaping) {- if (tokenChars[code] !== 1) {- throw new SyntaxError(`Unexpected character at index ${i}`);- }- if (start === -1) start = i;- else if (!mustUnescape) mustUnescape = true;- isEscaping = false;- } else if (inQuotes) {- if (tokenChars[code] === 1) {- if (start === -1) start = i;- } else if (code === 0x22/* '"' */ && start !== -1) {- inQuotes = false;- end = i;- } else if (code === 0x5c/* '\' */) {- isEscaping = true;- } else {- throw new SyntaxError(`Unexpected character at index ${i}`);- }- } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {- inQuotes = true;- } else if (end === -1 && tokenChars[code] === 1) {- if (start === -1) start = i;- } else if (start !== -1 && (code === 0x20 || code === 0x09)) {- if (end === -1) end = i;- } else if (code === 0x3b || code === 0x2c) {- if (start === -1) {- throw new SyntaxError(`Unexpected character at index ${i}`);- }-- if (end === -1) end = i;- var value = header.slice(start, end);- if (mustUnescape) {- value = value.replace(/\\/g, '');- mustUnescape = false;- }- push(params, paramName, value);- if (code === 0x2c) {- push(offers, extensionName, params);- params = {};- extensionName = undefined;- }-- paramName = undefined;- start = end = -1;- } else {- throw new SyntaxError(`Unexpected character at index ${i}`);- }- }- }-- if (start === -1 || inQuotes) {- throw new SyntaxError('Unexpected end of input');- }-- if (end === -1) end = i;- const token = header.slice(start, end);- if (extensionName === undefined) {- push(offers, token, {});- } else {- if (paramName === undefined) {- push(params, token, true);- } else if (mustUnescape) {- push(params, paramName, token.replace(/\\/g, ''));- } else {- push(params, paramName, token);- }- push(offers, extensionName, params);- }-- return offers;-}--/**- * Builds the `Sec-WebSocket-Extensions` header field value.- *- * @param {Object} extensions The map of extensions and parameters to format- * @return {String} A string representing the given object- * @public- */-function format (extensions) {- return Object.keys(extensions).map((extension) => {- var configurations = extensions[extension];- if (!Array.isArray(configurations)) configurations = [configurations];- return configurations.map((params) => {- return [extension].concat(Object.keys(params).map((k) => {- var values = params[k];- if (!Array.isArray(values)) values = [values];- return values.map((v) => v === true ? k : `${k}=${v}`).join('; ');- })).join('; ');- }).join(', ');- }).join(', ');-}--var extension = { format, parse: parse$3 };--var validation = createCommonjsModule(function (module, exports) {--try {- const isValidUTF8 = require('utf-8-validate');-- exports.isValidUTF8 = typeof isValidUTF8 === 'object'- ? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0- : isValidUTF8;-} catch (e) /* istanbul ignore next */ {- exports.isValidUTF8 = () => true;-}--/**- * Checks if a status code is allowed in a close frame.- *- * @param {Number} code The status code- * @return {Boolean} `true` if the status code is valid, else `false`- * @public- */-exports.isValidStatusCode = (code) => {- return (- (code >= 1000 &&- code <= 1013 &&- code !== 1004 &&- code !== 1005 &&- code !== 1006) ||- (code >= 3000 && code <= 4999)- );-};-});--const GET_INFO = 0;-const GET_PAYLOAD_LENGTH_16 = 1;-const GET_PAYLOAD_LENGTH_64 = 2;-const GET_MASK = 3;-const GET_DATA = 4;-const INFLATING = 5;--/**- * HyBi Receiver implementation.- *- * @extends stream.Writable- */-class Receiver extends Stream$2.Writable {- /**- * Creates a Receiver instance.- *- * @param {String} binaryType The type for binary data- * @param {Object} extensions An object containing the negotiated extensions- * @param {Number} maxPayload The maximum allowed message length- */- constructor (binaryType, extensions, maxPayload) {- super();-- this._binaryType = binaryType || constants$3.BINARY_TYPES[0];- this[constants$3.kWebSocket] = undefined;- this._extensions = extensions || {};- this._maxPayload = maxPayload | 0;-- this._bufferedBytes = 0;- this._buffers = [];-- this._compressed = false;- this._payloadLength = 0;- this._mask = undefined;- this._fragmented = 0;- this._masked = false;- this._fin = false;- this._opcode = 0;-- this._totalPayloadLength = 0;- this._messageLength = 0;- this._fragments = [];-- this._state = GET_INFO;- this._loop = false;- }-- /**- * Implements `Writable.prototype._write()`.- *- * @param {Buffer} chunk The chunk of data to write- * @param {String} encoding The character encoding of `chunk`- * @param {Function} cb Callback- */- _write (chunk, encoding, cb) {- if (this._opcode === 0x08) return cb();-- this._bufferedBytes += chunk.length;- this._buffers.push(chunk);- this.startLoop(cb);- }-- /**- * Consumes `n` bytes from the buffered data.- *- * @param {Number} n The number of bytes to consume- * @return {Buffer} The consumed bytes- * @private- */- consume (n) {- this._bufferedBytes -= n;-- if (n === this._buffers[0].length) return this._buffers.shift();-- if (n < this._buffers[0].length) {- const buf = this._buffers[0];- this._buffers[0] = buf.slice(n);- return buf.slice(0, n);- }-- const dst = Buffer.allocUnsafe(n);-- do {- const buf = this._buffers[0];-- if (n >= buf.length) {- this._buffers.shift().copy(dst, dst.length - n);- } else {- buf.copy(dst, dst.length - n, 0, n);- this._buffers[0] = buf.slice(n);- }-- n -= buf.length;- } while (n > 0);-- return dst;- }-- /**- * Starts the parsing loop.- *- * @param {Function} cb Callback- * @private- */- startLoop (cb) {- var err;- this._loop = true;-- do {- switch (this._state) {- case GET_INFO:- err = this.getInfo();- break;- case GET_PAYLOAD_LENGTH_16:- err = this.getPayloadLength16();- break;- case GET_PAYLOAD_LENGTH_64:- err = this.getPayloadLength64();- break;- case GET_MASK:- this.getMask();- break;- case GET_DATA:- err = this.getData(cb);- break;- default: // `INFLATING`- this._loop = false;- return;- }- } while (this._loop);-- cb(err);- }-- /**- * Reads the first two bytes of a frame.- *- * @return {(RangeError|undefined)} A possible error- * @private- */- getInfo () {- if (this._bufferedBytes < 2) {- this._loop = false;- return;- }-- const buf = this.consume(2);-- if ((buf[0] & 0x30) !== 0x00) {- this._loop = false;- return error$1(RangeError, 'RSV2 and RSV3 must be clear', true, 1002);- }-- const compressed = (buf[0] & 0x40) === 0x40;-- if (compressed && !this._extensions[permessageDeflate.extensionName]) {- this._loop = false;- return error$1(RangeError, 'RSV1 must be clear', true, 1002);- }-- this._fin = (buf[0] & 0x80) === 0x80;- this._opcode = buf[0] & 0x0f;- this._payloadLength = buf[1] & 0x7f;-- if (this._opcode === 0x00) {- if (compressed) {- this._loop = false;- return error$1(RangeError, 'RSV1 must be clear', true, 1002);- }-- if (!this._fragmented) {- this._loop = false;- return error$1(RangeError, 'invalid opcode 0', true, 1002);- }-- this._opcode = this._fragmented;- } else if (this._opcode === 0x01 || this._opcode === 0x02) {- if (this._fragmented) {- this._loop = false;- return error$1(RangeError, `invalid opcode ${this._opcode}`, true, 1002);- }-- this._compressed = compressed;- } else if (this._opcode > 0x07 && this._opcode < 0x0b) {- if (!this._fin) {- this._loop = false;- return error$1(RangeError, 'FIN must be set', true, 1002);- }-- if (compressed) {- this._loop = false;- return error$1(RangeError, 'RSV1 must be clear', true, 1002);- }-- if (this._payloadLength > 0x7d) {- this._loop = false;- return error$1(- RangeError,- `invalid payload length ${this._payloadLength}`,- true,- 1002- );- }- } else {- this._loop = false;- return error$1(RangeError, `invalid opcode ${this._opcode}`, true, 1002);- }-- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;- this._masked = (buf[1] & 0x80) === 0x80;-- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;- else return this.haveLength();- }-- /**- * Gets extended payload length (7+16).- *- * @return {(RangeError|undefined)} A possible error- * @private- */- getPayloadLength16 () {- if (this._bufferedBytes < 2) {- this._loop = false;- return;- }-- this._payloadLength = this.consume(2).readUInt16BE(0);- return this.haveLength();- }-- /**- * Gets extended payload length (7+64).- *- * @return {(RangeError|undefined)} A possible error- * @private- */- getPayloadLength64 () {- if (this._bufferedBytes < 8) {- this._loop = false;- return;- }-- const buf = this.consume(8);- const num = buf.readUInt32BE(0);-- //- // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned- // if payload length is greater than this number.- //- if (num > Math.pow(2, 53 - 32) - 1) {- this._loop = false;- return error$1(- RangeError,- 'Unsupported WebSocket frame: payload length > 2^53 - 1',- false,- 1009- );- }-- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);- return this.haveLength();- }-- /**- * Payload length has been read.- *- * @return {(RangeError|undefined)} A possible error- * @private- */- haveLength () {- if (this._payloadLength && this._opcode < 0x08) {- this._totalPayloadLength += this._payloadLength;- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {- this._loop = false;- return error$1(RangeError, 'Max payload size exceeded', false, 1009);- }- }-- if (this._masked) this._state = GET_MASK;- else this._state = GET_DATA;- }-- /**- * Reads mask bytes.- *- * @private- */- getMask () {- if (this._bufferedBytes < 4) {- this._loop = false;- return;- }-- this._mask = this.consume(4);- this._state = GET_DATA;- }-- /**- * Reads data bytes.- *- * @param {Function} cb Callback- * @return {(Error|RangeError|undefined)} A possible error- * @private- */- getData (cb) {- var data = constants$3.EMPTY_BUFFER;-- if (this._payloadLength) {- if (this._bufferedBytes < this._payloadLength) {- this._loop = false;- return;- }-- data = this.consume(this._payloadLength);- if (this._masked) bufferUtil.unmask(data, this._mask);- }-- if (this._opcode > 0x07) return this.controlMessage(data);-- if (this._compressed) {- this._state = INFLATING;- this.decompress(data, cb);- return;- }-- if (data.length) {- //- // This message is not compressed so its lenght is the sum of the payload- // length of all fragments.- //- this._messageLength = this._totalPayloadLength;- this._fragments.push(data);- }-- return this.dataMessage();- }-- /**- * Decompresses data.- *- * @param {Buffer} data Compressed data- * @param {Function} cb Callback- * @private- */- decompress (data, cb) {- const perMessageDeflate = this._extensions[permessageDeflate.extensionName];-- perMessageDeflate.decompress(data, this._fin, (err, buf) => {- if (err) return cb(err);-- if (buf.length) {- this._messageLength += buf.length;- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {- return cb(error$1(RangeError, 'Max payload size exceeded', false, 1009));- }-- this._fragments.push(buf);- }-- const er = this.dataMessage();- if (er) return cb(er);-- this.startLoop(cb);- });- }-- /**- * Handles a data message.- *- * @return {(Error|undefined)} A possible error- * @private- */- dataMessage () {- if (this._fin) {- const messageLength = this._messageLength;- const fragments = this._fragments;-- this._totalPayloadLength = 0;- this._messageLength = 0;- this._fragmented = 0;- this._fragments = [];-- if (this._opcode === 2) {- var data;-- if (this._binaryType === 'nodebuffer') {- data = toBuffer(fragments, messageLength);- } else if (this._binaryType === 'arraybuffer') {- data = toArrayBuffer(toBuffer(fragments, messageLength));- } else {- data = fragments;- }-- this.emit('message', data);- } else {- const buf = toBuffer(fragments, messageLength);-- if (!validation.isValidUTF8(buf)) {- this._loop = false;- return error$1(Error, 'invalid UTF-8 sequence', true, 1007);- }-- this.emit('message', buf.toString());- }- }-- this._state = GET_INFO;- }-- /**- * Handles a control message.- *- * @param {Buffer} data Data to handle- * @return {(Error|RangeError|undefined)} A possible error- * @private- */- controlMessage (data) {- if (this._opcode === 0x08) {- this._loop = false;-- if (data.length === 0) {- this.emit('conclude', 1005, '');- this.end();- } else if (data.length === 1) {- return error$1(RangeError, 'invalid payload length 1', true, 1002);- } else {- const code = data.readUInt16BE(0);-- if (!validation.isValidStatusCode(code)) {- return error$1(RangeError, `invalid status code ${code}`, true, 1002);- }-- const buf = data.slice(2);-- if (!validation.isValidUTF8(buf)) {- return error$1(Error, 'invalid UTF-8 sequence', true, 1007);- }-- this.emit('conclude', code, buf.toString());- this.end();- }-- return;- }-- if (this._opcode === 0x09) this.emit('ping', data);- else this.emit('pong', data);-- this._state = GET_INFO;- }-}--var receiver = Receiver;--/**- * Builds an error object.- *- * @param {(Error|RangeError)} ErrorCtor The error constructor- * @param {String} message The error message- * @param {Boolean} prefix Specifies whether or not to add a default prefix to- * `message`- * @param {Number} statusCode The status code- * @return {(Error|RangeError)} The error- * @private- */-function error$1 (ErrorCtor, message, prefix, statusCode) {- const err = new ErrorCtor(- prefix ? `Invalid WebSocket frame: ${message}` : message- );-- Error.captureStackTrace(err, error$1);- err[constants$3.kStatusCode] = statusCode;- return err;-}--/**- * Makes a buffer from a list of fragments.- *- * @param {Buffer[]} fragments The list of fragments composing the message- * @param {Number} messageLength The length of the message- * @return {Buffer}- * @private- */-function toBuffer (fragments, messageLength) {- if (fragments.length === 1) return fragments[0];- if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength);- return constants$3.EMPTY_BUFFER;-}--/**- * Converts a buffer to an `ArrayBuffer`.- *- * @param {Buffer} The buffer to convert- * @return {ArrayBuffer} Converted buffer- */-function toArrayBuffer (buf) {- if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {- return buf.buffer;- }-- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);-}--/**- * HyBi Sender implementation.- */-class Sender {- /**- * Creates a Sender instance.- *- * @param {net.Socket} socket The connection socket- * @param {Object} extensions An object containing the negotiated extensions- */- constructor (socket, extensions) {- this._extensions = extensions || {};- this._socket = socket;-- this._firstFragment = true;- this._compress = false;-- this._bufferedBytes = 0;- this._deflating = false;- this._queue = [];- }-- /**- * Frames a piece of data according to the HyBi WebSocket protocol.- *- * @param {Buffer} data The data to frame- * @param {Object} options Options object- * @param {Number} options.opcode The opcode- * @param {Boolean} options.readOnly Specifies whether `data` can be modified- * @param {Boolean} options.fin Specifies whether or not to set the FIN bit- * @param {Boolean} options.mask Specifies whether or not to mask `data`- * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit- * @return {Buffer[]} The framed data as a list of `Buffer` instances- * @public- */- static frame (data, options) {- const merge = data.length < 1024 || (options.mask && options.readOnly);- var offset = options.mask ? 6 : 2;- var payloadLength = data.length;-- if (data.length >= 65536) {- offset += 8;- payloadLength = 127;- } else if (data.length > 125) {- offset += 2;- payloadLength = 126;- }-- const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);-- target[0] = options.fin ? options.opcode | 0x80 : options.opcode;- if (options.rsv1) target[0] |= 0x40;-- if (payloadLength === 126) {- target.writeUInt16BE(data.length, 2);- } else if (payloadLength === 127) {- target.writeUInt32BE(0, 2);- target.writeUInt32BE(data.length, 6);- }-- if (!options.mask) {- target[1] = payloadLength;- if (merge) {- data.copy(target, offset);- return [target];- }-- return [target, data];- }-- const mask = crypto.randomBytes(4);-- target[1] = payloadLength | 0x80;- target[offset - 4] = mask[0];- target[offset - 3] = mask[1];- target[offset - 2] = mask[2];- target[offset - 1] = mask[3];-- if (merge) {- bufferUtil.mask(data, mask, target, offset, data.length);- return [target];- }-- bufferUtil.mask(data, mask, data, 0, data.length);- return [target, data];- }-- /**- * Sends a close message to the other peer.- *- * @param {(Number|undefined)} code The status code component of the body- * @param {String} data The message component of the body- * @param {Boolean} mask Specifies whether or not to mask the message- * @param {Function} cb Callback- * @public- */- close (code, data, mask, cb) {- var buf;-- if (code === undefined) {- buf = constants$3.EMPTY_BUFFER;- } else if (typeof code !== 'number' || !validation.isValidStatusCode(code)) {- throw new TypeError('First argument must be a valid error code number');- } else if (data === undefined || data === '') {- buf = Buffer.allocUnsafe(2);- buf.writeUInt16BE(code, 0);- } else {- buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));- buf.writeUInt16BE(code, 0);- buf.write(data, 2);- }-- if (this._deflating) {- this.enqueue([this.doClose, buf, mask, cb]);- } else {- this.doClose(buf, mask, cb);- }- }-- /**- * Frames and sends a close message.- *- * @param {Buffer} data The message to send- * @param {Boolean} mask Specifies whether or not to mask `data`- * @param {Function} cb Callback- * @private- */- doClose (data, mask, cb) {- this.sendFrame(Sender.frame(data, {- fin: true,- rsv1: false,- opcode: 0x08,- mask,- readOnly: false- }), cb);- }-- /**- * Sends a ping message to the other peer.- *- * @param {*} data The message to send- * @param {Boolean} mask Specifies whether or not to mask `data`- * @param {Function} cb Callback- * @public- */- ping (data, mask, cb) {- var readOnly = true;-- if (!Buffer.isBuffer(data)) {- if (data instanceof ArrayBuffer) {- data = Buffer.from(data);- } else if (ArrayBuffer.isView(data)) {- data = viewToBuffer(data);- } else {- data = Buffer.from(data);- readOnly = false;- }- }-- if (this._deflating) {- this.enqueue([this.doPing, data, mask, readOnly, cb]);- } else {- this.doPing(data, mask, readOnly, cb);- }- }-- /**- * Frames and sends a ping message.- *- * @param {*} data The message to send- * @param {Boolean} mask Specifies whether or not to mask `data`- * @param {Boolean} readOnly Specifies whether `data` can be modified- * @param {Function} cb Callback- * @private- */- doPing (data, mask, readOnly, cb) {- this.sendFrame(Sender.frame(data, {- fin: true,- rsv1: false,- opcode: 0x09,- mask,- readOnly- }), cb);- }-- /**- * Sends a pong message to the other peer.- *- * @param {*} data The message to send- * @param {Boolean} mask Specifies whether or not to mask `data`- * @param {Function} cb Callback- * @public- */- pong (data, mask, cb) {- var readOnly = true;-- if (!Buffer.isBuffer(data)) {- if (data instanceof ArrayBuffer) {- data = Buffer.from(data);- } else if (ArrayBuffer.isView(data)) {- data = viewToBuffer(data);- } else {- data = Buffer.from(data);- readOnly = false;- }- }-- if (this._deflating) {- this.enqueue([this.doPong, data, mask, readOnly, cb]);- } else {- this.doPong(data, mask, readOnly, cb);- }- }-- /**- * Frames and sends a pong message.- *- * @param {*} data The message to send- * @param {Boolean} mask Specifies whether or not to mask `data`- * @param {Boolean} readOnly Specifies whether `data` can be modified- * @param {Function} cb Callback- * @private- */- doPong (data, mask, readOnly, cb) {- this.sendFrame(Sender.frame(data, {- fin: true,- rsv1: false,- opcode: 0x0a,- mask,- readOnly- }), cb);- }-- /**- * Sends a data message to the other peer.- *- * @param {*} data The message to send- * @param {Object} options Options object- * @param {Boolean} options.compress Specifies whether or not to compress `data`- * @param {Boolean} options.binary Specifies whether `data` is binary or text- * @param {Boolean} options.fin Specifies whether the fragment is the last one- * @param {Boolean} options.mask Specifies whether or not to mask `data`- * @param {Function} cb Callback- * @public- */- send (data, options, cb) {- var opcode = options.binary ? 2 : 1;- var rsv1 = options.compress;- var readOnly = true;-- if (!Buffer.isBuffer(data)) {- if (data instanceof ArrayBuffer) {- data = Buffer.from(data);- } else if (ArrayBuffer.isView(data)) {- data = viewToBuffer(data);- } else {- data = Buffer.from(data);- readOnly = false;- }- }-- const perMessageDeflate = this._extensions[permessageDeflate.extensionName];-- if (this._firstFragment) {- this._firstFragment = false;- if (rsv1 && perMessageDeflate) {- rsv1 = data.length >= perMessageDeflate._threshold;- }- this._compress = rsv1;- } else {- rsv1 = false;- opcode = 0;- }-- if (options.fin) this._firstFragment = true;-- if (perMessageDeflate) {- const opts = {- fin: options.fin,- rsv1,- opcode,- mask: options.mask,- readOnly- };-- if (this._deflating) {- this.enqueue([this.dispatch, data, this._compress, opts, cb]);- } else {- this.dispatch(data, this._compress, opts, cb);- }- } else {- this.sendFrame(Sender.frame(data, {- fin: options.fin,- rsv1: false,- opcode,- mask: options.mask,- readOnly- }), cb);- }- }-- /**- * Dispatches a data message.- *- * @param {Buffer} data The message to send- * @param {Boolean} compress Specifies whether or not to compress `data`- * @param {Object} options Options object- * @param {Number} options.opcode The opcode- * @param {Boolean} options.readOnly Specifies whether `data` can be modified- * @param {Boolean} options.fin Specifies whether or not to set the FIN bit- * @param {Boolean} options.mask Specifies whether or not to mask `data`- * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit- * @param {Function} cb Callback- * @private- */- dispatch (data, compress, options, cb) {- if (!compress) {- this.sendFrame(Sender.frame(data, options), cb);- return;- }-- const perMessageDeflate = this._extensions[permessageDeflate.extensionName];-- this._deflating = true;- perMessageDeflate.compress(data, options.fin, (_, buf) => {- options.readOnly = false;- this.sendFrame(Sender.frame(buf, options), cb);- this._deflating = false;- this.dequeue();- });- }-- /**- * Executes queued send operations.- *- * @private- */- dequeue () {- while (!this._deflating && this._queue.length) {- const params = this._queue.shift();-- this._bufferedBytes -= params[1].length;- params[0].apply(this, params.slice(1));- }- }-- /**- * Enqueues a send operation.- *- * @param {Array} params Send operation parameters.- * @private- */- enqueue (params) {- this._bufferedBytes += params[1].length;- this._queue.push(params);- }-- /**- * Sends a frame.- *- * @param {Buffer[]} list The frame to send- * @param {Function} cb Callback- * @private- */- sendFrame (list, cb) {- if (list.length === 2) {- this._socket.write(list[0]);- this._socket.write(list[1], cb);- } else {- this._socket.write(list[0], cb);- }- }-}--var sender = Sender;--/**- * Converts an `ArrayBuffer` view into a buffer.- *- * @param {(DataView|TypedArray)} view The view to convert- * @return {Buffer} Converted view- * @private- */-function viewToBuffer (view) {- const buf = Buffer.from(view.buffer);-- if (view.byteLength !== view.buffer.byteLength) {- return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);- }-- return buf;-}--const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];-const kWebSocket = constants$3.kWebSocket;-const protocolVersions = [8, 13];-const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly.--/**- * Class representing a WebSocket.- *- * @extends EventEmitter- */-class WebSocket extends EventEmitter {- /**- * Create a new `WebSocket`.- *- * @param {(String|url.Url|url.URL)} address The URL to which to connect- * @param {(String|String[])} protocols The subprotocols- * @param {Object} options Connection options- */- constructor (address, protocols, options) {- super();-- this.readyState = WebSocket.CONNECTING;- this.protocol = '';-- this._binaryType = constants$3.BINARY_TYPES[0];- this._closeFrameReceived = false;- this._closeFrameSent = false;- this._closeMessage = '';- this._closeTimer = null;- this._closeCode = 1006;- this._extensions = {};- this._isServer = true;- this._receiver = null;- this._sender = null;- this._socket = null;-- if (address !== null) {- if (Array.isArray(protocols)) {- protocols = protocols.join(', ');- } else if (typeof protocols === 'object' && protocols !== null) {- options = protocols;- protocols = undefined;- }-- initAsClient.call(this, address, protocols, options);- }- }-- get CONNECTING () { return WebSocket.CONNECTING; }- get CLOSING () { return WebSocket.CLOSING; }- get CLOSED () { return WebSocket.CLOSED; }- get OPEN () { return WebSocket.OPEN; }-- /**- * This deviates from the WHATWG interface since ws doesn't support the required- * default "blob" type (instead we define a custom "nodebuffer" type).- *- * @type {String}- */- get binaryType () {- return this._binaryType;- }-- set binaryType (type) {- if (constants$3.BINARY_TYPES.indexOf(type) < 0) return;-- this._binaryType = type;-- //- // Allow to change `binaryType` on the fly.- //- if (this._receiver) this._receiver._binaryType = type;- }-- /**- * @type {Number}- */- get bufferedAmount () {- if (!this._socket) return 0;-- //- // `socket.bufferSize` is `undefined` if the socket is closed.- //- return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;- }-- /**- * @type {String}- */- get extensions () {- return Object.keys(this._extensions).join();- }-- /**- * Set up the socket and the internal resources.- *- * @param {net.Socket} socket The network socket between the server and client- * @param {Buffer} head The first packet of the upgraded stream- * @param {Number} maxPayload The maximum allowed message size- * @private- */- setSocket (socket, head, maxPayload) {- const receiver$1 = new receiver(- this._binaryType,- this._extensions,- maxPayload- );-- this._sender = new sender(socket, this._extensions);- this._receiver = receiver$1;- this._socket = socket;-- receiver$1[kWebSocket] = this;- socket[kWebSocket] = this;-- receiver$1.on('conclude', receiverOnConclude);- receiver$1.on('drain', receiverOnDrain);- receiver$1.on('error', receiverOnError);- receiver$1.on('message', receiverOnMessage);- receiver$1.on('ping', receiverOnPing);- receiver$1.on('pong', receiverOnPong);-- socket.setTimeout(0);- socket.setNoDelay();-- if (head.length > 0) socket.unshift(head);-- socket.on('close', socketOnClose);- socket.on('data', socketOnData);- socket.on('end', socketOnEnd);- socket.on('error', socketOnError);-- this.readyState = WebSocket.OPEN;- this.emit('open');- }-- /**- * Emit the `'close'` event.- *- * @private- */- emitClose () {- this.readyState = WebSocket.CLOSED;-- if (!this._socket) {- this.emit('close', this._closeCode, this._closeMessage);- return;- }-- if (this._extensions[permessageDeflate.extensionName]) {- this._extensions[permessageDeflate.extensionName].cleanup();- }-- this._receiver.removeAllListeners();- this.emit('close', this._closeCode, this._closeMessage);- }-- /**- * Start a closing handshake.- *- * +----------+ +-----------+ +----------+- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -- * | +----------+ +-----------+ +----------+ |- * +----------+ +-----------+ |- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING- * +----------+ +-----------+ |- * | | | +---+ |- * +------------------------+-->|fin| - - - -- * | +---+ | +---+- * - - - - -|fin|<---------------------+- * +---+- *- * @param {Number} code Status code explaining why the connection is closing- * @param {String} data A string explaining why the connection is closing- * @public- */- close (code, data) {- if (this.readyState === WebSocket.CLOSED) return;- if (this.readyState === WebSocket.CONNECTING) {- const msg = 'WebSocket was closed before the connection was established';- return abortHandshake(this, this._req, msg);- }-- if (this.readyState === WebSocket.CLOSING) {- if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();- return;- }-- this.readyState = WebSocket.CLOSING;- this._sender.close(code, data, !this._isServer, (err) => {- //- // This error is handled by the `'error'` listener on the socket. We only- // want to know if the close frame has been sent here.- //- if (err) return;-- this._closeFrameSent = true;-- if (this._socket.writable) {- if (this._closeFrameReceived) this._socket.end();-- //- // Ensure that the connection is closed even if the closing handshake- // fails.- //- this._closeTimer = setTimeout(- this._socket.destroy.bind(this._socket),- closeTimeout- );- }- });- }-- /**- * Send a ping.- *- * @param {*} data The data to send- * @param {Boolean} mask Indicates whether or not to mask `data`- * @param {Function} cb Callback which is executed when the ping is sent- * @public- */- ping (data, mask, cb) {- if (typeof data === 'function') {- cb = data;- data = mask = undefined;- } else if (typeof mask === 'function') {- cb = mask;- mask = undefined;- }-- if (this.readyState !== WebSocket.OPEN) {- const err = new Error(- `WebSocket is not open: readyState ${this.readyState} ` +- `(${readyStates[this.readyState]})`- );-- if (cb) return cb(err);- throw err;- }-- if (typeof data === 'number') data = data.toString();- if (mask === undefined) mask = !this._isServer;- this._sender.ping(data || constants$3.EMPTY_BUFFER, mask, cb);- }-- /**- * Send a pong.- *- * @param {*} data The data to send- * @param {Boolean} mask Indicates whether or not to mask `data`- * @param {Function} cb Callback which is executed when the pong is sent- * @public- */- pong (data, mask, cb) {- if (typeof data === 'function') {- cb = data;- data = mask = undefined;- } else if (typeof mask === 'function') {- cb = mask;- mask = undefined;- }-- if (this.readyState !== WebSocket.OPEN) {- const err = new Error(- `WebSocket is not open: readyState ${this.readyState} ` +- `(${readyStates[this.readyState]})`- );-- if (cb) return cb(err);- throw err;- }-- if (typeof data === 'number') data = data.toString();- if (mask === undefined) mask = !this._isServer;- this._sender.pong(data || constants$3.EMPTY_BUFFER, mask, cb);- }-- /**- * Send a data message.- *- * @param {*} data The message to send- * @param {Object} options Options object- * @param {Boolean} options.compress Specifies whether or not to compress `data`- * @param {Boolean} options.binary Specifies whether `data` is binary or text- * @param {Boolean} options.fin Specifies whether the fragment is the last one- * @param {Boolean} options.mask Specifies whether or not to mask `data`- * @param {Function} cb Callback which is executed when data is written out- * @public- */- send (data, options, cb) {- if (typeof options === 'function') {- cb = options;- options = {};- }-- if (this.readyState !== WebSocket.OPEN) {- const err = new Error(- `WebSocket is not open: readyState ${this.readyState} ` +- `(${readyStates[this.readyState]})`- );-- if (cb) return cb(err);- throw err;- }-- if (typeof data === 'number') data = data.toString();-- const opts = Object.assign({- binary: typeof data !== 'string',- mask: !this._isServer,- compress: true,- fin: true- }, options);-- if (!this._extensions[permessageDeflate.extensionName]) {- opts.compress = false;- }-- this._sender.send(data || constants$3.EMPTY_BUFFER, opts, cb);- }-- /**- * Forcibly close the connection.- *- * @public- */- terminate () {- if (this.readyState === WebSocket.CLOSED) return;- if (this.readyState === WebSocket.CONNECTING) {- const msg = 'WebSocket was closed before the connection was established';- return abortHandshake(this, this._req, msg);- }-- if (this._socket) {- this.readyState = WebSocket.CLOSING;- this._socket.destroy();- }- }-}--readyStates.forEach((readyState, i) => {- WebSocket[readyStates[i]] = i;-});--//-// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.-// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface-//-['open', 'error', 'close', 'message'].forEach((method) => {- Object.defineProperty(WebSocket.prototype, `on${method}`, {- /**- * Return the listener of the event.- *- * @return {(Function|undefined)} The event listener or `undefined`- * @public- */- get () {- const listeners = this.listeners(method);- for (var i = 0; i < listeners.length; i++) {- if (listeners[i]._listener) return listeners[i]._listener;- }- },- /**- * Add a listener for the event.- *- * @param {Function} listener The listener to add- * @public- */- set (listener) {- const listeners = this.listeners(method);- for (var i = 0; i < listeners.length; i++) {- //- // Remove only the listeners added via `addEventListener`.- //- if (listeners[i]._listener) this.removeListener(method, listeners[i]);- }- this.addEventListener(method, listener);- }- });-});--WebSocket.prototype.addEventListener = eventTarget.addEventListener;-WebSocket.prototype.removeEventListener = eventTarget.removeEventListener;--var websocket = WebSocket;--/**- * Initialize a WebSocket client.- *- * @param {(String|url.Url|url.URL)} address The URL to which to connect- * @param {String} protocols The subprotocols- * @param {Object} options Connection options- * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate- * @param {Number} options.handshakeTimeout Timeout in milliseconds for the handshake request- * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header- * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header- * @private- */-function initAsClient (address, protocols, options) {- options = Object.assign({- protocolVersion: protocolVersions[1],- perMessageDeflate: true- }, options, {- createConnection: undefined,- socketPath: undefined,- hostname: undefined,- protocol: undefined,- timeout: undefined,- method: undefined,- auth: undefined,- host: undefined,- path: undefined,- port: undefined- });-- if (protocolVersions.indexOf(options.protocolVersion) === -1) {- throw new RangeError(- `Unsupported protocol version: ${options.protocolVersion} ` +- `(supported versions: ${protocolVersions.join(', ')})`- );- }-- this._isServer = false;-- var parsedUrl;-- if (typeof address === 'object' && address.href !== undefined) {- parsedUrl = address;- this.url = address.href;- } else {- parsedUrl = Url.parse(address);- this.url = address;- }-- const isUnixSocket = parsedUrl.protocol === 'ws+unix:';-- if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {- throw new Error(`Invalid URL: ${this.url}`);- }-- const isSecure = parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';- const key = crypto.randomBytes(16).toString('base64');- const httpObj = isSecure ? https : http;- const path = parsedUrl.search- ? `${parsedUrl.pathname || '/'}${parsedUrl.search}`- : parsedUrl.pathname || '/';- var perMessageDeflate;-- options.createConnection = isSecure ? tlsConnect : netConnect;- options.port = parsedUrl.port || (isSecure ? 443 : 80);- options.host = parsedUrl.hostname.startsWith('[')- ? parsedUrl.hostname.slice(1, -1)- : parsedUrl.hostname;- options.headers = Object.assign({- 'Sec-WebSocket-Version': options.protocolVersion,- 'Sec-WebSocket-Key': key,- 'Connection': 'Upgrade',- 'Upgrade': 'websocket'- }, options.headers);- options.path = path;-- if (options.perMessageDeflate) {- perMessageDeflate = new permessageDeflate(- options.perMessageDeflate !== true ? options.perMessageDeflate : {},- false- );- options.headers['Sec-WebSocket-Extensions'] = extension.format({- [permessageDeflate.extensionName]: perMessageDeflate.offer()- });- }- if (protocols) {- options.headers['Sec-WebSocket-Protocol'] = protocols;- }- if (options.origin) {- if (options.protocolVersion < 13) {- options.headers['Sec-WebSocket-Origin'] = options.origin;- } else {- options.headers.Origin = options.origin;- }- }- if (parsedUrl.auth) {- options.auth = parsedUrl.auth;- } else if (parsedUrl.username || parsedUrl.password) {- options.auth = `${parsedUrl.username}:${parsedUrl.password}`;- }-- if (isUnixSocket) {- const parts = path.split(':');-- if (options.agent == null && process.versions.modules < 57) {- //- // Setting `socketPath` in conjunction with `createConnection` without an- // agent throws an error on Node.js < 8. Work around the issue by using a- // different property.- //- options._socketPath = parts[0];- } else {- options.socketPath = parts[0];- }-- options.path = parts[1];- }-- var req = this._req = httpObj.get(options);-- if (options.handshakeTimeout) {- req.setTimeout(- options.handshakeTimeout,- () => abortHandshake(this, req, 'Opening handshake has timed out')- );- }-- req.on('error', (err) => {- if (this._req.aborted) return;-- req = this._req = null;- this.readyState = WebSocket.CLOSING;- this.emit('error', err);- this.emitClose();- });-- req.on('response', (res) => {- if (this.emit('unexpected-response', req, res)) return;-- abortHandshake(this, req, `Unexpected server response: ${res.statusCode}`);- });-- req.on('upgrade', (res, socket, head) => {- this.emit('upgrade', res);-- //- // The user may have closed the connection from a listener of the `upgrade`- // event.- //- if (this.readyState !== WebSocket.CONNECTING) return;-- req = this._req = null;-- const digest = crypto.createHash('sha1')- .update(key + constants$3.GUID, 'binary')- .digest('base64');-- if (res.headers['sec-websocket-accept'] !== digest) {- abortHandshake(this, socket, 'Invalid Sec-WebSocket-Accept header');- return;- }-- const serverProt = res.headers['sec-websocket-protocol'];- const protList = (protocols || '').split(/, */);- var protError;-- if (!protocols && serverProt) {- protError = 'Server sent a subprotocol but none was requested';- } else if (protocols && !serverProt) {- protError = 'Server sent no subprotocol';- } else if (serverProt && protList.indexOf(serverProt) === -1) {- protError = 'Server sent an invalid subprotocol';- }-- if (protError) {- abortHandshake(this, socket, protError);- return;- }-- if (serverProt) this.protocol = serverProt;-- if (perMessageDeflate) {- try {- const extensions = extension.parse(- res.headers['sec-websocket-extensions']- );-- if (extensions[permessageDeflate.extensionName]) {- perMessageDeflate.accept(- extensions[permessageDeflate.extensionName]- );- this._extensions[permessageDeflate.extensionName] = perMessageDeflate;- }- } catch (err) {- abortHandshake(this, socket, 'Invalid Sec-WebSocket-Extensions header');- return;- }- }-- this.setSocket(socket, head, 0);- });-}--/**- * Create a `net.Socket` and initiate a connection.- *- * @param {Object} options Connection options- * @return {net.Socket} The newly created socket used to start the connection- * @private- */-function netConnect (options) {- options.path = options.socketPath || options._socketPath || undefined;- return net.connect(options);-}--/**- * Create a `tls.TLSSocket` and initiate a connection.- *- * @param {Object} options Connection options- * @return {tls.TLSSocket} The newly created socket used to start the connection- * @private- */-function tlsConnect (options) {- options.path = options.socketPath || options._socketPath || undefined;- options.servername = options.servername || options.host;- return tls.connect(options);-}--/**- * Abort the handshake and emit an error.- *- * @param {WebSocket} websocket The WebSocket instance- * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the- * socket to destroy- * @param {String} message The error message- * @private- */-function abortHandshake (websocket, stream, message) {- websocket.readyState = WebSocket.CLOSING;-- const err = new Error(message);- Error.captureStackTrace(err, abortHandshake);-- if (stream.setHeader) {- stream.abort();- stream.once('abort', websocket.emitClose.bind(websocket));- websocket.emit('error', err);- } else {- stream.destroy(err);- stream.once('error', websocket.emit.bind(websocket, 'error'));- stream.once('close', websocket.emitClose.bind(websocket));- }-}--/**- * The listener of the `Receiver` `'conclude'` event.- *- * @param {Number} code The status code- * @param {String} reason The reason for closing- * @private- */-function receiverOnConclude (code, reason) {- const websocket = this[kWebSocket];-- websocket._socket.removeListener('data', socketOnData);- websocket._socket.resume();-- websocket._closeFrameReceived = true;- websocket._closeMessage = reason;- websocket._closeCode = code;-- if (code === 1005) websocket.close();- else websocket.close(code, reason);-}--/**- * The listener of the `Receiver` `'drain'` event.- *- * @private- */-function receiverOnDrain () {- this[kWebSocket]._socket.resume();-}--/**- * The listener of the `Receiver` `'error'` event.- *- * @param {(RangeError|Error)} err The emitted error- * @private- */-function receiverOnError (err) {- const websocket = this[kWebSocket];-- websocket._socket.removeListener('data', socketOnData);-- websocket.readyState = WebSocket.CLOSING;- websocket._closeCode = err[constants$3.kStatusCode];- websocket.emit('error', err);- websocket._socket.destroy();-}--/**- * The listener of the `Receiver` `'finish'` event.- *- * @private- */-function receiverOnFinish () {- this[kWebSocket].emitClose();-}--/**- * The listener of the `Receiver` `'message'` event.- *- * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message- * @private- */-function receiverOnMessage (data) {- this[kWebSocket].emit('message', data);-}--/**- * The listener of the `Receiver` `'ping'` event.- *- * @param {Buffer} data The data included in the ping frame- * @private- */-function receiverOnPing (data) {- const websocket = this[kWebSocket];-- websocket.pong(data, !websocket._isServer, constants$3.NOOP);- websocket.emit('ping', data);-}--/**- * The listener of the `Receiver` `'pong'` event.- *- * @param {Buffer} data The data included in the pong frame- * @private- */-function receiverOnPong (data) {- this[kWebSocket].emit('pong', data);-}--/**- * The listener of the `net.Socket` `'close'` event.- *- * @private- */-function socketOnClose () {- const websocket = this[kWebSocket];-- this.removeListener('close', socketOnClose);- this.removeListener('end', socketOnEnd);-- websocket.readyState = WebSocket.CLOSING;-- //- // The close frame might not have been received or the `'end'` event emitted,- // for example, if the socket was destroyed due to an error. Ensure that the- // `receiver` stream is closed after writing any remaining buffered data to- // it. If the readable side of the socket is in flowing mode then there is no- // buffered data as everything has been already written and `readable.read()`- // will return `null`. If instead, the socket is paused, any possible buffered- // data will be read as a single chunk and emitted synchronously in a single- // `'data'` event.- //- websocket._socket.read();- websocket._receiver.end();-- this.removeListener('data', socketOnData);- this[kWebSocket] = undefined;-- clearTimeout(websocket._closeTimer);-- if (- websocket._receiver._writableState.finished ||- websocket._receiver._writableState.errorEmitted- ) {- websocket.emitClose();- } else {- websocket._receiver.on('error', receiverOnFinish);- websocket._receiver.on('finish', receiverOnFinish);- }-}--/**- * The listener of the `net.Socket` `'data'` event.- *- * @param {Buffer} chunk A chunk of data- * @private- */-function socketOnData (chunk) {- if (!this[kWebSocket]._receiver.write(chunk)) {- this.pause();- }-}--/**- * The listener of the `net.Socket` `'end'` event.- *- * @private- */-function socketOnEnd () {- const websocket = this[kWebSocket];-- websocket.readyState = WebSocket.CLOSING;- websocket._receiver.end();- this.end();-}--/**- * The listener of the `net.Socket` `'error'` event.- *- * @private- */-function socketOnError () {- const websocket = this[kWebSocket];-- this.removeListener('error', socketOnError);- this.on('error', constants$3.NOOP);-- if (websocket) {- websocket.readyState = WebSocket.CLOSING;- this.destroy();- }-}--/**- * Class representing a WebSocket server.- *- * @extends EventEmitter- */-class WebSocketServer extends EventEmitter {- /**- * Create a `WebSocketServer` instance.- *- * @param {Object} options Configuration options- * @param {String} options.host The hostname where to bind the server- * @param {Number} options.port The port where to bind the server- * @param {http.Server} options.server A pre-created HTTP/S server to use- * @param {Function} options.verifyClient An hook to reject connections- * @param {Function} options.handleProtocols An hook to handle protocols- * @param {String} options.path Accept only connections matching this path- * @param {Boolean} options.noServer Enable no server mode- * @param {Boolean} options.clientTracking Specifies whether or not to track clients- * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate- * @param {Number} options.maxPayload The maximum allowed message size- * @param {Function} callback A listener for the `listening` event- */- constructor (options, callback) {- super();-- options = Object.assign({- maxPayload: 100 * 1024 * 1024,- perMessageDeflate: false,- handleProtocols: null,- clientTracking: true,- verifyClient: null,- noServer: false,- backlog: null, // use default (511 as implemented in net.js)- server: null,- host: null,- path: null,- port: null- }, options);-- if (options.port == null && !options.server && !options.noServer) {- throw new TypeError(- 'One of the "port", "server", or "noServer" options must be specified'- );- }-- if (options.port != null) {- this._server = http.createServer((req, res) => {- const body = http.STATUS_CODES[426];-- res.writeHead(426, {- 'Content-Length': body.length,- 'Content-Type': 'text/plain'- });- res.end(body);- });- this._server.listen(options.port, options.host, options.backlog, callback);- } else if (options.server) {- this._server = options.server;- }-- if (this._server) {- this._removeListeners = addListeners(this._server, {- listening: this.emit.bind(this, 'listening'),- error: this.emit.bind(this, 'error'),- upgrade: (req, socket, head) => {- this.handleUpgrade(req, socket, head, (ws) => {- this.emit('connection', ws, req);- });- }- });- }-- if (options.perMessageDeflate === true) options.perMessageDeflate = {};- if (options.clientTracking) this.clients = new Set();- this.options = options;- }-- /**- * Returns the bound address, the address family name, and port of the server- * as reported by the operating system if listening on an IP socket.- * If the server is listening on a pipe or UNIX domain socket, the name is- * returned as a string.- *- * @return {(Object|String|null)} The address of the server- * @public- */- address () {- if (this.options.noServer) {- throw new Error('The server is operating in "noServer" mode');- }-- if (!this._server) return null;- return this._server.address();- }-- /**- * Close the server.- *- * @param {Function} cb Callback- * @public- */- close (cb) {- //- // Terminate all associated clients.- //- if (this.clients) {- for (const client of this.clients) client.terminate();- }-- const server = this._server;-- if (server) {- this._removeListeners();- this._removeListeners = this._server = null;-- //- // Close the http server if it was internally created.- //- if (this.options.port != null) return server.close(cb);- }-- if (cb) cb();- }-- /**- * See if a given request should be handled by this server instance.- *- * @param {http.IncomingMessage} req Request object to inspect- * @return {Boolean} `true` if the request is valid, else `false`- * @public- */- shouldHandle (req) {- if (this.options.path && Url.parse(req.url).pathname !== this.options.path) {- return false;- }-- return true;- }-- /**- * Handle a HTTP Upgrade request.- *- * @param {http.IncomingMessage} req The request object- * @param {net.Socket} socket The network socket between the server and client- * @param {Buffer} head The first packet of the upgraded stream- * @param {Function} cb Callback- * @public- */- handleUpgrade (req, socket, head, cb) {- socket.on('error', socketOnError$1);-- const version = +req.headers['sec-websocket-version'];- const extensions = {};-- if (- req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' ||- !req.headers['sec-websocket-key'] || (version !== 8 && version !== 13) ||- !this.shouldHandle(req)- ) {- return abortHandshake$1(socket, 400);- }-- if (this.options.perMessageDeflate) {- const perMessageDeflate = new permessageDeflate(- this.options.perMessageDeflate,- true,- this.options.maxPayload- );-- try {- const offers = extension.parse(- req.headers['sec-websocket-extensions']- );-- if (offers[permessageDeflate.extensionName]) {- perMessageDeflate.accept(offers[permessageDeflate.extensionName]);- extensions[permessageDeflate.extensionName] = perMessageDeflate;- }- } catch (err) {- return abortHandshake$1(socket, 400);- }- }-- //- // Optionally call external client verification handler.- //- if (this.options.verifyClient) {- const info = {- origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],- secure: !!(req.connection.authorized || req.connection.encrypted),- req- };-- if (this.options.verifyClient.length === 2) {- this.options.verifyClient(info, (verified, code, message, headers) => {- if (!verified) {- return abortHandshake$1(socket, code || 401, message, headers);- }-- this.completeUpgrade(extensions, req, socket, head, cb);- });- return;- }-- if (!this.options.verifyClient(info)) return abortHandshake$1(socket, 401);- }-- this.completeUpgrade(extensions, req, socket, head, cb);- }-- /**- * Upgrade the connection to WebSocket.- *- * @param {Object} extensions The accepted extensions- * @param {http.IncomingMessage} req The request object- * @param {net.Socket} socket The network socket between the server and client- * @param {Buffer} head The first packet of the upgraded stream- * @param {Function} cb Callback- * @private- */- completeUpgrade (extensions, req, socket, head, cb) {- //- // Destroy the socket if the client has already sent a FIN packet.- //- if (!socket.readable || !socket.writable) return socket.destroy();-- const key = crypto.createHash('sha1')- .update(req.headers['sec-websocket-key'] + constants$3.GUID, 'binary')- .digest('base64');-- const headers = [- 'HTTP/1.1 101 Switching Protocols',- 'Upgrade: websocket',- 'Connection: Upgrade',- `Sec-WebSocket-Accept: ${key}`- ];-- const ws = new websocket(null);- var protocol = req.headers['sec-websocket-protocol'];-- if (protocol) {- protocol = protocol.trim().split(/ *, */);-- //- // Optionally call external protocol selection handler.- //- if (this.options.handleProtocols) {- protocol = this.options.handleProtocols(protocol, req);- } else {- protocol = protocol[0];- }-- if (protocol) {- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);- ws.protocol = protocol;- }- }-- if (extensions[permessageDeflate.extensionName]) {- const params = extensions[permessageDeflate.extensionName].params;- const value = extension.format({- [permessageDeflate.extensionName]: [params]- });- headers.push(`Sec-WebSocket-Extensions: ${value}`);- ws._extensions = extensions;- }-- //- // Allow external modification/inspection of handshake headers.- //- this.emit('headers', headers, req);-- socket.write(headers.concat('\r\n').join('\r\n'));- socket.removeListener('error', socketOnError$1);-- ws.setSocket(socket, head, this.options.maxPayload);-- if (this.clients) {- this.clients.add(ws);- ws.on('close', () => this.clients.delete(ws));- }-- cb(ws);- }-}--var websocketServer = WebSocketServer;--/**- * Add event listeners on an `EventEmitter` using a map of <event, listener>- * pairs.- *- * @param {EventEmitter} server The event emitter- * @param {Object.<String, Function>} map The listeners to add- * @return {Function} A function that will remove the added listeners when called- * @private- */-function addListeners (server, map) {- for (const event of Object.keys(map)) server.on(event, map[event]);-- return function removeListeners () {- for (const event of Object.keys(map)) {- server.removeListener(event, map[event]);- }- };-}--/**- * Handle premature socket errors.- *- * @private- */-function socketOnError$1 () {- this.destroy();-}--/**- * Close the connection when preconditions are not fulfilled.- *- * @param {net.Socket} socket The socket of the upgrade request- * @param {Number} code The HTTP response status code- * @param {String} [message] The HTTP response body- * @param {Object} [headers] Additional HTTP response headers- * @private- */-function abortHandshake$1 (socket, code, message, headers) {- if (socket.writable) {- message = message || http.STATUS_CODES[code];- headers = Object.assign({- 'Connection': 'close',- 'Content-type': 'text/html',- 'Content-Length': Buffer.byteLength(message)- }, headers);-- socket.write(- `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +- Object.keys(headers).map(h => `${h}: ${headers[h]}`).join('\r\n') +- '\r\n\r\n' +- message- );- }-- socket.removeListener('error', socketOnError$1);- socket.destroy();-}--websocket.Server = websocketServer;-websocket.Receiver = receiver;-websocket.Sender = sender;--var ws = websocket;--/**- * Copyright (c) 2016, Lee Byron- * All rights reserved.- *- * This source code is licensed under the MIT license found in the- * LICENSE file in the root directory of this source tree.- *- * @flow- * @ignore- */--/**- * [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator)- * is a *protocol* which describes a standard way to produce a sequence of- * values, typically the values of the Iterable represented by this Iterator.- *- * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface)- * it can be utilized by any version of JavaScript.- *- * @external Iterator- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator|MDN Iteration protocols}- */--/**- * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)- * is a *protocol* which when implemented allows a JavaScript object to define- * their iteration behavior, such as what values are looped over in a- * [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)- * loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables)- * implement the Iterable protocol, including `Array` and `Map`.- *- * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface)- * it can be utilized by any version of JavaScript.- *- * @external Iterable- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable|MDN Iteration protocols}- */--// In ES2015 environments, Symbol exists-var SYMBOL /*: any */ = typeof Symbol === 'function' ? Symbol : void 0;--// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator-var SYMBOL_ITERATOR$1 = SYMBOL && SYMBOL.iterator;--/**- * A property name to be used as the name of an Iterable's method responsible- * for producing an Iterator, referred to as `@@iterator`. Typically represents- * the value `Symbol.iterator` but falls back to the string `"@@iterator"` when- * `Symbol.iterator` is not defined.- *- * Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`,- * but do not use it for accessing existing Iterables, instead use- * {@link getIterator} or {@link isIterable}.- *- * @example- *- * var $$iterator = require('iterall').$$iterator- *- * function Counter (to) {- * this.to = to- * }- *- * Counter.prototype[$$iterator] = function () {- * return {- * to: this.to,- * num: 0,- * next () {- * if (this.num >= this.to) {- * return { value: undefined, done: true }- * }- * return { value: this.num++, done: false }- * }- * }- * }- *- * var counter = new Counter(3)- * for (var number of counter) {- * console.log(number) // 0 ... 1 ... 2- * }- *- * @type {Symbol|string}- */-/*:: declare export var $$iterator: '@@iterator'; */-var $$iterator = SYMBOL_ITERATOR$1 || '@@iterator';--/**- * Returns true if the provided object implements the Iterator protocol via- * either implementing a `Symbol.iterator` or `"@@iterator"` method.- *- * @example- *- * var isIterable = require('iterall').isIterable- * isIterable([ 1, 2, 3 ]) // true- * isIterable('ABC') // true- * isIterable({ length: 1, 0: 'Alpha' }) // false- * isIterable({ key: 'value' }) // false- * isIterable(new Map()) // true- *- * @param obj- * A value which might implement the Iterable protocol.- * @return {boolean} true if Iterable.- */-/*:: declare export function isIterable(obj: any): boolean; */-function isIterable(obj) {- return !!getIteratorMethod(obj)-}--/**- * Returns true if the provided object implements the Array-like protocol via- * defining a positive-integer `length` property.- *- * @example- *- * var isArrayLike = require('iterall').isArrayLike- * isArrayLike([ 1, 2, 3 ]) // true- * isArrayLike('ABC') // true- * isArrayLike({ length: 1, 0: 'Alpha' }) // true- * isArrayLike({ key: 'value' }) // false- * isArrayLike(new Map()) // false- *- * @param obj- * A value which might implement the Array-like protocol.- * @return {boolean} true if Array-like.- */-/*:: declare export function isArrayLike(obj: any): boolean; */-function isArrayLike(obj) {- var length = obj != null && obj.length;- return typeof length === 'number' && length >= 0 && length % 1 === 0-}--/**- * Returns true if the provided object is an Object (i.e. not a string literal)- * and is either Iterable or Array-like.- *- * This may be used in place of [Array.isArray()][isArray] to determine if an- * object should be iterated-over. It always excludes string literals and- * includes Arrays (regardless of if it is Iterable). It also includes other- * Array-like objects such as NodeList, TypedArray, and Buffer.- *- * @example- *- * var isCollection = require('iterall').isCollection- * isCollection([ 1, 2, 3 ]) // true- * isCollection('ABC') // false- * isCollection({ length: 1, 0: 'Alpha' }) // true- * isCollection({ key: 'value' }) // false- * isCollection(new Map()) // true- *- * @example- *- * var forEach = require('iterall').forEach- * if (isCollection(obj)) {- * forEach(obj, function (value) {- * console.log(value)- * })- * }- *- * @param obj- * An Object value which might implement the Iterable or Array-like protocols.- * @return {boolean} true if Iterable or Array-like Object.- */-/*:: declare export function isCollection(obj: any): boolean; */-function isCollection$1(obj) {- return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj))-}--/**- * If the provided object implements the Iterator protocol, its Iterator object- * is returned. Otherwise returns undefined.- *- * @example- *- * var getIterator = require('iterall').getIterator- * var iterator = getIterator([ 1, 2, 3 ])- * iterator.next() // { value: 1, done: false }- * iterator.next() // { value: 2, done: false }- * iterator.next() // { value: 3, done: false }- * iterator.next() // { value: undefined, done: true }- *- * @template T the type of each iterated value- * @param {Iterable<T>} iterable- * An Iterable object which is the source of an Iterator.- * @return {Iterator<T>} new Iterator instance.- */-/*:: declare export var getIterator:- & (<+TValue>(iterable: Iterable<TValue>) => Iterator<TValue>)- & ((iterable: mixed) => void | Iterator<mixed>); */-function getIterator(iterable) {- var method = getIteratorMethod(iterable);- if (method) {- return method.call(iterable)- }-}--/**- * If the provided object implements the Iterator protocol, the method- * responsible for producing its Iterator object is returned.- *- * This is used in rare cases for performance tuning. This method must be called- * with obj as the contextual this-argument.- *- * @example- *- * var getIteratorMethod = require('iterall').getIteratorMethod- * var myArray = [ 1, 2, 3 ]- * var method = getIteratorMethod(myArray)- * if (method) {- * var iterator = method.call(myArray)- * }- *- * @template T the type of each iterated value- * @param {Iterable<T>} iterable- * An Iterable object which defines an `@@iterator` method.- * @return {function(): Iterator<T>} `@@iterator` method.- */-/*:: declare export var getIteratorMethod:- & (<+TValue>(iterable: Iterable<TValue>) => (() => Iterator<TValue>))- & ((iterable: mixed) => (void | (() => Iterator<mixed>))); */-function getIteratorMethod(iterable) {- if (iterable != null) {- var method =- (SYMBOL_ITERATOR$1 && iterable[SYMBOL_ITERATOR$1]) || iterable['@@iterator'];- if (typeof method === 'function') {- return method- }- }-}--/**- * Similar to {@link getIterator}, this method returns a new Iterator given an- * Iterable. However it will also create an Iterator for a non-Iterable- * Array-like collection, such as Array in a non-ES2015 environment.- *- * `createIterator` is complimentary to `forEach`, but allows a "pull"-based- * iteration as opposed to `forEach`'s "push"-based iteration.- *- * `createIterator` produces an Iterator for Array-likes with the same behavior- * as ArrayIteratorPrototype described in the ECMAScript specification, and- * does *not* skip over "holes".- *- * @example- *- * var createIterator = require('iterall').createIterator- *- * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' }- * var iterator = createIterator(myArraylike)- * iterator.next() // { value: 'Alpha', done: false }- * iterator.next() // { value: 'Bravo', done: false }- * iterator.next() // { value: 'Charlie', done: false }- * iterator.next() // { value: undefined, done: true }- *- * @template T the type of each iterated value- * @param {Iterable<T>|{ length: number }} collection- * An Iterable or Array-like object to produce an Iterator.- * @return {Iterator<T>} new Iterator instance.- */-/*:: declare export var createIterator:- & (<+TValue>(collection: Iterable<TValue>) => Iterator<TValue>)- & ((collection: {length: number}) => Iterator<mixed>)- & ((collection: mixed) => (void | Iterator<mixed>)); */-function createIterator(collection) {- if (collection != null) {- var iterator = getIterator(collection);- if (iterator) {- return iterator- }- if (isArrayLike(collection)) {- return new ArrayLikeIterator(collection)- }- }-}--// When the object provided to `createIterator` is not Iterable but is-// Array-like, this simple Iterator is created.-function ArrayLikeIterator(obj) {- this._o = obj;- this._i = 0;-}--// Note: all Iterators are themselves Iterable.-ArrayLikeIterator.prototype[$$iterator] = function() {- return this-};--// A simple state-machine determines the IteratorResult returned, yielding-// each value in the Array-like object in order of their indicies.-ArrayLikeIterator.prototype.next = function() {- if (this._o === void 0 || this._i >= this._o.length) {- this._o = void 0;- return { value: void 0, done: true }- }- return { value: this._o[this._i++], done: false }-};--/**- * Given an object which either implements the Iterable protocol or is- * Array-like, iterate over it, calling the `callback` at each iteration.- *- * Use `forEach` where you would expect to use a `for ... of` loop in ES6.- * However `forEach` adheres to the behavior of [Array#forEach][] described in- * the ECMAScript specification, skipping over "holes" in Array-likes. It will- * also delegate to a `forEach` method on `collection` if one is defined,- * ensuring native performance for `Arrays`.- *- * Similar to [Array#forEach][], the `callback` function accepts three- * arguments, and is provided with `thisArg` as the calling context.- *- * Note: providing an infinite Iterator to forEach will produce an error.- *- * [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach- *- * @example- *- * var forEach = require('iterall').forEach- *- * forEach(myIterable, function (value, index, iterable) {- * console.log(value, index, iterable === myIterable)- * })- *- * @example- *- * // ES6:- * for (let value of myIterable) {- * console.log(value)- * }- *- * // Any JavaScript environment:- * forEach(myIterable, function (value) {- * console.log(value)- * })- *- * @template T the type of each iterated value- * @param {Iterable<T>|{ length: number }} collection- * The Iterable or array to iterate over.- * @param {function(T, number, object)} callback- * Function to execute for each iteration, taking up to three arguments- * @param [thisArg]- * Optional. Value to use as `this` when executing `callback`.- */-/*:: declare export var forEach:- & (<+TValue, TCollection: Iterable<TValue>>(- collection: TCollection,- callbackFn: (value: TValue, index: number, collection: TCollection) => any,- thisArg?: any- ) => void)- & (<TCollection: {length: number}>(- collection: TCollection,- callbackFn: (value: mixed, index: number, collection: TCollection) => any,- thisArg?: any- ) => void); */-function forEach(collection, callback, thisArg) {- if (collection != null) {- if (typeof collection.forEach === 'function') {- return collection.forEach(callback, thisArg)- }- var i = 0;- var iterator = getIterator(collection);- if (iterator) {- var step;- while (!(step = iterator.next()).done) {- callback.call(thisArg, step.value, i++, collection);- // Infinite Iterators could cause forEach to run forever.- // After a very large number of iterations, produce an error.- /* istanbul ignore if */- if (i > 9999999) {- throw new TypeError('Near-infinite iteration.')- }- }- } else if (isArrayLike(collection)) {- for (; i < collection.length; i++) {- if (collection.hasOwnProperty(i)) {- callback.call(thisArg, collection[i], i, collection);- }- }- }- }-}--/////////////////////////////////////////////////////-// //-// ASYNC ITERATORS //-// //-/////////////////////////////////////////////////////--/**- * [AsyncIterable](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface)- * is a *protocol* which when implemented allows a JavaScript object to define- * an asynchronous iteration behavior, such as what values are looped over in- * a [`for-await-of`](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements)- * loop or `iterall`'s {@link forAwaitEach} function.- *- * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/)- * it can be utilized by any version of JavaScript.- *- * @external AsyncIterable- * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface|Async Iteration Proposal}- * @template T The type of each iterated value- * @property {function (): AsyncIterator<T>} Symbol.asyncIterator- * A method which produces an AsyncIterator for this AsyncIterable.- */--/**- * [AsyncIterator](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface)- * is a *protocol* which describes a standard way to produce and consume an- * asynchronous sequence of values, typically the values of the- * {@link AsyncIterable} represented by this {@link AsyncIterator}.- *- * AsyncIterator is similar to Observable or Stream. Like an {@link Iterator} it- * also as a `next()` method, however instead of an IteratorResult,- * calling this method returns a {@link Promise} for a IteratorResult.- *- * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/)- * it can be utilized by any version of JavaScript.- *- * @external AsyncIterator- * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface|Async Iteration Proposal}- */--// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator-var SYMBOL_ASYNC_ITERATOR$1 = SYMBOL && SYMBOL.asyncIterator;--/**- * A property name to be used as the name of an AsyncIterable's method- * responsible for producing an Iterator, referred to as `@@asyncIterator`.- * Typically represents the value `Symbol.asyncIterator` but falls back to the- * string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined.- *- * Use `$$asyncIterator` for defining new AsyncIterables instead of- * `Symbol.asyncIterator`, but do not use it for accessing existing Iterables,- * instead use {@link getAsyncIterator} or {@link isAsyncIterable}.- *- * @example- *- * var $$asyncIterator = require('iterall').$$asyncIterator- *- * function Chirper (to) {- * this.to = to- * }- *- * Chirper.prototype[$$asyncIterator] = function () {- * return {- * to: this.to,- * num: 0,- * next () {- * return new Promise(resolve => {- * if (this.num >= this.to) {- * resolve({ value: undefined, done: true })- * } else {- * setTimeout(() => {- * resolve({ value: this.num++, done: false })- * }, 1000)- * }- * })- * }- * }- * }- *- * var chirper = new Chirper(3)- * for await (var number of chirper) {- * console.log(number) // 0 ...wait... 1 ...wait... 2- * }- *- * @type {Symbol|string}- */-/*:: declare export var $$asyncIterator: '@@asyncIterator'; */-var $$asyncIterator = SYMBOL_ASYNC_ITERATOR$1 || '@@asyncIterator';--/**- * Returns true if the provided object implements the AsyncIterator protocol via- * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method.- *- * @example- *- * var isAsyncIterable = require('iterall').isAsyncIterable- * isAsyncIterable(myStream) // true- * isAsyncIterable('ABC') // false- *- * @param obj- * A value which might implement the AsyncIterable protocol.- * @return {boolean} true if AsyncIterable.- */-/*:: declare export function isAsyncIterable(obj: any): boolean; */-function isAsyncIterable$1(obj) {- return !!getAsyncIteratorMethod(obj)-}--/**- * If the provided object implements the AsyncIterator protocol, its- * AsyncIterator object is returned. Otherwise returns undefined.- *- * @example- *- * var getAsyncIterator = require('iterall').getAsyncIterator- * var asyncIterator = getAsyncIterator(myStream)- * asyncIterator.next().then(console.log) // { value: 1, done: false }- * asyncIterator.next().then(console.log) // { value: 2, done: false }- * asyncIterator.next().then(console.log) // { value: 3, done: false }- * asyncIterator.next().then(console.log) // { value: undefined, done: true }- *- * @template T the type of each iterated value- * @param {AsyncIterable<T>} asyncIterable- * An AsyncIterable object which is the source of an AsyncIterator.- * @return {AsyncIterator<T>} new AsyncIterator instance.- */-/*:: declare export var getAsyncIterator:- & (<+TValue>(asyncIterable: AsyncIterable<TValue>) => AsyncIterator<TValue>)- & ((asyncIterable: mixed) => (void | AsyncIterator<mixed>)); */-function getAsyncIterator(asyncIterable) {- var method = getAsyncIteratorMethod(asyncIterable);- if (method) {- return method.call(asyncIterable)- }-}--/**- * If the provided object implements the AsyncIterator protocol, the method- * responsible for producing its AsyncIterator object is returned.- *- * This is used in rare cases for performance tuning. This method must be called- * with obj as the contextual this-argument.- *- * @example- *- * var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod- * var method = getAsyncIteratorMethod(myStream)- * if (method) {- * var asyncIterator = method.call(myStream)- * }- *- * @template T the type of each iterated value- * @param {AsyncIterable<T>} asyncIterable- * An AsyncIterable object which defines an `@@asyncIterator` method.- * @return {function(): AsyncIterator<T>} `@@asyncIterator` method.- */-/*:: declare export var getAsyncIteratorMethod:- & (<+TValue>(asyncIterable: AsyncIterable<TValue>) => (() => AsyncIterator<TValue>))- & ((asyncIterable: mixed) => (void | (() => AsyncIterator<mixed>))); */-function getAsyncIteratorMethod(asyncIterable) {- if (asyncIterable != null) {- var method =- (SYMBOL_ASYNC_ITERATOR$1 && asyncIterable[SYMBOL_ASYNC_ITERATOR$1]) ||- asyncIterable['@@asyncIterator'];- if (typeof method === 'function') {- return method- }- }-}--/**- * Similar to {@link getAsyncIterator}, this method returns a new AsyncIterator- * given an AsyncIterable. However it will also create an AsyncIterator for a- * non-async Iterable as well as non-Iterable Array-like collection, such as- * Array in a pre-ES2015 environment.- *- * `createAsyncIterator` is complimentary to `forAwaitEach`, but allows a- * buffering "pull"-based iteration as opposed to `forAwaitEach`'s- * "push"-based iteration.- *- * `createAsyncIterator` produces an AsyncIterator for non-async Iterables as- * described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects).- *- * > Note: Creating `AsyncIterator`s requires the existence of `Promise`.- * > While `Promise` has been available in modern browsers for a number of- * > years, legacy browsers (like IE 11) may require a polyfill.- *- * @example- *- * var createAsyncIterator = require('iterall').createAsyncIterator- *- * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' }- * var iterator = createAsyncIterator(myArraylike)- * iterator.next().then(console.log) // { value: 'Alpha', done: false }- * iterator.next().then(console.log) // { value: 'Bravo', done: false }- * iterator.next().then(console.log) // { value: 'Charlie', done: false }- * iterator.next().then(console.log) // { value: undefined, done: true }- *- * @template T the type of each iterated value- * @param {AsyncIterable<T>|Iterable<T>|{ length: number }} source- * An AsyncIterable, Iterable, or Array-like object to produce an Iterator.- * @return {AsyncIterator<T>} new AsyncIterator instance.- */-/*:: declare export var createAsyncIterator:- & (<+TValue>(- collection: Iterable<Promise<TValue> | TValue> | AsyncIterable<TValue>- ) => AsyncIterator<TValue>)- & ((collection: {length: number}) => AsyncIterator<mixed>)- & ((collection: mixed) => (void | AsyncIterator<mixed>)); */-function createAsyncIterator(source) {- if (source != null) {- var asyncIterator = getAsyncIterator(source);- if (asyncIterator) {- return asyncIterator- }- var iterator = createIterator(source);- if (iterator) {- return new AsyncFromSyncIterator(iterator)- }- }-}--// When the object provided to `createAsyncIterator` is not AsyncIterable but is-// sync Iterable, this simple wrapper is created.-function AsyncFromSyncIterator(iterator) {- this._i = iterator;-}--// Note: all AsyncIterators are themselves AsyncIterable.-AsyncFromSyncIterator.prototype[$$asyncIterator] = function() {- return this-};--// A simple state-machine determines the IteratorResult returned, yielding-// each value in the Array-like object in order of their indicies.-AsyncFromSyncIterator.prototype.next = function(value) {- return unwrapAsyncFromSync(this._i, 'next', value)-};--AsyncFromSyncIterator.prototype.return = function(value) {- return this._i.return- ? unwrapAsyncFromSync(this._i, 'return', value)- : Promise.resolve({ value: value, done: true })-};--AsyncFromSyncIterator.prototype.throw = function(value) {- return this._i.throw- ? unwrapAsyncFromSync(this._i, 'throw', value)- : Promise.reject(value)-};--function unwrapAsyncFromSync(iterator, fn, value) {- var step;- return new Promise(function(resolve) {- step = iterator[fn](value);- resolve(step.value);- }).then(function(value) {- return { value: value, done: step.done }- })-}--/**- * Given an object which either implements the AsyncIterable protocol or is- * Array-like, iterate over it, calling the `callback` at each iteration.- *- * Use `forAwaitEach` where you would expect to use a [for-await-of](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) loop.- *- * Similar to [Array#forEach][], the `callback` function accepts three- * arguments, and is provided with `thisArg` as the calling context.- *- * > Note: Using `forAwaitEach` requires the existence of `Promise`.- * > While `Promise` has been available in modern browsers for a number of- * > years, legacy browsers (like IE 11) may require a polyfill.- *- * @example- *- * var forAwaitEach = require('iterall').forAwaitEach- *- * forAwaitEach(myIterable, function (value, index, iterable) {- * console.log(value, index, iterable === myIterable)- * })- *- * @example- *- * // ES2017:- * for await (let value of myAsyncIterable) {- * console.log(await doSomethingAsync(value))- * }- * console.log('done')- *- * // Any JavaScript environment:- * forAwaitEach(myAsyncIterable, function (value) {- * return doSomethingAsync(value).then(console.log)- * }).then(function () {- * console.log('done')- * })- *- * @template T the type of each iterated value- * @param {AsyncIterable<T>|Iterable<Promise<T> | T>|{ length: number }} source- * The AsyncIterable or array to iterate over.- * @param {function(T, number, object)} callback- * Function to execute for each iteration, taking up to three arguments- * @param [thisArg]- * Optional. Value to use as `this` when executing `callback`.- */-/*:: declare export var forAwaitEach:- & (<+TValue, TCollection: Iterable<Promise<TValue> | TValue> | AsyncIterable<TValue>>(- collection: TCollection,- callbackFn: (value: TValue, index: number, collection: TCollection) => any,- thisArg?: any- ) => Promise<void>)- & (<TCollection: { length: number }>(- collection: TCollection,- callbackFn: (value: mixed, index: number, collection: TCollection) => any,- thisArg?: any- ) => Promise<void>); */-function forAwaitEach(source, callback, thisArg) {- var asyncIterator = createAsyncIterator(source);- if (asyncIterator) {- var i = 0;- return new Promise(function(resolve, reject) {- function next() {- asyncIterator- .next()- .then(function(step) {- if (!step.done) {- Promise.resolve(callback.call(thisArg, step.value, i++, source))- .then(next)- .catch(reject);- } else {- resolve();- }- // Explicitly return null, silencing bluebird-style warnings.- return null- })- .catch(reject);- // Explicitly return null, silencing bluebird-style warnings.- return null- }- next();- })- }-}--var iterall = /*#__PURE__*/Object.freeze({- __proto__: null,- $$iterator: $$iterator,- isIterable: isIterable,- isArrayLike: isArrayLike,- isCollection: isCollection$1,- getIterator: getIterator,- getIteratorMethod: getIteratorMethod,- createIterator: createIterator,- forEach: forEach,- $$asyncIterator: $$asyncIterator,- isAsyncIterable: isAsyncIterable$1,- getAsyncIterator: getAsyncIterator,- getAsyncIteratorMethod: getAsyncIteratorMethod,- createAsyncIterator: createAsyncIterator,- forAwaitEach: forAwaitEach-});--var emptyIterable = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true });-exports.createEmptyIterable = void 0;--exports.createEmptyIterable = function () {- var _a;- return _a = {- next: function () {- return Promise.resolve({ value: undefined, done: true });- },- return: function () {- return Promise.resolve({ value: undefined, done: true });- },- throw: function (e) {- return Promise.reject(e);- }- },- _a[iterall.$$asyncIterator] = function () {- return this;- },- _a;-};--});--var isSubscriptions = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true });-exports.isASubscriptionOperation = void 0;--exports.isASubscriptionOperation = function (document, operationName) {- var operationAST = graphql$1.getOperationAST(document, operationName);- return !!operationAST && operationAST.operation === 'subscription';-};--});--var parseLegacyProtocol = createCommonjsModule(function (module, exports) {-var __assign = (commonjsGlobal && commonjsGlobal.__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);-};-Object.defineProperty(exports, "__esModule", { value: true });-exports.parseLegacyProtocolMessage = void 0;--exports.parseLegacyProtocolMessage = function (connectionContext, message) {- var messageToReturn = message;- switch (message.type) {- case messageTypes.default.INIT:- connectionContext.isLegacy = true;- messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.GQL_CONNECTION_INIT });- break;- case messageTypes.default.SUBSCRIPTION_START:- messageToReturn = {- id: message.id,- type: messageTypes.default.GQL_START,- payload: {- query: message.query,- operationName: message.operationName,- variables: message.variables,- },- };- break;- case messageTypes.default.SUBSCRIPTION_END:- messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.GQL_STOP });- break;- case messageTypes.default.GQL_CONNECTION_ACK:- if (connectionContext.isLegacy) {- messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.INIT_SUCCESS });- }- break;- case messageTypes.default.GQL_CONNECTION_ERROR:- if (connectionContext.isLegacy) {- messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.INIT_FAIL, payload: message.payload.message ? { error: message.payload.message } : message.payload });- }- break;- case messageTypes.default.GQL_ERROR:- if (connectionContext.isLegacy) {- messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.SUBSCRIPTION_FAIL });- }- break;- case messageTypes.default.GQL_DATA:- if (connectionContext.isLegacy) {- messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.SUBSCRIPTION_DATA });- }- break;- case messageTypes.default.GQL_COMPLETE:- if (connectionContext.isLegacy) {- messageToReturn = null;- }- break;- case messageTypes.default.SUBSCRIPTION_SUCCESS:- if (!connectionContext.isLegacy) {- messageToReturn = null;- }- break;- }- return messageToReturn;-};--});--var server = createCommonjsModule(function (module, exports) {-Object.defineProperty(exports, "__esModule", { value: true });-exports.SubscriptionServer = void 0;----------var isWebSocketServer = function (socket) { return socket.on; };-var SubscriptionServer = (function () {- function SubscriptionServer(options, socketOptionsOrServer) {- var _this = this;- var onOperation = options.onOperation, onOperationComplete = options.onOperationComplete, onConnect = options.onConnect, onDisconnect = options.onDisconnect, keepAlive = options.keepAlive;- this.specifiedRules = options.validationRules || graphql$1.specifiedRules;- this.loadExecutor(options);- this.onOperation = onOperation;- this.onOperationComplete = onOperationComplete;- this.onConnect = onConnect;- this.onDisconnect = onDisconnect;- this.keepAlive = keepAlive;- if (isWebSocketServer(socketOptionsOrServer)) {- this.wsServer = socketOptionsOrServer;- }- else {- this.wsServer = new ws.Server(socketOptionsOrServer || {});- }- var connectionHandler = (function (socket, request) {- socket.upgradeReq = request;- if (socket.protocol === undefined ||- (socket.protocol.indexOf(protocol.GRAPHQL_WS) === -1 && socket.protocol.indexOf(protocol.GRAPHQL_SUBSCRIPTIONS) === -1)) {- socket.close(1002);- return;- }- var connectionContext = Object.create(null);- connectionContext.initPromise = Promise.resolve(true);- connectionContext.isLegacy = false;- connectionContext.socket = socket;- connectionContext.request = request;- connectionContext.operations = {};- var connectionClosedHandler = function (error) {- if (error) {- _this.sendError(connectionContext, '', { message: error.message ? error.message : error }, messageTypes.default.GQL_CONNECTION_ERROR);- setTimeout(function () {- connectionContext.socket.close(1011);- }, 10);- }- _this.onClose(connectionContext);- if (_this.onDisconnect) {- _this.onDisconnect(socket, connectionContext);- }- };- socket.on('error', connectionClosedHandler);- socket.on('close', connectionClosedHandler);- socket.on('message', _this.onMessage(connectionContext));- });- this.wsServer.on('connection', connectionHandler);- this.closeHandler = function () {- _this.wsServer.removeListener('connection', connectionHandler);- _this.wsServer.close();- };- }- SubscriptionServer.create = function (options, socketOptionsOrServer) {- return new SubscriptionServer(options, socketOptionsOrServer);- };- Object.defineProperty(SubscriptionServer.prototype, "server", {- get: function () {- return this.wsServer;- },- enumerable: false,- configurable: true- });- SubscriptionServer.prototype.close = function () {- this.closeHandler();- };- SubscriptionServer.prototype.loadExecutor = function (options) {- var execute = options.execute, subscribe = options.subscribe, schema = options.schema, rootValue = options.rootValue;- if (!execute) {- throw new Error('Must provide `execute` for websocket server constructor.');- }- this.schema = schema;- this.rootValue = rootValue;- this.execute = execute;- this.subscribe = subscribe;- };- SubscriptionServer.prototype.unsubscribe = function (connectionContext, opId) {- if (connectionContext.operations && connectionContext.operations[opId]) {- if (connectionContext.operations[opId].return) {- connectionContext.operations[opId].return();- }- delete connectionContext.operations[opId];- if (this.onOperationComplete) {- this.onOperationComplete(connectionContext.socket, opId);- }- }- };- SubscriptionServer.prototype.onClose = function (connectionContext) {- var _this = this;- Object.keys(connectionContext.operations).forEach(function (opId) {- _this.unsubscribe(connectionContext, opId);- });- };- SubscriptionServer.prototype.onMessage = function (connectionContext) {- var _this = this;- return function (message) {- var parsedMessage;- try {- parsedMessage = parseLegacyProtocol.parseLegacyProtocolMessage(connectionContext, JSON.parse(message));- }- catch (e) {- _this.sendError(connectionContext, null, { message: e.message }, messageTypes.default.GQL_CONNECTION_ERROR);- return;- }- var opId = parsedMessage.id;- switch (parsedMessage.type) {- case messageTypes.default.GQL_CONNECTION_INIT:- if (_this.onConnect) {- connectionContext.initPromise = new Promise(function (resolve, reject) {- try {- resolve(_this.onConnect(parsedMessage.payload, connectionContext.socket, connectionContext));- }- catch (e) {- reject(e);- }- });- }- connectionContext.initPromise.then(function (result) {- if (result === false) {- throw new Error('Prohibited connection!');- }- _this.sendMessage(connectionContext, undefined, messageTypes.default.GQL_CONNECTION_ACK, undefined);- if (_this.keepAlive) {- _this.sendKeepAlive(connectionContext);- var keepAliveTimer_1 = setInterval(function () {- if (connectionContext.socket.readyState === ws.OPEN) {- _this.sendKeepAlive(connectionContext);- }- else {- clearInterval(keepAliveTimer_1);- }- }, _this.keepAlive);- }- }).catch(function (error) {- _this.sendError(connectionContext, opId, { message: error.message }, messageTypes.default.GQL_CONNECTION_ERROR);- setTimeout(function () {- connectionContext.socket.close(1011);- }, 10);- });- break;- case messageTypes.default.GQL_CONNECTION_TERMINATE:- connectionContext.socket.close();- break;- case messageTypes.default.GQL_START:- connectionContext.initPromise.then(function (initResult) {- if (connectionContext.operations && connectionContext.operations[opId]) {- _this.unsubscribe(connectionContext, opId);- }- var baseParams = {- query: parsedMessage.payload.query,- variables: parsedMessage.payload.variables,- operationName: parsedMessage.payload.operationName,- context: isObject_1.default(initResult) ? Object.assign(Object.create(Object.getPrototypeOf(initResult)), initResult) : {},- formatResponse: undefined,- formatError: undefined,- callback: undefined,- schema: _this.schema,- };- var promisedParams = Promise.resolve(baseParams);- connectionContext.operations[opId] = emptyIterable.createEmptyIterable();- if (_this.onOperation) {- var messageForCallback = parsedMessage;- promisedParams = Promise.resolve(_this.onOperation(messageForCallback, baseParams, connectionContext.socket));- }- promisedParams.then(function (params) {- if (typeof params !== 'object') {- var error = "Invalid params returned from onOperation! return values must be an object!";- _this.sendError(connectionContext, opId, { message: error });- throw new Error(error);- }- if (!params.schema) {- var error = 'Missing schema information. The GraphQL schema should be provided either statically in' +- ' the `SubscriptionServer` constructor or as a property on the object returned from onOperation!';- _this.sendError(connectionContext, opId, { message: error });- throw new Error(error);- }- var document = typeof baseParams.query !== 'string' ? baseParams.query : graphql$1.parse(baseParams.query);- var executionPromise;- var validationErrors = graphql$1.validate(params.schema, document, _this.specifiedRules);- if (validationErrors.length > 0) {- executionPromise = Promise.resolve({ errors: validationErrors });- }- else {- var executor = _this.execute;- if (_this.subscribe && isSubscriptions.isASubscriptionOperation(document, params.operationName)) {- executor = _this.subscribe;- }- executionPromise = Promise.resolve(executor(params.schema, document, _this.rootValue, params.context, params.variables, params.operationName));- }- return executionPromise.then(function (executionResult) { return ({- executionIterable: iterall.isAsyncIterable(executionResult) ?- executionResult : iterall.createAsyncIterator([executionResult]),- params: params,- }); });- }).then(function (_a) {- var executionIterable = _a.executionIterable, params = _a.params;- iterall.forAwaitEach(executionIterable, function (value) {- var result = value;- if (params.formatResponse) {- try {- result = params.formatResponse(value, params);- }- catch (err) {- console.error('Error in formatError function:', err);- }- }- _this.sendMessage(connectionContext, opId, messageTypes.default.GQL_DATA, result);- })- .then(function () {- _this.sendMessage(connectionContext, opId, messageTypes.default.GQL_COMPLETE, null);- })- .catch(function (e) {- var error = e;- if (params.formatError) {- try {- error = params.formatError(e, params);- }- catch (err) {- console.error('Error in formatError function: ', err);- }- }- if (Object.keys(e).length === 0) {- error = { name: e.name, message: e.message };- }- _this.sendError(connectionContext, opId, error);- });- return executionIterable;- }).then(function (subscription) {- connectionContext.operations[opId] = subscription;- }).then(function () {- _this.sendMessage(connectionContext, opId, messageTypes.default.SUBSCRIPTION_SUCCESS, undefined);- }).catch(function (e) {- if (e.errors) {- _this.sendMessage(connectionContext, opId, messageTypes.default.GQL_DATA, { errors: e.errors });- }- else {- _this.sendError(connectionContext, opId, { message: e.message });- }- _this.unsubscribe(connectionContext, opId);- return;- });- return promisedParams;- }).catch(function (error) {- _this.sendError(connectionContext, opId, { message: error.message });- _this.unsubscribe(connectionContext, opId);- });- break;- case messageTypes.default.GQL_STOP:- _this.unsubscribe(connectionContext, opId);- break;- default:- _this.sendError(connectionContext, opId, { message: 'Invalid message type!' });- }- };- };- SubscriptionServer.prototype.sendKeepAlive = function (connectionContext) {- if (connectionContext.isLegacy) {- this.sendMessage(connectionContext, undefined, messageTypes.default.KEEP_ALIVE, undefined);- }- else {- this.sendMessage(connectionContext, undefined, messageTypes.default.GQL_CONNECTION_KEEP_ALIVE, undefined);- }- };- SubscriptionServer.prototype.sendMessage = function (connectionContext, opId, type, payload) {- var parsedMessage = parseLegacyProtocol.parseLegacyProtocolMessage(connectionContext, {- type: type,- id: opId,- payload: payload,- });- if (parsedMessage && connectionContext.socket.readyState === ws.OPEN) {- connectionContext.socket.send(JSON.stringify(parsedMessage));- }- };- SubscriptionServer.prototype.sendError = function (connectionContext, opId, errorPayload, overrideDefaultErrorType) {- var sanitizedOverrideDefaultErrorType = overrideDefaultErrorType || messageTypes.default.GQL_ERROR;- if ([- messageTypes.default.GQL_CONNECTION_ERROR,- messageTypes.default.GQL_ERROR,- ].indexOf(sanitizedOverrideDefaultErrorType) === -1) {- throw new Error('overrideDefaultErrorType should be one of the allowed error messages' +- ' GQL_CONNECTION_ERROR or GQL_ERROR');- }- this.sendMessage(connectionContext, opId, sanitizedOverrideDefaultErrorType, errorPayload);- };- return SubscriptionServer;-}());-exports.SubscriptionServer = SubscriptionServer;--});--var dist = createCommonjsModule(function (module, exports) {-var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {- if (k2 === undefined) k2 = k;- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });-}) : (function(o, m, k, k2) {- if (k2 === undefined) k2 = k;- o[k2] = m[k];-}));-var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {- for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);-};-Object.defineProperty(exports, "__esModule", { value: true });-__exportStar(client, exports);-__exportStar(server, exports);-__exportStar(messageTypes, exports);-__exportStar(protocol, exports);--});--/* eslint-disable no-case-declarations */-/**- * This loader loads a schema from a URL. The loaded schema is a fully-executable,- * remote schema since it's created using [@graphql-tools/wrap](/docs/remote-schemas).- *- * ```- * const schema = await loadSchema('http://localhost:3000/graphql', {- * loaders: [- * new UrlLoader(),- * ]- * });- * ```- */-class UrlLoader {- loaderId() {- return 'url';- }- async canLoad(pointer, options) {- return this.canLoadSync(pointer, options);- }- canLoadSync(pointer, _options) {- return !!validUrl.isWebUri(pointer);- }- buildAsyncExecutor({ pointer, fetch, extraHeaders, defaultMethod, useGETForQueries, }) {- const HTTP_URL = pointer.replace('ws:', 'http:').replace('wss:', 'https:');- return async ({ document, variables }) => {- let method = defaultMethod;- if (useGETForQueries) {- method = 'GET';- for (const definition of document.definitions) {- if (definition.kind === Kind.OPERATION_DEFINITION) {- if (definition.operation !== 'query') {- method = defaultMethod;- }- }- }- }- let fetchResult;- const query = print(document);- switch (method) {- case 'GET':- const urlObj = new URL(HTTP_URL);- urlObj.searchParams.set('query', query);- if (variables && Object.keys(variables).length > 0) {- urlObj.searchParams.set('variables', JSON.stringify(variables));- }- const finalUrl = urlObj.toString();- fetchResult = await fetch(finalUrl, {- method: 'GET',- headers: extraHeaders,- });- break;- case 'POST':- fetchResult = await fetch(HTTP_URL, {- method: 'POST',- body: JSON.stringify({- query,- variables,- }),- headers: extraHeaders,- });- break;- }- return fetchResult.json();- };- }- buildSubscriber(pointer, webSocketImpl) {- const WS_URL = pointer.replace('http:', 'ws:').replace('https:', 'wss:');- const subscriptionClient = new dist.SubscriptionClient(WS_URL, {}, webSocketImpl);- return async ({ document, variables }) => {- return observableToAsyncIterable(subscriptionClient.request({- query: document,- variables,- }));- };- }- async getExecutorAndSubscriber(pointer, options) {- let headers = {};- let fetch$1 = nodePonyfill.fetch;- let defaultMethod = 'POST';- let webSocketImpl = websocket$1.w3cwebsocket;- if (options) {- if (Array.isArray(options.headers)) {- headers = options.headers.reduce((prev, v) => ({ ...prev, ...v }), {});- }- else if (typeof options.headers === 'object') {- headers = options.headers;- }- if (options.customFetch) {- if (typeof options.customFetch === 'string') {- const [moduleName, fetchFnName] = options.customFetch.split('#');- fetch$1 = await Promise.resolve().then(function () { return _interopNamespace(require(moduleName)); }).then(module => (fetchFnName ? module[fetchFnName] : module));- }- else {- fetch$1 = options.customFetch;- }- }- if (options.webSocketImpl) {- if (typeof options.webSocketImpl === 'string') {- const [moduleName, webSocketImplName] = options.webSocketImpl.split('#');- webSocketImpl = await Promise.resolve().then(function () { return _interopNamespace(require(moduleName)); }).then(module => webSocketImplName ? module[webSocketImplName] : module);- }- else {- webSocketImpl = options.webSocketImpl;- }- }- if (options.method) {- defaultMethod = options.method;- }- }- const extraHeaders = {- Accept: 'application/json',- 'Content-Type': 'application/json',- ...headers,- };- const executor = this.buildAsyncExecutor({- pointer,- fetch: fetch$1,- extraHeaders,- defaultMethod,- useGETForQueries: options.useGETForQueries,- });- let subscriber;- if (options.enableSubscriptions) {- subscriber = this.buildSubscriber(pointer, webSocketImpl);- }- return {- executor,- subscriber,- };- }- async getSubschemaConfig(pointer, options) {- const { executor, subscriber } = await this.getExecutorAndSubscriber(pointer, options);- return {- schema: await introspectSchema(executor, undefined, options),- executor,- subscriber,- };- }- async load(pointer, options) {- const subschemaConfig = await this.getSubschemaConfig(pointer, options);- const remoteExecutableSchema = wrapSchema(subschemaConfig);- return {- location: pointer,- schema: remoteExecutableSchema,- };- }- loadSync() {- throw new Error('Loader Url has no sync mode');- }-}--function isNothing(subject) {- return (typeof subject === 'undefined') || (subject === null);-}---function isObject$3(subject) {- return (typeof subject === 'object') && (subject !== null);-}---function toArray(sequence) {- if (Array.isArray(sequence)) return sequence;- else if (isNothing(sequence)) return [];-- return [ sequence ];-}---function extend(target, source) {- var index, length, key, sourceKeys;-- if (source) {- sourceKeys = Object.keys(source);-- for (index = 0, length = sourceKeys.length; index < length; index += 1) {- key = sourceKeys[index];- target[key] = source[key];- }- }-- return target;-}---function repeat(string, count) {- var result = '', cycle;-- for (cycle = 0; cycle < count; cycle += 1) {- result += string;- }-- return result;-}---function isNegativeZero(number) {- return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);-}---var isNothing_1 = isNothing;-var isObject_1$1 = isObject$3;-var toArray_1 = toArray;-var repeat_1 = repeat;-var isNegativeZero_1 = isNegativeZero;-var extend_1 = extend;--var common$1 = {- isNothing: isNothing_1,- isObject: isObject_1$1,- toArray: toArray_1,- repeat: repeat_1,- isNegativeZero: isNegativeZero_1,- extend: extend_1-};--// YAML error class. http://stackoverflow.com/questions/8458984--function YAMLException(reason, mark) {- // Super constructor- Error.call(this);-- this.name = 'YAMLException';- this.reason = reason;- this.mark = mark;- this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');-- // Include stack trace in error object- if (Error.captureStackTrace) {- // Chrome and NodeJS- Error.captureStackTrace(this, this.constructor);- } else {- // FF, IE 10+ and Safari 6+. Fallback for others- this.stack = (new Error()).stack || '';- }-}---// Inherit from Error-YAMLException.prototype = Object.create(Error.prototype);-YAMLException.prototype.constructor = YAMLException;---YAMLException.prototype.toString = function toString(compact) {- var result = this.name + ': ';-- result += this.reason || '(unknown reason)';-- if (!compact && this.mark) {- result += ' ' + this.mark.toString();- }-- return result;-};---var exception = YAMLException;--function Mark(name, buffer, position, line, column) {- this.name = name;- this.buffer = buffer;- this.position = position;- this.line = line;- this.column = column;-}---Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {- var head, start, tail, end, snippet;-- if (!this.buffer) return null;-- indent = indent || 4;- maxLength = maxLength || 75;-- head = '';- start = this.position;-- while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {- start -= 1;- if (this.position - start > (maxLength / 2 - 1)) {- head = ' ... ';- start += 5;- break;- }- }-- tail = '';- end = this.position;-- while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {- end += 1;- if (end - this.position > (maxLength / 2 - 1)) {- tail = ' ... ';- end -= 5;- break;- }- }-- snippet = this.buffer.slice(start, end);-- return common$1.repeat(' ', indent) + head + snippet + tail + '\n' +- common$1.repeat(' ', indent + this.position - start + head.length) + '^';-};---Mark.prototype.toString = function toString(compact) {- var snippet, where = '';-- if (this.name) {- where += 'in "' + this.name + '" ';- }-- where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);-- if (!compact) {- snippet = this.getSnippet();-- if (snippet) {- where += ':\n' + snippet;- }- }-- return where;-};---var mark = Mark;--var TYPE_CONSTRUCTOR_OPTIONS = [- 'kind',- 'resolve',- 'construct',- 'instanceOf',- 'predicate',- 'represent',- 'defaultStyle',- 'styleAliases'-];--var YAML_NODE_KINDS = [- 'scalar',- 'sequence',- 'mapping'-];--function compileStyleAliases(map) {- var result = {};-- if (map !== null) {- Object.keys(map).forEach(function (style) {- map[style].forEach(function (alias) {- result[String(alias)] = style;- });- });- }-- return result;-}--function Type(tag, options) {- options = options || {};-- Object.keys(options).forEach(function (name) {- if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {- throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');- }- });-- // TODO: Add tag format check.- this.tag = tag;- this.kind = options['kind'] || null;- this.resolve = options['resolve'] || function () { return true; };- this.construct = options['construct'] || function (data) { return data; };- this.instanceOf = options['instanceOf'] || null;- this.predicate = options['predicate'] || null;- this.represent = options['represent'] || null;- this.defaultStyle = options['defaultStyle'] || null;- this.styleAliases = compileStyleAliases(options['styleAliases'] || null);-- if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {- throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');- }-}--var type = Type;--/*eslint-disable max-len*/-------function compileList(schema, name, result) {- var exclude = [];-- schema.include.forEach(function (includedSchema) {- result = compileList(includedSchema, name, result);- });-- schema[name].forEach(function (currentType) {- result.forEach(function (previousType, previousIndex) {- if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {- exclude.push(previousIndex);- }- });-- result.push(currentType);- });-- return result.filter(function (type, index) {- return exclude.indexOf(index) === -1;- });-}---function compileMap(/* lists... */) {- var result = {- scalar: {},- sequence: {},- mapping: {},- fallback: {}- }, index, length;-- function collectType(type) {- result[type.kind][type.tag] = result['fallback'][type.tag] = type;- }-- for (index = 0, length = arguments.length; index < length; index += 1) {- arguments[index].forEach(collectType);- }- return result;-}---function Schema(definition) {- this.include = definition.include || [];- this.implicit = definition.implicit || [];- this.explicit = definition.explicit || [];-- this.implicit.forEach(function (type) {- if (type.loadKind && type.loadKind !== 'scalar') {- throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');- }- });-- this.compiledImplicit = compileList(this, 'implicit', []);- this.compiledExplicit = compileList(this, 'explicit', []);- this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);-}---Schema.DEFAULT = null;---Schema.create = function createSchema() {- var schemas, types;-- switch (arguments.length) {- case 1:- schemas = Schema.DEFAULT;- types = arguments[0];- break;-- case 2:- schemas = arguments[0];- types = arguments[1];- break;-- default:- throw new exception('Wrong number of arguments for Schema.create function');- }-- schemas = common$1.toArray(schemas);- types = common$1.toArray(types);-- if (!schemas.every(function (schema) { return schema instanceof Schema; })) {- throw new exception('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');- }-- if (!types.every(function (type$1) { return type$1 instanceof type; })) {- throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');- }-- return new Schema({- include: schemas,- explicit: types- });-};---var schema = Schema;--var str = new type('tag:yaml.org,2002:str', {- kind: 'scalar',- construct: function (data) { return data !== null ? data : ''; }-});--var seq = new type('tag:yaml.org,2002:seq', {- kind: 'sequence',- construct: function (data) { return data !== null ? data : []; }-});--var map = new type('tag:yaml.org,2002:map', {- kind: 'mapping',- construct: function (data) { return data !== null ? data : {}; }-});--var failsafe = new schema({- explicit: [- str,- seq,- map- ]-});--function resolveYamlNull(data) {- if (data === null) return true;-- var max = data.length;-- return (max === 1 && data === '~') ||- (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));-}--function constructYamlNull() {- return null;-}--function isNull(object) {- return object === null;-}--var _null = new type('tag:yaml.org,2002:null', {- kind: 'scalar',- resolve: resolveYamlNull,- construct: constructYamlNull,- predicate: isNull,- represent: {- canonical: function () { return '~'; },- lowercase: function () { return 'null'; },- uppercase: function () { return 'NULL'; },- camelcase: function () { return 'Null'; }- },- defaultStyle: 'lowercase'-});--function resolveYamlBoolean(data) {- if (data === null) return false;-- var max = data.length;-- return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||- (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));-}--function constructYamlBoolean(data) {- return data === 'true' ||- data === 'True' ||- data === 'TRUE';-}--function isBoolean(object) {- return Object.prototype.toString.call(object) === '[object Boolean]';-}--var bool = new type('tag:yaml.org,2002:bool', {- kind: 'scalar',- resolve: resolveYamlBoolean,- construct: constructYamlBoolean,- predicate: isBoolean,- represent: {- lowercase: function (object) { return object ? 'true' : 'false'; },- uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },- camelcase: function (object) { return object ? 'True' : 'False'; }- },- defaultStyle: 'lowercase'-});--function isHexCode(c) {- return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||- ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||- ((0x61/* a */ <= c) && (c <= 0x66/* f */));-}--function isOctCode(c) {- return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));-}--function isDecCode(c) {- return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));-}--function resolveYamlInteger(data) {- if (data === null) return false;-- var max = data.length,- index = 0,- hasDigits = false,- ch;-- if (!max) return false;-- ch = data[index];-- // sign- if (ch === '-' || ch === '+') {- ch = data[++index];- }-- if (ch === '0') {- // 0- if (index + 1 === max) return true;- ch = data[++index];-- // base 2, base 8, base 16-- if (ch === 'b') {- // base 2- index++;-- for (; index < max; index++) {- ch = data[index];- if (ch === '_') continue;- if (ch !== '0' && ch !== '1') return false;- hasDigits = true;- }- return hasDigits && ch !== '_';- }--- if (ch === 'x') {- // base 16- index++;-- for (; index < max; index++) {- ch = data[index];- if (ch === '_') continue;- if (!isHexCode(data.charCodeAt(index))) return false;- hasDigits = true;- }- return hasDigits && ch !== '_';- }-- // base 8- for (; index < max; index++) {- ch = data[index];- if (ch === '_') continue;- if (!isOctCode(data.charCodeAt(index))) return false;- hasDigits = true;- }- return hasDigits && ch !== '_';- }-- // base 10 (except 0) or base 60-- // value should not start with `_`;- if (ch === '_') return false;-- for (; index < max; index++) {- ch = data[index];- if (ch === '_') continue;- if (ch === ':') break;- if (!isDecCode(data.charCodeAt(index))) {- return false;- }- hasDigits = true;- }-- // Should have digits and should not end with `_`- if (!hasDigits || ch === '_') return false;-- // if !base60 - done;- if (ch !== ':') return true;-- // base60 almost not used, no needs to optimize- return /^(:[0-5]?[0-9])+$/.test(data.slice(index));-}--function constructYamlInteger(data) {- var value = data, sign = 1, ch, base, digits = [];-- if (value.indexOf('_') !== -1) {- value = value.replace(/_/g, '');- }-- ch = value[0];-- if (ch === '-' || ch === '+') {- if (ch === '-') sign = -1;- value = value.slice(1);- ch = value[0];- }-- if (value === '0') return 0;-- if (ch === '0') {- if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);- if (value[1] === 'x') return sign * parseInt(value, 16);- return sign * parseInt(value, 8);- }-- if (value.indexOf(':') !== -1) {- value.split(':').forEach(function (v) {- digits.unshift(parseInt(v, 10));- });-- value = 0;- base = 1;-- digits.forEach(function (d) {- value += (d * base);- base *= 60;- });-- return sign * value;-- }-- return sign * parseInt(value, 10);-}--function isInteger$1(object) {- return (Object.prototype.toString.call(object)) === '[object Number]' &&- (object % 1 === 0 && !common$1.isNegativeZero(object));-}--var int_1 = new type('tag:yaml.org,2002:int', {- kind: 'scalar',- resolve: resolveYamlInteger,- construct: constructYamlInteger,- predicate: isInteger$1,- represent: {- binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },- octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },- decimal: function (obj) { return obj.toString(10); },- /* eslint-disable max-len */- hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }- },- defaultStyle: 'decimal',- styleAliases: {- binary: [ 2, 'bin' ],- octal: [ 8, 'oct' ],- decimal: [ 10, 'dec' ],- hexadecimal: [ 16, 'hex' ]- }-});--var YAML_FLOAT_PATTERN = new RegExp(- // 2.5e4, 2.5 and integers- '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +- // .2e4, .2- // special case, seems not from spec- '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +- // 20:59- '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +- // .inf- '|[-+]?\\.(?:inf|Inf|INF)' +- // .nan- '|\\.(?:nan|NaN|NAN))$');--function resolveYamlFloat(data) {- if (data === null) return false;-- if (!YAML_FLOAT_PATTERN.test(data) ||- // Quick hack to not allow integers end with `_`- // Probably should update regexp & check speed- data[data.length - 1] === '_') {- return false;- }-- return true;-}--function constructYamlFloat(data) {- var value, sign, base, digits;-- value = data.replace(/_/g, '').toLowerCase();- sign = value[0] === '-' ? -1 : 1;- digits = [];-- if ('+-'.indexOf(value[0]) >= 0) {- value = value.slice(1);- }-- if (value === '.inf') {- return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;-- } else if (value === '.nan') {- return NaN;-- } else if (value.indexOf(':') >= 0) {- value.split(':').forEach(function (v) {- digits.unshift(parseFloat(v, 10));- });-- value = 0.0;- base = 1;-- digits.forEach(function (d) {- value += d * base;- base *= 60;- });-- return sign * value;-- }- return sign * parseFloat(value, 10);-}---var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;--function representYamlFloat(object, style) {- var res;-- if (isNaN(object)) {- switch (style) {- case 'lowercase': return '.nan';- case 'uppercase': return '.NAN';- case 'camelcase': return '.NaN';- }- } else if (Number.POSITIVE_INFINITY === object) {- switch (style) {- case 'lowercase': return '.inf';- case 'uppercase': return '.INF';- case 'camelcase': return '.Inf';- }- } else if (Number.NEGATIVE_INFINITY === object) {- switch (style) {- case 'lowercase': return '-.inf';- case 'uppercase': return '-.INF';- case 'camelcase': return '-.Inf';- }- } else if (common$1.isNegativeZero(object)) {- return '-0.0';- }-- res = object.toString(10);-- // JS stringifier can build scientific format without dots: 5e-100,- // while YAML requres dot: 5.e-100. Fix it with simple hack-- return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;-}--function isFloat(object) {- return (Object.prototype.toString.call(object) === '[object Number]') &&- (object % 1 !== 0 || common$1.isNegativeZero(object));-}--var float_1 = new type('tag:yaml.org,2002:float', {- kind: 'scalar',- resolve: resolveYamlFloat,- construct: constructYamlFloat,- predicate: isFloat,- represent: representYamlFloat,- defaultStyle: 'lowercase'-});--var json$1 = new schema({- include: [- failsafe- ],- implicit: [- _null,- bool,- int_1,- float_1- ]-});--var core = new schema({- include: [- json$1- ]-});--var YAML_DATE_REGEXP = new RegExp(- '^([0-9][0-9][0-9][0-9])' + // [1] year- '-([0-9][0-9])' + // [2] month- '-([0-9][0-9])$'); // [3] day--var YAML_TIMESTAMP_REGEXP = new RegExp(- '^([0-9][0-9][0-9][0-9])' + // [1] year- '-([0-9][0-9]?)' + // [2] month- '-([0-9][0-9]?)' + // [3] day- '(?:[Tt]|[ \\t]+)' + // ...- '([0-9][0-9]?)' + // [4] hour- ':([0-9][0-9])' + // [5] minute- ':([0-9][0-9])' + // [6] second- '(?:\\.([0-9]*))?' + // [7] fraction- '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour- '(?::([0-9][0-9]))?))?$'); // [11] tz_minute--function resolveYamlTimestamp(data) {- if (data === null) return false;- if (YAML_DATE_REGEXP.exec(data) !== null) return true;- if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;- return false;-}--function constructYamlTimestamp(data) {- var match, year, month, day, hour, minute, second, fraction = 0,- delta = null, tz_hour, tz_minute, date;-- match = YAML_DATE_REGEXP.exec(data);- if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);-- if (match === null) throw new Error('Date resolve error');-- // match: [1] year [2] month [3] day-- year = +(match[1]);- month = +(match[2]) - 1; // JS month starts with 0- day = +(match[3]);-- if (!match[4]) { // no hour- return new Date(Date.UTC(year, month, day));- }-- // match: [4] hour [5] minute [6] second [7] fraction-- hour = +(match[4]);- minute = +(match[5]);- second = +(match[6]);-- if (match[7]) {- fraction = match[7].slice(0, 3);- while (fraction.length < 3) { // milli-seconds- fraction += '0';- }- fraction = +fraction;- }-- // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute-- if (match[9]) {- tz_hour = +(match[10]);- tz_minute = +(match[11] || 0);- delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds- if (match[9] === '-') delta = -delta;- }-- date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));-- if (delta) date.setTime(date.getTime() - delta);-- return date;-}--function representYamlTimestamp(object /*, style*/) {- return object.toISOString();-}--var timestamp = new type('tag:yaml.org,2002:timestamp', {- kind: 'scalar',- resolve: resolveYamlTimestamp,- construct: constructYamlTimestamp,- instanceOf: Date,- represent: representYamlTimestamp-});--function resolveYamlMerge(data) {- return data === '<<' || data === null;-}--var merge = new type('tag:yaml.org,2002:merge', {- kind: 'scalar',- resolve: resolveYamlMerge-});--/*eslint-disable no-bitwise*/--var NodeBuffer;--try {- // A trick for browserified version, to not include `Buffer` shim- var _require = commonjsRequire;- NodeBuffer = _require('buffer').Buffer;-} catch (__) {}-----// [ 64, 65, 66 ] -> [ padding, CR, LF ]-var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';---function resolveYamlBinary(data) {- if (data === null) return false;-- var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;-- // Convert one by one.- for (idx = 0; idx < max; idx++) {- code = map.indexOf(data.charAt(idx));-- // Skip CR/LF- if (code > 64) continue;-- // Fail on illegal characters- if (code < 0) return false;-- bitlen += 6;- }-- // If there are any bits left, source was corrupted- return (bitlen % 8) === 0;-}--function constructYamlBinary(data) {- var idx, tailbits,- input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan- max = input.length,- map = BASE64_MAP,- bits = 0,- result = [];-- // Collect by 6*4 bits (3 bytes)-- for (idx = 0; idx < max; idx++) {- if ((idx % 4 === 0) && idx) {- result.push((bits >> 16) & 0xFF);- result.push((bits >> 8) & 0xFF);- result.push(bits & 0xFF);- }-- bits = (bits << 6) | map.indexOf(input.charAt(idx));- }-- // Dump tail-- tailbits = (max % 4) * 6;-- if (tailbits === 0) {- result.push((bits >> 16) & 0xFF);- result.push((bits >> 8) & 0xFF);- result.push(bits & 0xFF);- } else if (tailbits === 18) {- result.push((bits >> 10) & 0xFF);- result.push((bits >> 2) & 0xFF);- } else if (tailbits === 12) {- result.push((bits >> 4) & 0xFF);- }-- // Wrap into Buffer for NodeJS and leave Array for browser- if (NodeBuffer) {- // Support node 6.+ Buffer API when available- return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);- }-- return result;-}--function representYamlBinary(object /*, style*/) {- var result = '', bits = 0, idx, tail,- max = object.length,- map = BASE64_MAP;-- // Convert every three bytes to 4 ASCII characters.-- for (idx = 0; idx < max; idx++) {- if ((idx % 3 === 0) && idx) {- result += map[(bits >> 18) & 0x3F];- result += map[(bits >> 12) & 0x3F];- result += map[(bits >> 6) & 0x3F];- result += map[bits & 0x3F];- }-- bits = (bits << 8) + object[idx];- }-- // Dump tail-- tail = max % 3;-- if (tail === 0) {- result += map[(bits >> 18) & 0x3F];- result += map[(bits >> 12) & 0x3F];- result += map[(bits >> 6) & 0x3F];- result += map[bits & 0x3F];- } else if (tail === 2) {- result += map[(bits >> 10) & 0x3F];- result += map[(bits >> 4) & 0x3F];- result += map[(bits << 2) & 0x3F];- result += map[64];- } else if (tail === 1) {- result += map[(bits >> 2) & 0x3F];- result += map[(bits << 4) & 0x3F];- result += map[64];- result += map[64];- }-- return result;-}--function isBinary(object) {- return NodeBuffer && NodeBuffer.isBuffer(object);-}--var binary = new type('tag:yaml.org,2002:binary', {- kind: 'scalar',- resolve: resolveYamlBinary,- construct: constructYamlBinary,- predicate: isBinary,- represent: representYamlBinary-});--var _hasOwnProperty = Object.prototype.hasOwnProperty;-var _toString = Object.prototype.toString;--function resolveYamlOmap(data) {- if (data === null) return true;-- var objectKeys = [], index, length, pair, pairKey, pairHasKey,- object = data;-- for (index = 0, length = object.length; index < length; index += 1) {- pair = object[index];- pairHasKey = false;-- if (_toString.call(pair) !== '[object Object]') return false;-- for (pairKey in pair) {- if (_hasOwnProperty.call(pair, pairKey)) {- if (!pairHasKey) pairHasKey = true;- else return false;- }- }-- if (!pairHasKey) return false;-- if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);- else return false;- }-- return true;-}--function constructYamlOmap(data) {- return data !== null ? data : [];-}--var omap = new type('tag:yaml.org,2002:omap', {- kind: 'sequence',- resolve: resolveYamlOmap,- construct: constructYamlOmap-});--var _toString$1 = Object.prototype.toString;--function resolveYamlPairs(data) {- if (data === null) return true;-- var index, length, pair, keys, result,- object = data;-- result = new Array(object.length);-- for (index = 0, length = object.length; index < length; index += 1) {- pair = object[index];-- if (_toString$1.call(pair) !== '[object Object]') return false;-- keys = Object.keys(pair);-- if (keys.length !== 1) return false;-- result[index] = [ keys[0], pair[keys[0]] ];- }-- return true;-}--function constructYamlPairs(data) {- if (data === null) return [];-- var index, length, pair, keys, result,- object = data;-- result = new Array(object.length);-- for (index = 0, length = object.length; index < length; index += 1) {- pair = object[index];-- keys = Object.keys(pair);-- result[index] = [ keys[0], pair[keys[0]] ];- }-- return result;-}--var pairs = new type('tag:yaml.org,2002:pairs', {- kind: 'sequence',- resolve: resolveYamlPairs,- construct: constructYamlPairs-});--var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;--function resolveYamlSet(data) {- if (data === null) return true;-- var key, object = data;-- for (key in object) {- if (_hasOwnProperty$1.call(object, key)) {- if (object[key] !== null) return false;- }- }-- return true;-}--function constructYamlSet(data) {- return data !== null ? data : {};-}--var set = new type('tag:yaml.org,2002:set', {- kind: 'mapping',- resolve: resolveYamlSet,- construct: constructYamlSet-});--var default_safe = new schema({- include: [- core- ],- implicit: [- timestamp,- merge- ],- explicit: [- binary,- omap,- pairs,- set- ]-});--function resolveJavascriptUndefined() {- return true;-}--function constructJavascriptUndefined() {- /*eslint-disable no-undefined*/- return undefined;-}--function representJavascriptUndefined() {- return '';-}--function isUndefined(object) {- return typeof object === 'undefined';-}--var _undefined = new type('tag:yaml.org,2002:js/undefined', {- kind: 'scalar',- resolve: resolveJavascriptUndefined,- construct: constructJavascriptUndefined,- predicate: isUndefined,- represent: representJavascriptUndefined-});--function resolveJavascriptRegExp(data) {- if (data === null) return false;- if (data.length === 0) return false;-- var regexp = data,- tail = /\/([gim]*)$/.exec(data),- modifiers = '';-- // if regexp starts with '/' it can have modifiers and must be properly closed- // `/foo/gim` - modifiers tail can be maximum 3 chars- if (regexp[0] === '/') {- if (tail) modifiers = tail[1];-- if (modifiers.length > 3) return false;- // if expression starts with /, is should be properly terminated- if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;- }-- return true;-}--function constructJavascriptRegExp(data) {- var regexp = data,- tail = /\/([gim]*)$/.exec(data),- modifiers = '';-- // `/foo/gim` - tail can be maximum 4 chars- if (regexp[0] === '/') {- if (tail) modifiers = tail[1];- regexp = regexp.slice(1, regexp.length - modifiers.length - 1);- }-- return new RegExp(regexp, modifiers);-}--function representJavascriptRegExp(object /*, style*/) {- var result = '/' + object.source + '/';-- if (object.global) result += 'g';- if (object.multiline) result += 'm';- if (object.ignoreCase) result += 'i';-- return result;-}--function isRegExp(object) {- return Object.prototype.toString.call(object) === '[object RegExp]';-}--var regexp = new type('tag:yaml.org,2002:js/regexp', {- kind: 'scalar',- resolve: resolveJavascriptRegExp,- construct: constructJavascriptRegExp,- predicate: isRegExp,- represent: representJavascriptRegExp-});--var esprima;--// Browserified version does not have esprima-//-// 1. For node.js just require module as deps-// 2. For browser try to require mudule via external AMD system.-// If not found - try to fallback to window.esprima. If not-// found too - then fail to parse.-//-try {- // workaround to exclude package from browserify list.- var _require$1 = commonjsRequire;- esprima = _require$1('esprima');-} catch (_) {- /* eslint-disable no-redeclare */- /* global window */- if (typeof window !== 'undefined') esprima = window.esprima;-}----function resolveJavascriptFunction(data) {- if (data === null) return false;-- try {- var source = '(' + data + ')',- ast = esprima.parse(source, { range: true });-- if (ast.type !== 'Program' ||- ast.body.length !== 1 ||- ast.body[0].type !== 'ExpressionStatement' ||- (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&- ast.body[0].expression.type !== 'FunctionExpression')) {- return false;- }-- return true;- } catch (err) {- return false;- }-}--function constructJavascriptFunction(data) {- /*jslint evil:true*/-- var source = '(' + data + ')',- ast = esprima.parse(source, { range: true }),- params = [],- body;-- if (ast.type !== 'Program' ||- ast.body.length !== 1 ||- ast.body[0].type !== 'ExpressionStatement' ||- (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&- ast.body[0].expression.type !== 'FunctionExpression')) {- throw new Error('Failed to resolve function');- }-- ast.body[0].expression.params.forEach(function (param) {- params.push(param.name);- });-- body = ast.body[0].expression.body.range;-- // Esprima's ranges include the first '{' and the last '}' characters on- // function expressions. So cut them out.- if (ast.body[0].expression.body.type === 'BlockStatement') {- /*eslint-disable no-new-func*/- return new Function(params, source.slice(body[0] + 1, body[1] - 1));- }- // ES6 arrow functions can omit the BlockStatement. In that case, just return- // the body.- /*eslint-disable no-new-func*/- return new Function(params, 'return ' + source.slice(body[0], body[1]));-}--function representJavascriptFunction(object /*, style*/) {- return object.toString();-}--function isFunction(object) {- return Object.prototype.toString.call(object) === '[object Function]';-}--var _function = new type('tag:yaml.org,2002:js/function', {- kind: 'scalar',- resolve: resolveJavascriptFunction,- construct: constructJavascriptFunction,- predicate: isFunction,- represent: representJavascriptFunction-});--var default_full = schema.DEFAULT = new schema({- include: [- default_safe- ],- explicit: [- _undefined,- regexp,- _function- ]-});--/*eslint-disable max-len,no-use-before-define*/---------var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;---var CONTEXT_FLOW_IN = 1;-var CONTEXT_FLOW_OUT = 2;-var CONTEXT_BLOCK_IN = 3;-var CONTEXT_BLOCK_OUT = 4;---var CHOMPING_CLIP = 1;-var CHOMPING_STRIP = 2;-var CHOMPING_KEEP = 3;---var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;-var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;-var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;-var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;-var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;---function _class(obj) { return Object.prototype.toString.call(obj); }--function is_EOL(c) {- return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);-}--function is_WHITE_SPACE(c) {- return (c === 0x09/* Tab */) || (c === 0x20/* Space */);-}--function is_WS_OR_EOL(c) {- return (c === 0x09/* Tab */) ||- (c === 0x20/* Space */) ||- (c === 0x0A/* LF */) ||- (c === 0x0D/* CR */);-}--function is_FLOW_INDICATOR(c) {- return c === 0x2C/* , */ ||- c === 0x5B/* [ */ ||- c === 0x5D/* ] */ ||- c === 0x7B/* { */ ||- c === 0x7D/* } */;-}--function fromHexCode(c) {- var lc;-- if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {- return c - 0x30;- }-- /*eslint-disable no-bitwise*/- lc = c | 0x20;-- if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {- return lc - 0x61 + 10;- }-- return -1;-}--function escapedHexLen(c) {- if (c === 0x78/* x */) { return 2; }- if (c === 0x75/* u */) { return 4; }- if (c === 0x55/* U */) { return 8; }- return 0;-}--function fromDecimalCode(c) {- if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {- return c - 0x30;- }-- return -1;-}--function simpleEscapeSequence(c) {- /* eslint-disable indent */- return (c === 0x30/* 0 */) ? '\x00' :- (c === 0x61/* a */) ? '\x07' :- (c === 0x62/* b */) ? '\x08' :- (c === 0x74/* t */) ? '\x09' :- (c === 0x09/* Tab */) ? '\x09' :- (c === 0x6E/* n */) ? '\x0A' :- (c === 0x76/* v */) ? '\x0B' :- (c === 0x66/* f */) ? '\x0C' :- (c === 0x72/* r */) ? '\x0D' :- (c === 0x65/* e */) ? '\x1B' :- (c === 0x20/* Space */) ? ' ' :- (c === 0x22/* " */) ? '\x22' :- (c === 0x2F/* / */) ? '/' :- (c === 0x5C/* \ */) ? '\x5C' :- (c === 0x4E/* N */) ? '\x85' :- (c === 0x5F/* _ */) ? '\xA0' :- (c === 0x4C/* L */) ? '\u2028' :- (c === 0x50/* P */) ? '\u2029' : '';-}--function charFromCodepoint(c) {- if (c <= 0xFFFF) {- return String.fromCharCode(c);- }- // Encode UTF-16 surrogate pair- // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF- return String.fromCharCode(- ((c - 0x010000) >> 10) + 0xD800,- ((c - 0x010000) & 0x03FF) + 0xDC00- );-}--var simpleEscapeCheck = new Array(256); // integer, for fast access-var simpleEscapeMap = new Array(256);-for (var i = 0; i < 256; i++) {- simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;- simpleEscapeMap[i] = simpleEscapeSequence(i);-}---function State(input, options) {- this.input = input;-- this.filename = options['filename'] || null;- this.schema = options['schema'] || default_full;- this.onWarning = options['onWarning'] || null;- this.legacy = options['legacy'] || false;- this.json = options['json'] || false;- this.listener = options['listener'] || null;-- this.implicitTypes = this.schema.compiledImplicit;- this.typeMap = this.schema.compiledTypeMap;-- this.length = input.length;- this.position = 0;- this.line = 0;- this.lineStart = 0;- this.lineIndent = 0;-- this.documents = [];-- /*- this.version;- this.checkLineBreaks;- this.tagMap;- this.anchorMap;- this.tag;- this.anchor;- this.kind;- this.result;*/--}---function generateError(state, message) {- return new exception(- message,- new mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));-}--function throwError$1(state, message) {- throw generateError(state, message);-}--function throwWarning(state, message) {- if (state.onWarning) {- state.onWarning.call(null, generateError(state, message));- }-}---var directiveHandlers = {-- YAML: function handleYamlDirective(state, name, args) {-- var match, major, minor;-- if (state.version !== null) {- throwError$1(state, 'duplication of %YAML directive');- }-- if (args.length !== 1) {- throwError$1(state, 'YAML directive accepts exactly one argument');- }-- match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);-- if (match === null) {- throwError$1(state, 'ill-formed argument of the YAML directive');- }-- major = parseInt(match[1], 10);- minor = parseInt(match[2], 10);-- if (major !== 1) {- throwError$1(state, 'unacceptable YAML version of the document');- }-- state.version = args[0];- state.checkLineBreaks = (minor < 2);-- if (minor !== 1 && minor !== 2) {- throwWarning(state, 'unsupported YAML version of the document');- }- },-- TAG: function handleTagDirective(state, name, args) {-- var handle, prefix;-- if (args.length !== 2) {- throwError$1(state, 'TAG directive accepts exactly two arguments');- }-- handle = args[0];- prefix = args[1];-- if (!PATTERN_TAG_HANDLE.test(handle)) {- throwError$1(state, 'ill-formed tag handle (first argument) of the TAG directive');- }-- if (_hasOwnProperty$2.call(state.tagMap, handle)) {- throwError$1(state, 'there is a previously declared suffix for "' + handle + '" tag handle');- }-- if (!PATTERN_TAG_URI.test(prefix)) {- throwError$1(state, 'ill-formed tag prefix (second argument) of the TAG directive');- }-- state.tagMap[handle] = prefix;- }-};---function captureSegment(state, start, end, checkJson) {- var _position, _length, _character, _result;-- if (start < end) {- _result = state.input.slice(start, end);-- if (checkJson) {- for (_position = 0, _length = _result.length; _position < _length; _position += 1) {- _character = _result.charCodeAt(_position);- if (!(_character === 0x09 ||- (0x20 <= _character && _character <= 0x10FFFF))) {- throwError$1(state, 'expected valid JSON character');- }- }- } else if (PATTERN_NON_PRINTABLE.test(_result)) {- throwError$1(state, 'the stream contains non-printable characters');- }-- state.result += _result;- }-}--function mergeMappings(state, destination, source, overridableKeys) {- var sourceKeys, key, index, quantity;-- if (!common$1.isObject(source)) {- throwError$1(state, 'cannot merge mappings; the provided source object is unacceptable');- }-- sourceKeys = Object.keys(source);-- for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {- key = sourceKeys[index];-- if (!_hasOwnProperty$2.call(destination, key)) {- destination[key] = source[key];- overridableKeys[key] = true;- }- }-}--function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {- var index, quantity;-- // The output is a plain object here, so keys can only be strings.- // We need to convert keyNode to a string, but doing so can hang the process- // (deeply nested arrays that explode exponentially using aliases).- if (Array.isArray(keyNode)) {- keyNode = Array.prototype.slice.call(keyNode);-- for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {- if (Array.isArray(keyNode[index])) {- throwError$1(state, 'nested arrays are not supported inside keys');- }-- if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {- keyNode[index] = '[object Object]';- }- }- }-- // Avoid code execution in load() via toString property- // (still use its own toString for arrays, timestamps,- // and whatever user schema extensions happen to have @@toStringTag)- if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {- keyNode = '[object Object]';- }--- keyNode = String(keyNode);-- if (_result === null) {- _result = {};- }-- if (keyTag === 'tag:yaml.org,2002:merge') {- if (Array.isArray(valueNode)) {- for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {- mergeMappings(state, _result, valueNode[index], overridableKeys);- }- } else {- mergeMappings(state, _result, valueNode, overridableKeys);- }- } else {- if (!state.json &&- !_hasOwnProperty$2.call(overridableKeys, keyNode) &&- _hasOwnProperty$2.call(_result, keyNode)) {- state.line = startLine || state.line;- state.position = startPos || state.position;- throwError$1(state, 'duplicated mapping key');- }- _result[keyNode] = valueNode;- delete overridableKeys[keyNode];- }-- return _result;-}--function readLineBreak(state) {- var ch;-- ch = state.input.charCodeAt(state.position);-- if (ch === 0x0A/* LF */) {- state.position++;- } else if (ch === 0x0D/* CR */) {- state.position++;- if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {- state.position++;- }- } else {- throwError$1(state, 'a line break is expected');- }-- state.line += 1;- state.lineStart = state.position;-}--function skipSeparationSpace(state, allowComments, checkIndent) {- var lineBreaks = 0,- ch = state.input.charCodeAt(state.position);-- while (ch !== 0) {- while (is_WHITE_SPACE(ch)) {- ch = state.input.charCodeAt(++state.position);- }-- if (allowComments && ch === 0x23/* # */) {- do {- ch = state.input.charCodeAt(++state.position);- } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);- }-- if (is_EOL(ch)) {- readLineBreak(state);-- ch = state.input.charCodeAt(state.position);- lineBreaks++;- state.lineIndent = 0;-- while (ch === 0x20/* Space */) {- state.lineIndent++;- ch = state.input.charCodeAt(++state.position);- }- } else {- break;- }- }-- if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {- throwWarning(state, 'deficient indentation');- }-- return lineBreaks;-}--function testDocumentSeparator(state) {- var _position = state.position,- ch;-- ch = state.input.charCodeAt(_position);-- // Condition state.position === state.lineStart is tested- // in parent on each call, for efficiency. No needs to test here again.- if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&- ch === state.input.charCodeAt(_position + 1) &&- ch === state.input.charCodeAt(_position + 2)) {-- _position += 3;-- ch = state.input.charCodeAt(_position);-- if (ch === 0 || is_WS_OR_EOL(ch)) {- return true;- }- }-- return false;-}--function writeFoldedLines(state, count) {- if (count === 1) {- state.result += ' ';- } else if (count > 1) {- state.result += common$1.repeat('\n', count - 1);- }-}---function readPlainScalar(state, nodeIndent, withinFlowCollection) {- var preceding,- following,- captureStart,- captureEnd,- hasPendingContent,- _line,- _lineStart,- _lineIndent,- _kind = state.kind,- _result = state.result,- ch;-- ch = state.input.charCodeAt(state.position);-- if (is_WS_OR_EOL(ch) ||- is_FLOW_INDICATOR(ch) ||- ch === 0x23/* # */ ||- ch === 0x26/* & */ ||- ch === 0x2A/* * */ ||- ch === 0x21/* ! */ ||- ch === 0x7C/* | */ ||- ch === 0x3E/* > */ ||- ch === 0x27/* ' */ ||- ch === 0x22/* " */ ||- ch === 0x25/* % */ ||- ch === 0x40/* @ */ ||- ch === 0x60/* ` */) {- return false;- }-- if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {- following = state.input.charCodeAt(state.position + 1);-- if (is_WS_OR_EOL(following) ||- withinFlowCollection && is_FLOW_INDICATOR(following)) {- return false;- }- }-- state.kind = 'scalar';- state.result = '';- captureStart = captureEnd = state.position;- hasPendingContent = false;-- while (ch !== 0) {- if (ch === 0x3A/* : */) {- following = state.input.charCodeAt(state.position + 1);-- if (is_WS_OR_EOL(following) ||- withinFlowCollection && is_FLOW_INDICATOR(following)) {- break;- }-- } else if (ch === 0x23/* # */) {- preceding = state.input.charCodeAt(state.position - 1);-- if (is_WS_OR_EOL(preceding)) {- break;- }-- } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||- withinFlowCollection && is_FLOW_INDICATOR(ch)) {- break;-- } else if (is_EOL(ch)) {- _line = state.line;- _lineStart = state.lineStart;- _lineIndent = state.lineIndent;- skipSeparationSpace(state, false, -1);-- if (state.lineIndent >= nodeIndent) {- hasPendingContent = true;- ch = state.input.charCodeAt(state.position);- continue;- } else {- state.position = captureEnd;- state.line = _line;- state.lineStart = _lineStart;- state.lineIndent = _lineIndent;- break;- }- }-- if (hasPendingContent) {- captureSegment(state, captureStart, captureEnd, false);- writeFoldedLines(state, state.line - _line);- captureStart = captureEnd = state.position;- hasPendingContent = false;- }-- if (!is_WHITE_SPACE(ch)) {- captureEnd = state.position + 1;- }-- ch = state.input.charCodeAt(++state.position);- }-- captureSegment(state, captureStart, captureEnd, false);-- if (state.result) {- return true;- }-- state.kind = _kind;- state.result = _result;- return false;-}--function readSingleQuotedScalar(state, nodeIndent) {- var ch,- captureStart, captureEnd;-- ch = state.input.charCodeAt(state.position);-- if (ch !== 0x27/* ' */) {- return false;- }-- state.kind = 'scalar';- state.result = '';- state.position++;- captureStart = captureEnd = state.position;-- while ((ch = state.input.charCodeAt(state.position)) !== 0) {- if (ch === 0x27/* ' */) {- captureSegment(state, captureStart, state.position, true);- ch = state.input.charCodeAt(++state.position);-- if (ch === 0x27/* ' */) {- captureStart = state.position;- state.position++;- captureEnd = state.position;- } else {- return true;- }-- } else if (is_EOL(ch)) {- captureSegment(state, captureStart, captureEnd, true);- writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));- captureStart = captureEnd = state.position;-- } else if (state.position === state.lineStart && testDocumentSeparator(state)) {- throwError$1(state, 'unexpected end of the document within a single quoted scalar');-- } else {- state.position++;- captureEnd = state.position;- }- }-- throwError$1(state, 'unexpected end of the stream within a single quoted scalar');-}--function readDoubleQuotedScalar(state, nodeIndent) {- var captureStart,- captureEnd,- hexLength,- hexResult,- tmp,- ch;-- ch = state.input.charCodeAt(state.position);-- if (ch !== 0x22/* " */) {- return false;- }-- state.kind = 'scalar';- state.result = '';- state.position++;- captureStart = captureEnd = state.position;-- while ((ch = state.input.charCodeAt(state.position)) !== 0) {- if (ch === 0x22/* " */) {- captureSegment(state, captureStart, state.position, true);- state.position++;- return true;-- } else if (ch === 0x5C/* \ */) {- captureSegment(state, captureStart, state.position, true);- ch = state.input.charCodeAt(++state.position);-- if (is_EOL(ch)) {- skipSeparationSpace(state, false, nodeIndent);-- // TODO: rework to inline fn with no type cast?- } else if (ch < 256 && simpleEscapeCheck[ch]) {- state.result += simpleEscapeMap[ch];- state.position++;-- } else if ((tmp = escapedHexLen(ch)) > 0) {- hexLength = tmp;- hexResult = 0;-- for (; hexLength > 0; hexLength--) {- ch = state.input.charCodeAt(++state.position);-- if ((tmp = fromHexCode(ch)) >= 0) {- hexResult = (hexResult << 4) + tmp;-- } else {- throwError$1(state, 'expected hexadecimal character');- }- }-- state.result += charFromCodepoint(hexResult);-- state.position++;-- } else {- throwError$1(state, 'unknown escape sequence');- }-- captureStart = captureEnd = state.position;-- } else if (is_EOL(ch)) {- captureSegment(state, captureStart, captureEnd, true);- writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));- captureStart = captureEnd = state.position;-- } else if (state.position === state.lineStart && testDocumentSeparator(state)) {- throwError$1(state, 'unexpected end of the document within a double quoted scalar');-- } else {- state.position++;- captureEnd = state.position;- }- }-- throwError$1(state, 'unexpected end of the stream within a double quoted scalar');-}--function readFlowCollection(state, nodeIndent) {- var readNext = true,- _line,- _tag = state.tag,- _result,- _anchor = state.anchor,- following,- terminator,- isPair,- isExplicitPair,- isMapping,- overridableKeys = {},- keyNode,- keyTag,- valueNode,- ch;-- ch = state.input.charCodeAt(state.position);-- if (ch === 0x5B/* [ */) {- terminator = 0x5D;/* ] */- isMapping = false;- _result = [];- } else if (ch === 0x7B/* { */) {- terminator = 0x7D;/* } */- isMapping = true;- _result = {};- } else {- return false;- }-- if (state.anchor !== null) {- state.anchorMap[state.anchor] = _result;- }-- ch = state.input.charCodeAt(++state.position);-- while (ch !== 0) {- skipSeparationSpace(state, true, nodeIndent);-- ch = state.input.charCodeAt(state.position);-- if (ch === terminator) {- state.position++;- state.tag = _tag;- state.anchor = _anchor;- state.kind = isMapping ? 'mapping' : 'sequence';- state.result = _result;- return true;- } else if (!readNext) {- throwError$1(state, 'missed comma between flow collection entries');- }-- keyTag = keyNode = valueNode = null;- isPair = isExplicitPair = false;-- if (ch === 0x3F/* ? */) {- following = state.input.charCodeAt(state.position + 1);-- if (is_WS_OR_EOL(following)) {- isPair = isExplicitPair = true;- state.position++;- skipSeparationSpace(state, true, nodeIndent);- }- }-- _line = state.line;- composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);- keyTag = state.tag;- keyNode = state.result;- skipSeparationSpace(state, true, nodeIndent);-- ch = state.input.charCodeAt(state.position);-- if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {- isPair = true;- ch = state.input.charCodeAt(++state.position);- skipSeparationSpace(state, true, nodeIndent);- composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);- valueNode = state.result;- }-- if (isMapping) {- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);- } else if (isPair) {- _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));- } else {- _result.push(keyNode);- }-- skipSeparationSpace(state, true, nodeIndent);-- ch = state.input.charCodeAt(state.position);-- if (ch === 0x2C/* , */) {- readNext = true;- ch = state.input.charCodeAt(++state.position);- } else {- readNext = false;- }- }-- throwError$1(state, 'unexpected end of the stream within a flow collection');-}--function readBlockScalar(state, nodeIndent) {- var captureStart,- folding,- chomping = CHOMPING_CLIP,- didReadContent = false,- detectedIndent = false,- textIndent = nodeIndent,- emptyLines = 0,- atMoreIndented = false,- tmp,- ch;-- ch = state.input.charCodeAt(state.position);-- if (ch === 0x7C/* | */) {- folding = false;- } else if (ch === 0x3E/* > */) {- folding = true;- } else {- return false;- }-- state.kind = 'scalar';- state.result = '';-- while (ch !== 0) {- ch = state.input.charCodeAt(++state.position);-- if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {- if (CHOMPING_CLIP === chomping) {- chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;- } else {- throwError$1(state, 'repeat of a chomping mode identifier');- }-- } else if ((tmp = fromDecimalCode(ch)) >= 0) {- if (tmp === 0) {- throwError$1(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');- } else if (!detectedIndent) {- textIndent = nodeIndent + tmp - 1;- detectedIndent = true;- } else {- throwError$1(state, 'repeat of an indentation width identifier');- }-- } else {- break;- }- }-- if (is_WHITE_SPACE(ch)) {- do { ch = state.input.charCodeAt(++state.position); }- while (is_WHITE_SPACE(ch));-- if (ch === 0x23/* # */) {- do { ch = state.input.charCodeAt(++state.position); }- while (!is_EOL(ch) && (ch !== 0));- }- }-- while (ch !== 0) {- readLineBreak(state);- state.lineIndent = 0;-- ch = state.input.charCodeAt(state.position);-- while ((!detectedIndent || state.lineIndent < textIndent) &&- (ch === 0x20/* Space */)) {- state.lineIndent++;- ch = state.input.charCodeAt(++state.position);- }-- if (!detectedIndent && state.lineIndent > textIndent) {- textIndent = state.lineIndent;- }-- if (is_EOL(ch)) {- emptyLines++;- continue;- }-- // End of the scalar.- if (state.lineIndent < textIndent) {-- // Perform the chomping.- if (chomping === CHOMPING_KEEP) {- state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);- } else if (chomping === CHOMPING_CLIP) {- if (didReadContent) { // i.e. only if the scalar is not empty.- state.result += '\n';- }- }-- // Break this `while` cycle and go to the funciton's epilogue.- break;- }-- // Folded style: use fancy rules to handle line breaks.- if (folding) {-- // Lines starting with white space characters (more-indented lines) are not folded.- if (is_WHITE_SPACE(ch)) {- atMoreIndented = true;- // except for the first content line (cf. Example 8.1)- state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);-- // End of more-indented block.- } else if (atMoreIndented) {- atMoreIndented = false;- state.result += common$1.repeat('\n', emptyLines + 1);-- // Just one line break - perceive as the same line.- } else if (emptyLines === 0) {- if (didReadContent) { // i.e. only if we have already read some scalar content.- state.result += ' ';- }-- // Several line breaks - perceive as different lines.- } else {- state.result += common$1.repeat('\n', emptyLines);- }-- // Literal style: just add exact number of line breaks between content lines.- } else {- // Keep all line breaks except the header line break.- state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);- }-- didReadContent = true;- detectedIndent = true;- emptyLines = 0;- captureStart = state.position;-- while (!is_EOL(ch) && (ch !== 0)) {- ch = state.input.charCodeAt(++state.position);- }-- captureSegment(state, captureStart, state.position, false);- }-- return true;-}--function readBlockSequence(state, nodeIndent) {- var _line,- _tag = state.tag,- _anchor = state.anchor,- _result = [],- following,- detected = false,- ch;-- if (state.anchor !== null) {- state.anchorMap[state.anchor] = _result;- }-- ch = state.input.charCodeAt(state.position);-- while (ch !== 0) {-- if (ch !== 0x2D/* - */) {- break;- }-- following = state.input.charCodeAt(state.position + 1);-- if (!is_WS_OR_EOL(following)) {- break;- }-- detected = true;- state.position++;-- if (skipSeparationSpace(state, true, -1)) {- if (state.lineIndent <= nodeIndent) {- _result.push(null);- ch = state.input.charCodeAt(state.position);- continue;- }- }-- _line = state.line;- composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);- _result.push(state.result);- skipSeparationSpace(state, true, -1);-- ch = state.input.charCodeAt(state.position);-- if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {- throwError$1(state, 'bad indentation of a sequence entry');- } else if (state.lineIndent < nodeIndent) {- break;- }- }-- if (detected) {- state.tag = _tag;- state.anchor = _anchor;- state.kind = 'sequence';- state.result = _result;- return true;- }- return false;-}--function readBlockMapping(state, nodeIndent, flowIndent) {- var following,- allowCompact,- _line,- _pos,- _tag = state.tag,- _anchor = state.anchor,- _result = {},- overridableKeys = {},- keyTag = null,- keyNode = null,- valueNode = null,- atExplicitKey = false,- detected = false,- ch;-- if (state.anchor !== null) {- state.anchorMap[state.anchor] = _result;- }-- ch = state.input.charCodeAt(state.position);-- while (ch !== 0) {- following = state.input.charCodeAt(state.position + 1);- _line = state.line; // Save the current line.- _pos = state.position;-- //- // Explicit notation case. There are two separate blocks:- // first for the key (denoted by "?") and second for the value (denoted by ":")- //- if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {-- if (ch === 0x3F/* ? */) {- if (atExplicitKey) {- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);- keyTag = keyNode = valueNode = null;- }-- detected = true;- atExplicitKey = true;- allowCompact = true;-- } else if (atExplicitKey) {- // i.e. 0x3A/* : */ === character after the explicit key.- atExplicitKey = false;- allowCompact = true;-- } else {- throwError$1(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');- }-- state.position += 1;- ch = following;-- //- // Implicit notation case. Flow-style node as the key first, then ":", and the value.- //- } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {-- if (state.line === _line) {- ch = state.input.charCodeAt(state.position);-- while (is_WHITE_SPACE(ch)) {- ch = state.input.charCodeAt(++state.position);- }-- if (ch === 0x3A/* : */) {- ch = state.input.charCodeAt(++state.position);-- if (!is_WS_OR_EOL(ch)) {- throwError$1(state, 'a whitespace character is expected after the key-value separator within a block mapping');- }-- if (atExplicitKey) {- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);- keyTag = keyNode = valueNode = null;- }-- detected = true;- atExplicitKey = false;- allowCompact = false;- keyTag = state.tag;- keyNode = state.result;-- } else if (detected) {- throwError$1(state, 'can not read an implicit mapping pair; a colon is missed');-- } else {- state.tag = _tag;- state.anchor = _anchor;- return true; // Keep the result of `composeNode`.- }-- } else if (detected) {- throwError$1(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');-- } else {- state.tag = _tag;- state.anchor = _anchor;- return true; // Keep the result of `composeNode`.- }-- } else {- break; // Reading is done. Go to the epilogue.- }-- //- // Common reading code for both explicit and implicit notations.- //- if (state.line === _line || state.lineIndent > nodeIndent) {- if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {- if (atExplicitKey) {- keyNode = state.result;- } else {- valueNode = state.result;- }- }-- if (!atExplicitKey) {- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);- keyTag = keyNode = valueNode = null;- }-- skipSeparationSpace(state, true, -1);- ch = state.input.charCodeAt(state.position);- }-- if (state.lineIndent > nodeIndent && (ch !== 0)) {- throwError$1(state, 'bad indentation of a mapping entry');- } else if (state.lineIndent < nodeIndent) {- break;- }- }-- //- // Epilogue.- //-- // Special case: last mapping's node contains only the key in explicit notation.- if (atExplicitKey) {- storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);- }-- // Expose the resulting mapping.- if (detected) {- state.tag = _tag;- state.anchor = _anchor;- state.kind = 'mapping';- state.result = _result;- }-- return detected;-}--function readTagProperty(state) {- var _position,- isVerbatim = false,- isNamed = false,- tagHandle,- tagName,- ch;-- ch = state.input.charCodeAt(state.position);-- if (ch !== 0x21/* ! */) return false;-- if (state.tag !== null) {- throwError$1(state, 'duplication of a tag property');- }-- ch = state.input.charCodeAt(++state.position);-- if (ch === 0x3C/* < */) {- isVerbatim = true;- ch = state.input.charCodeAt(++state.position);-- } else if (ch === 0x21/* ! */) {- isNamed = true;- tagHandle = '!!';- ch = state.input.charCodeAt(++state.position);-- } else {- tagHandle = '!';- }-- _position = state.position;-- if (isVerbatim) {- do { ch = state.input.charCodeAt(++state.position); }- while (ch !== 0 && ch !== 0x3E/* > */);-- if (state.position < state.length) {- tagName = state.input.slice(_position, state.position);- ch = state.input.charCodeAt(++state.position);- } else {- throwError$1(state, 'unexpected end of the stream within a verbatim tag');- }- } else {- while (ch !== 0 && !is_WS_OR_EOL(ch)) {-- if (ch === 0x21/* ! */) {- if (!isNamed) {- tagHandle = state.input.slice(_position - 1, state.position + 1);-- if (!PATTERN_TAG_HANDLE.test(tagHandle)) {- throwError$1(state, 'named tag handle cannot contain such characters');- }-- isNamed = true;- _position = state.position + 1;- } else {- throwError$1(state, 'tag suffix cannot contain exclamation marks');- }- }-- ch = state.input.charCodeAt(++state.position);- }-- tagName = state.input.slice(_position, state.position);-- if (PATTERN_FLOW_INDICATORS.test(tagName)) {- throwError$1(state, 'tag suffix cannot contain flow indicator characters');- }- }-- if (tagName && !PATTERN_TAG_URI.test(tagName)) {- throwError$1(state, 'tag name cannot contain such characters: ' + tagName);- }-- if (isVerbatim) {- state.tag = tagName;-- } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) {- state.tag = state.tagMap[tagHandle] + tagName;-- } else if (tagHandle === '!') {- state.tag = '!' + tagName;-- } else if (tagHandle === '!!') {- state.tag = 'tag:yaml.org,2002:' + tagName;-- } else {- throwError$1(state, 'undeclared tag handle "' + tagHandle + '"');- }-- return true;-}--function readAnchorProperty(state) {- var _position,- ch;-- ch = state.input.charCodeAt(state.position);-- if (ch !== 0x26/* & */) return false;-- if (state.anchor !== null) {- throwError$1(state, 'duplication of an anchor property');- }-- ch = state.input.charCodeAt(++state.position);- _position = state.position;-- while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {- ch = state.input.charCodeAt(++state.position);- }-- if (state.position === _position) {- throwError$1(state, 'name of an anchor node must contain at least one character');- }-- state.anchor = state.input.slice(_position, state.position);- return true;-}--function readAlias(state) {- var _position, alias,- ch;-- ch = state.input.charCodeAt(state.position);-- if (ch !== 0x2A/* * */) return false;-- ch = state.input.charCodeAt(++state.position);- _position = state.position;-- while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {- ch = state.input.charCodeAt(++state.position);- }-- if (state.position === _position) {- throwError$1(state, 'name of an alias node must contain at least one character');- }-- alias = state.input.slice(_position, state.position);-- if (!state.anchorMap.hasOwnProperty(alias)) {- throwError$1(state, 'unidentified alias "' + alias + '"');- }-- state.result = state.anchorMap[alias];- skipSeparationSpace(state, true, -1);- return true;-}--function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {- var allowBlockStyles,- allowBlockScalars,- allowBlockCollections,- indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent- atNewLine = false,- hasContent = false,- typeIndex,- typeQuantity,- type,- flowIndent,- blockIndent;-- if (state.listener !== null) {- state.listener('open', state);- }-- state.tag = null;- state.anchor = null;- state.kind = null;- state.result = null;-- allowBlockStyles = allowBlockScalars = allowBlockCollections =- CONTEXT_BLOCK_OUT === nodeContext ||- CONTEXT_BLOCK_IN === nodeContext;-- if (allowToSeek) {- if (skipSeparationSpace(state, true, -1)) {- atNewLine = true;-- if (state.lineIndent > parentIndent) {- indentStatus = 1;- } else if (state.lineIndent === parentIndent) {- indentStatus = 0;- } else if (state.lineIndent < parentIndent) {- indentStatus = -1;- }- }- }-- if (indentStatus === 1) {- while (readTagProperty(state) || readAnchorProperty(state)) {- if (skipSeparationSpace(state, true, -1)) {- atNewLine = true;- allowBlockCollections = allowBlockStyles;-- if (state.lineIndent > parentIndent) {- indentStatus = 1;- } else if (state.lineIndent === parentIndent) {- indentStatus = 0;- } else if (state.lineIndent < parentIndent) {- indentStatus = -1;- }- } else {- allowBlockCollections = false;- }- }- }-- if (allowBlockCollections) {- allowBlockCollections = atNewLine || allowCompact;- }-- if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {- if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {- flowIndent = parentIndent;- } else {- flowIndent = parentIndent + 1;- }-- blockIndent = state.position - state.lineStart;-- if (indentStatus === 1) {- if (allowBlockCollections &&- (readBlockSequence(state, blockIndent) ||- readBlockMapping(state, blockIndent, flowIndent)) ||- readFlowCollection(state, flowIndent)) {- hasContent = true;- } else {- if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||- readSingleQuotedScalar(state, flowIndent) ||- readDoubleQuotedScalar(state, flowIndent)) {- hasContent = true;-- } else if (readAlias(state)) {- hasContent = true;-- if (state.tag !== null || state.anchor !== null) {- throwError$1(state, 'alias node should not have any properties');- }-- } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {- hasContent = true;-- if (state.tag === null) {- state.tag = '?';- }- }-- if (state.anchor !== null) {- state.anchorMap[state.anchor] = state.result;- }- }- } else if (indentStatus === 0) {- // Special case: block sequences are allowed to have same indentation level as the parent.- // http://www.yaml.org/spec/1.2/spec.html#id2799784- hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);- }- }-- if (state.tag !== null && state.tag !== '!') {- if (state.tag === '?') {- // Implicit resolving is not allowed for non-scalar types, and '?'- // non-specific tag is only automatically assigned to plain scalars.- //- // We only need to check kind conformity in case user explicitly assigns '?'- // tag, for example like this: "!<?> [0]"- //- if (state.result !== null && state.kind !== 'scalar') {- throwError$1(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');- }-- for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {- type = state.implicitTypes[typeIndex];-- if (type.resolve(state.result)) { // `state.result` updated in resolver if matched- state.result = type.construct(state.result);- state.tag = type.tag;- if (state.anchor !== null) {- state.anchorMap[state.anchor] = state.result;- }- break;- }- }- } else if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) {- type = state.typeMap[state.kind || 'fallback'][state.tag];-- if (state.result !== null && type.kind !== state.kind) {- throwError$1(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');- }-- if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched- throwError$1(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');- } else {- state.result = type.construct(state.result);- if (state.anchor !== null) {- state.anchorMap[state.anchor] = state.result;- }- }- } else {- throwError$1(state, 'unknown tag !<' + state.tag + '>');- }- }-- if (state.listener !== null) {- state.listener('close', state);- }- return state.tag !== null || state.anchor !== null || hasContent;-}--function readDocument(state) {- var documentStart = state.position,- _position,- directiveName,- directiveArgs,- hasDirectives = false,- ch;-- state.version = null;- state.checkLineBreaks = state.legacy;- state.tagMap = {};- state.anchorMap = {};-- while ((ch = state.input.charCodeAt(state.position)) !== 0) {- skipSeparationSpace(state, true, -1);-- ch = state.input.charCodeAt(state.position);-- if (state.lineIndent > 0 || ch !== 0x25/* % */) {- break;- }-- hasDirectives = true;- ch = state.input.charCodeAt(++state.position);- _position = state.position;-- while (ch !== 0 && !is_WS_OR_EOL(ch)) {- ch = state.input.charCodeAt(++state.position);- }-- directiveName = state.input.slice(_position, state.position);- directiveArgs = [];-- if (directiveName.length < 1) {- throwError$1(state, 'directive name must not be less than one character in length');- }-- while (ch !== 0) {- while (is_WHITE_SPACE(ch)) {- ch = state.input.charCodeAt(++state.position);- }-- if (ch === 0x23/* # */) {- do { ch = state.input.charCodeAt(++state.position); }- while (ch !== 0 && !is_EOL(ch));- break;- }-- if (is_EOL(ch)) break;-- _position = state.position;-- while (ch !== 0 && !is_WS_OR_EOL(ch)) {- ch = state.input.charCodeAt(++state.position);- }-- directiveArgs.push(state.input.slice(_position, state.position));- }-- if (ch !== 0) readLineBreak(state);-- if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) {- directiveHandlers[directiveName](state, directiveName, directiveArgs);- } else {- throwWarning(state, 'unknown document directive "' + directiveName + '"');- }- }-- skipSeparationSpace(state, true, -1);-- if (state.lineIndent === 0 &&- state.input.charCodeAt(state.position) === 0x2D/* - */ &&- state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&- state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {- state.position += 3;- skipSeparationSpace(state, true, -1);-- } else if (hasDirectives) {- throwError$1(state, 'directives end mark is expected');- }-- composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);- skipSeparationSpace(state, true, -1);-- if (state.checkLineBreaks &&- PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {- throwWarning(state, 'non-ASCII line breaks are interpreted as content');- }-- state.documents.push(state.result);-- if (state.position === state.lineStart && testDocumentSeparator(state)) {-- if (state.input.charCodeAt(state.position) === 0x2E/* . */) {- state.position += 3;- skipSeparationSpace(state, true, -1);- }- return;- }-- if (state.position < (state.length - 1)) {- throwError$1(state, 'end of the stream or a document separator is expected');- } else {- return;- }-}---function loadDocuments$1(input, options) {- input = String(input);- options = options || {};-- if (input.length !== 0) {-- // Add tailing `\n` if not exists- if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&- input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {- input += '\n';- }-- // Strip BOM- if (input.charCodeAt(0) === 0xFEFF) {- input = input.slice(1);- }- }-- var state = new State(input, options);-- var nullpos = input.indexOf('\0');-- if (nullpos !== -1) {- state.position = nullpos;- throwError$1(state, 'null byte is not allowed in input');- }-- // Use 0 as string terminator. That significantly simplifies bounds check.- state.input += '\0';-- while (state.input.charCodeAt(state.position) === 0x20/* Space */) {- state.lineIndent += 1;- state.position += 1;- }-- while (state.position < (state.length - 1)) {- readDocument(state);- }-- return state.documents;-}---function loadAll(input, iterator, options) {- if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {- options = iterator;- iterator = null;- }-- var documents = loadDocuments$1(input, options);-- if (typeof iterator !== 'function') {- return documents;- }-- for (var index = 0, length = documents.length; index < length; index += 1) {- iterator(documents[index]);- }-}---function load(input, options) {- var documents = loadDocuments$1(input, options);-- if (documents.length === 0) {- /*eslint-disable no-undefined*/- return undefined;- } else if (documents.length === 1) {- return documents[0];- }- throw new exception('expected a single document in the stream, but found more');-}---function safeLoadAll(input, iterator, options) {- if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {- options = iterator;- iterator = null;- }-- return loadAll(input, iterator, common$1.extend({ schema: default_safe }, options));-}---function safeLoad(input, options) {- return load(input, common$1.extend({ schema: default_safe }, options));-}---var loadAll_1 = loadAll;-var load_1 = load;-var safeLoadAll_1 = safeLoadAll;-var safeLoad_1 = safeLoad;--var loader = {- loadAll: loadAll_1,- load: load_1,- safeLoadAll: safeLoadAll_1,- safeLoad: safeLoad_1-};--/*eslint-disable no-use-before-define*/-------var _toString$2 = Object.prototype.toString;-var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;--var CHAR_TAB = 0x09; /* Tab */-var CHAR_LINE_FEED = 0x0A; /* LF */-var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */-var CHAR_SPACE = 0x20; /* Space */-var CHAR_EXCLAMATION = 0x21; /* ! */-var CHAR_DOUBLE_QUOTE$1 = 0x22; /* " */-var CHAR_SHARP = 0x23; /* # */-var CHAR_PERCENT = 0x25; /* % */-var CHAR_AMPERSAND = 0x26; /* & */-var CHAR_SINGLE_QUOTE$1 = 0x27; /* ' */-var CHAR_ASTERISK$1 = 0x2A; /* * */-var CHAR_COMMA$2 = 0x2C; /* , */-var CHAR_MINUS = 0x2D; /* - */-var CHAR_COLON = 0x3A; /* : */-var CHAR_EQUALS = 0x3D; /* = */-var CHAR_GREATER_THAN = 0x3E; /* > */-var CHAR_QUESTION = 0x3F; /* ? */-var CHAR_COMMERCIAL_AT = 0x40; /* @ */-var CHAR_LEFT_SQUARE_BRACKET$2 = 0x5B; /* [ */-var CHAR_RIGHT_SQUARE_BRACKET$2 = 0x5D; /* ] */-var CHAR_GRAVE_ACCENT = 0x60; /* ` */-var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */-var CHAR_VERTICAL_LINE = 0x7C; /* | */-var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */--var ESCAPE_SEQUENCES = {};--ESCAPE_SEQUENCES[0x00] = '\\0';-ESCAPE_SEQUENCES[0x07] = '\\a';-ESCAPE_SEQUENCES[0x08] = '\\b';-ESCAPE_SEQUENCES[0x09] = '\\t';-ESCAPE_SEQUENCES[0x0A] = '\\n';-ESCAPE_SEQUENCES[0x0B] = '\\v';-ESCAPE_SEQUENCES[0x0C] = '\\f';-ESCAPE_SEQUENCES[0x0D] = '\\r';-ESCAPE_SEQUENCES[0x1B] = '\\e';-ESCAPE_SEQUENCES[0x22] = '\\"';-ESCAPE_SEQUENCES[0x5C] = '\\\\';-ESCAPE_SEQUENCES[0x85] = '\\N';-ESCAPE_SEQUENCES[0xA0] = '\\_';-ESCAPE_SEQUENCES[0x2028] = '\\L';-ESCAPE_SEQUENCES[0x2029] = '\\P';--var DEPRECATED_BOOLEANS_SYNTAX = [- 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',- 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'-];--function compileStyleMap(schema, map) {- var result, keys, index, length, tag, style, type;-- if (map === null) return {};-- result = {};- keys = Object.keys(map);-- for (index = 0, length = keys.length; index < length; index += 1) {- tag = keys[index];- style = String(map[tag]);-- if (tag.slice(0, 2) === '!!') {- tag = 'tag:yaml.org,2002:' + tag.slice(2);- }- type = schema.compiledTypeMap['fallback'][tag];-- if (type && _hasOwnProperty$3.call(type.styleAliases, style)) {- style = type.styleAliases[style];- }-- result[tag] = style;- }-- return result;-}--function encodeHex(character) {- var string, handle, length;-- string = character.toString(16).toUpperCase();-- if (character <= 0xFF) {- handle = 'x';- length = 2;- } else if (character <= 0xFFFF) {- handle = 'u';- length = 4;- } else if (character <= 0xFFFFFFFF) {- handle = 'U';- length = 8;- } else {- throw new exception('code point within a string may not be greater than 0xFFFFFFFF');- }-- return '\\' + handle + common$1.repeat('0', length - string.length) + string;-}--function State$1(options) {- this.schema = options['schema'] || default_full;- this.indent = Math.max(1, (options['indent'] || 2));- this.noArrayIndent = options['noArrayIndent'] || false;- this.skipInvalid = options['skipInvalid'] || false;- this.flowLevel = (common$1.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);- this.styleMap = compileStyleMap(this.schema, options['styles'] || null);- this.sortKeys = options['sortKeys'] || false;- this.lineWidth = options['lineWidth'] || 80;- this.noRefs = options['noRefs'] || false;- this.noCompatMode = options['noCompatMode'] || false;- this.condenseFlow = options['condenseFlow'] || false;-- this.implicitTypes = this.schema.compiledImplicit;- this.explicitTypes = this.schema.compiledExplicit;-- this.tag = null;- this.result = '';-- this.duplicates = [];- this.usedDuplicates = null;-}--// Indents every line in a string. Empty lines (\n only) are not indented.-function indentString$2(string, spaces) {- var ind = common$1.repeat(' ', spaces),- position = 0,- next = -1,- result = '',- line,- length = string.length;-- while (position < length) {- next = string.indexOf('\n', position);- if (next === -1) {- line = string.slice(position);- position = length;- } else {- line = string.slice(position, next + 1);- position = next + 1;- }-- if (line.length && line !== '\n') result += ind;-- result += line;- }-- return result;-}--function generateNextLine(state, level) {- return '\n' + common$1.repeat(' ', state.indent * level);-}--function testImplicitResolving(state, str) {- var index, length, type;-- for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {- type = state.implicitTypes[index];-- if (type.resolve(str)) {- return true;- }- }-- return false;-}--// [33] s-white ::= s-space | s-tab-function isWhitespace(c) {- return c === CHAR_SPACE || c === CHAR_TAB;-}--// Returns true if the character can be printed without escaping.-// From YAML 1.2: "any allowed characters known to be non-printable-// should also be escaped. [However,] This isn’t mandatory"-// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.-function isPrintable(c) {- return (0x00020 <= c && c <= 0x00007E)- || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)- || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)- || (0x10000 <= c && c <= 0x10FFFF);-}--// [34] ns-char ::= nb-char - s-white-// [27] nb-char ::= c-printable - b-char - c-byte-order-mark-// [26] b-char ::= b-line-feed | b-carriage-return-// [24] b-line-feed ::= #xA /* LF */-// [25] b-carriage-return ::= #xD /* CR */-// [3] c-byte-order-mark ::= #xFEFF-function isNsChar(c) {- return isPrintable(c) && !isWhitespace(c)- // byte-order-mark- && c !== 0xFEFF- // b-char- && c !== CHAR_CARRIAGE_RETURN- && c !== CHAR_LINE_FEED;-}--// Simplified test for values allowed after the first character in plain style.-function isPlainSafe(c, prev) {- // Uses a subset of nb-char - c-flow-indicator - ":" - "#"- // where nb-char ::= c-printable - b-char - c-byte-order-mark.- return isPrintable(c) && c !== 0xFEFF- // - c-flow-indicator- && c !== CHAR_COMMA$2- && c !== CHAR_LEFT_SQUARE_BRACKET$2- && c !== CHAR_RIGHT_SQUARE_BRACKET$2- && c !== CHAR_LEFT_CURLY_BRACKET- && c !== CHAR_RIGHT_CURLY_BRACKET- // - ":" - "#"- // /* An ns-char preceding */ "#"- && c !== CHAR_COLON- && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));-}--// Simplified test for values allowed as the first character in plain style.-function isPlainSafeFirst(c) {- // Uses a subset of ns-char - c-indicator- // where ns-char = nb-char - s-white.- return isPrintable(c) && c !== 0xFEFF- && !isWhitespace(c) // - s-white- // - (c-indicator ::=- // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”- && c !== CHAR_MINUS- && c !== CHAR_QUESTION- && c !== CHAR_COLON- && c !== CHAR_COMMA$2- && c !== CHAR_LEFT_SQUARE_BRACKET$2- && c !== CHAR_RIGHT_SQUARE_BRACKET$2- && c !== CHAR_LEFT_CURLY_BRACKET- && c !== CHAR_RIGHT_CURLY_BRACKET- // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”- && c !== CHAR_SHARP- && c !== CHAR_AMPERSAND- && c !== CHAR_ASTERISK$1- && c !== CHAR_EXCLAMATION- && c !== CHAR_VERTICAL_LINE- && c !== CHAR_EQUALS- && c !== CHAR_GREATER_THAN- && c !== CHAR_SINGLE_QUOTE$1- && c !== CHAR_DOUBLE_QUOTE$1- // | “%” | “@” | “`”)- && c !== CHAR_PERCENT- && c !== CHAR_COMMERCIAL_AT- && c !== CHAR_GRAVE_ACCENT;-}--// Determines whether block indentation indicator is required.-function needIndentIndicator(string) {- var leadingSpaceRe = /^\n* /;- return leadingSpaceRe.test(string);-}--var STYLE_PLAIN = 1,- STYLE_SINGLE = 2,- STYLE_LITERAL = 3,- STYLE_FOLDED = 4,- STYLE_DOUBLE = 5;--// Determines which scalar styles are possible and returns the preferred style.-// lineWidth = -1 => no limit.-// Pre-conditions: str.length > 0.-// Post-conditions:-// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.-// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).-// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).-function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {- var i;- var char, prev_char;- var hasLineBreak = false;- var hasFoldableLine = false; // only checked if shouldTrackWidth- var shouldTrackWidth = lineWidth !== -1;- var previousLineBreak = -1; // count the first line correctly- var plain = isPlainSafeFirst(string.charCodeAt(0))- && !isWhitespace(string.charCodeAt(string.length - 1));-- if (singleLineOnly) {- // Case: no block styles.- // Check for disallowed characters to rule out plain and single.- for (i = 0; i < string.length; i++) {- char = string.charCodeAt(i);- if (!isPrintable(char)) {- return STYLE_DOUBLE;- }- prev_char = i > 0 ? string.charCodeAt(i - 1) : null;- plain = plain && isPlainSafe(char, prev_char);- }- } else {- // Case: block styles permitted.- for (i = 0; i < string.length; i++) {- char = string.charCodeAt(i);- if (char === CHAR_LINE_FEED) {- hasLineBreak = true;- // Check if any line can be folded.- if (shouldTrackWidth) {- hasFoldableLine = hasFoldableLine ||- // Foldable line = too long, and not more-indented.- (i - previousLineBreak - 1 > lineWidth &&- string[previousLineBreak + 1] !== ' ');- previousLineBreak = i;- }- } else if (!isPrintable(char)) {- return STYLE_DOUBLE;- }- prev_char = i > 0 ? string.charCodeAt(i - 1) : null;- plain = plain && isPlainSafe(char, prev_char);- }- // in case the end is missing a \n- hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&- (i - previousLineBreak - 1 > lineWidth &&- string[previousLineBreak + 1] !== ' '));- }- // Although every style can represent \n without escaping, prefer block styles- // for multiline, since they're more readable and they don't add empty lines.- // Also prefer folding a super-long line.- if (!hasLineBreak && !hasFoldableLine) {- // Strings interpretable as another type have to be quoted;- // e.g. the string 'true' vs. the boolean true.- return plain && !testAmbiguousType(string)- ? STYLE_PLAIN : STYLE_SINGLE;- }- // Edge case: block indentation indicator can only have one digit.- if (indentPerLevel > 9 && needIndentIndicator(string)) {- return STYLE_DOUBLE;- }- // At this point we know block styles are valid.- // Prefer literal style unless we want to fold.- return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;-}--// Note: line breaking/folding is implemented for only the folded style.-// NB. We drop the last trailing newline (if any) of a returned block scalar-// since the dumper adds its own newline. This always works:-// • No ending newline => unaffected; already using strip "-" chomping.-// • Ending newline => removed then restored.-// Importantly, this keeps the "+" chomp indicator from gaining an extra line.-function writeScalar(state, string, level, iskey) {- state.dump = (function () {- if (string.length === 0) {- return "''";- }- if (!state.noCompatMode &&- DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {- return "'" + string + "'";- }-- var indent = state.indent * Math.max(1, level); // no 0-indent scalars- // As indentation gets deeper, let the width decrease monotonically- // to the lower bound min(state.lineWidth, 40).- // Note that this implies- // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.- // state.lineWidth > 40 + state.indent: width decreases until the lower bound.- // This behaves better than a constant minimum width which disallows narrower options,- // or an indent threshold which causes the width to suddenly increase.- var lineWidth = state.lineWidth === -1- ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);-- // Without knowing if keys are implicit/explicit, assume implicit for safety.- var singleLineOnly = iskey- // No block styles in flow mode.- || (state.flowLevel > -1 && level >= state.flowLevel);- function testAmbiguity(string) {- return testImplicitResolving(state, string);- }-- switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {- case STYLE_PLAIN:- return string;- case STYLE_SINGLE:- return "'" + string.replace(/'/g, "''") + "'";- case STYLE_LITERAL:- return '|' + blockHeader(string, state.indent)- + dropEndingNewline(indentString$2(string, indent));- case STYLE_FOLDED:- return '>' + blockHeader(string, state.indent)- + dropEndingNewline(indentString$2(foldString(string, lineWidth), indent));- case STYLE_DOUBLE:- return '"' + escapeString(string) + '"';- default:- throw new exception('impossible error: invalid scalar style');- }- }());-}--// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.-function blockHeader(string, indentPerLevel) {- var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';-- // note the special case: the string '\n' counts as a "trailing" empty line.- var clip = string[string.length - 1] === '\n';- var keep = clip && (string[string.length - 2] === '\n' || string === '\n');- var chomp = keep ? '+' : (clip ? '' : '-');-- return indentIndicator + chomp + '\n';-}--// (See the note for writeScalar.)-function dropEndingNewline(string) {- return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;-}--// Note: a long line without a suitable break point will exceed the width limit.-// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.-function foldString(string, width) {- // In folded style, $k$ consecutive newlines output as $k+1$ newlines—- // unless they're before or after a more-indented line, or at the very- // beginning or end, in which case $k$ maps to $k$.- // Therefore, parse each chunk as newline(s) followed by a content line.- var lineRe = /(\n+)([^\n]*)/g;-- // first line (possibly an empty line)- var result = (function () {- var nextLF = string.indexOf('\n');- nextLF = nextLF !== -1 ? nextLF : string.length;- lineRe.lastIndex = nextLF;- return foldLine(string.slice(0, nextLF), width);- }());- // If we haven't reached the first content line yet, don't add an extra \n.- var prevMoreIndented = string[0] === '\n' || string[0] === ' ';- var moreIndented;-- // rest of the lines- var match;- while ((match = lineRe.exec(string))) {- var prefix = match[1], line = match[2];- moreIndented = (line[0] === ' ');- result += prefix- + (!prevMoreIndented && !moreIndented && line !== ''- ? '\n' : '')- + foldLine(line, width);- prevMoreIndented = moreIndented;- }-- return result;-}--// Greedy line breaking.-// Picks the longest line under the limit each time,-// otherwise settles for the shortest line over the limit.-// NB. More-indented lines *cannot* be folded, as that would add an extra \n.-function foldLine(line, width) {- if (line === '' || line[0] === ' ') return line;-- // Since a more-indented line adds a \n, breaks can't be followed by a space.- var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.- var match;- // start is an inclusive index. end, curr, and next are exclusive.- var start = 0, end, curr = 0, next = 0;- var result = '';-- // Invariants: 0 <= start <= length-1.- // 0 <= curr <= next <= max(0, length-2). curr - start <= width.- // Inside the loop:- // A match implies length >= 2, so curr and next are <= length-2.- while ((match = breakRe.exec(line))) {- next = match.index;- // maintain invariant: curr - start <= width- if (next - start > width) {- end = (curr > start) ? curr : next; // derive end <= length-2- result += '\n' + line.slice(start, end);- // skip the space that was output as \n- start = end + 1; // derive start <= length-1- }- curr = next;- }-- // By the invariants, start <= length-1, so there is something left over.- // It is either the whole string or a part starting from non-whitespace.- result += '\n';- // Insert a break if the remainder is too long and there is a break available.- if (line.length - start > width && curr > start) {- result += line.slice(start, curr) + '\n' + line.slice(curr + 1);- } else {- result += line.slice(start);- }-- return result.slice(1); // drop extra \n joiner-}--// Escapes a double-quoted string.-function escapeString(string) {- var result = '';- var char, nextChar;- var escapeSeq;-- for (var i = 0; i < string.length; i++) {- char = string.charCodeAt(i);- // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").- if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {- nextChar = string.charCodeAt(i + 1);- if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {- // Combine the surrogate pair and store it escaped.- result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);- // Advance index one extra since we already used that char here.- i++; continue;- }- }- escapeSeq = ESCAPE_SEQUENCES[char];- result += !escapeSeq && isPrintable(char)- ? string[i]- : escapeSeq || encodeHex(char);- }-- return result;-}--function writeFlowSequence(state, level, object) {- var _result = '',- _tag = state.tag,- index,- length;-- for (index = 0, length = object.length; index < length; index += 1) {- // Write only valid elements.- if (writeNode(state, level, object[index], false, false)) {- if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');- _result += state.dump;- }- }-- state.tag = _tag;- state.dump = '[' + _result + ']';-}--function writeBlockSequence(state, level, object, compact) {- var _result = '',- _tag = state.tag,- index,- length;-- for (index = 0, length = object.length; index < length; index += 1) {- // Write only valid elements.- if (writeNode(state, level + 1, object[index], true, true)) {- if (!compact || index !== 0) {- _result += generateNextLine(state, level);- }-- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {- _result += '-';- } else {- _result += '- ';- }-- _result += state.dump;- }- }-- state.tag = _tag;- state.dump = _result || '[]'; // Empty sequence if no valid values.-}--function writeFlowMapping(state, level, object) {- var _result = '',- _tag = state.tag,- objectKeyList = Object.keys(object),- index,- length,- objectKey,- objectValue,- pairBuffer;-- for (index = 0, length = objectKeyList.length; index < length; index += 1) {-- pairBuffer = '';- if (index !== 0) pairBuffer += ', ';-- if (state.condenseFlow) pairBuffer += '"';-- objectKey = objectKeyList[index];- objectValue = object[objectKey];-- if (!writeNode(state, level, objectKey, false, false)) {- continue; // Skip this pair because of invalid key;- }-- if (state.dump.length > 1024) pairBuffer += '? ';-- pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');-- if (!writeNode(state, level, objectValue, false, false)) {- continue; // Skip this pair because of invalid value.- }-- pairBuffer += state.dump;-- // Both key and value are valid.- _result += pairBuffer;- }-- state.tag = _tag;- state.dump = '{' + _result + '}';-}--function writeBlockMapping(state, level, object, compact) {- var _result = '',- _tag = state.tag,- objectKeyList = Object.keys(object),- index,- length,- objectKey,- objectValue,- explicitPair,- pairBuffer;-- // Allow sorting keys so that the output file is deterministic- if (state.sortKeys === true) {- // Default sorting- objectKeyList.sort();- } else if (typeof state.sortKeys === 'function') {- // Custom sort function- objectKeyList.sort(state.sortKeys);- } else if (state.sortKeys) {- // Something is wrong- throw new exception('sortKeys must be a boolean or a function');- }-- for (index = 0, length = objectKeyList.length; index < length; index += 1) {- pairBuffer = '';-- if (!compact || index !== 0) {- pairBuffer += generateNextLine(state, level);- }-- objectKey = objectKeyList[index];- objectValue = object[objectKey];-- if (!writeNode(state, level + 1, objectKey, true, true, true)) {- continue; // Skip this pair because of invalid key.- }-- explicitPair = (state.tag !== null && state.tag !== '?') ||- (state.dump && state.dump.length > 1024);-- if (explicitPair) {- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {- pairBuffer += '?';- } else {- pairBuffer += '? ';- }- }-- pairBuffer += state.dump;-- if (explicitPair) {- pairBuffer += generateNextLine(state, level);- }-- if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {- continue; // Skip this pair because of invalid value.- }-- if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {- pairBuffer += ':';- } else {- pairBuffer += ': ';- }-- pairBuffer += state.dump;-- // Both key and value are valid.- _result += pairBuffer;- }-- state.tag = _tag;- state.dump = _result || '{}'; // Empty mapping if no valid pairs.-}--function detectType(state, object, explicit) {- var _result, typeList, index, length, type, style;-- typeList = explicit ? state.explicitTypes : state.implicitTypes;-- for (index = 0, length = typeList.length; index < length; index += 1) {- type = typeList[index];-- if ((type.instanceOf || type.predicate) &&- (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&- (!type.predicate || type.predicate(object))) {-- state.tag = explicit ? type.tag : '?';-- if (type.represent) {- style = state.styleMap[type.tag] || type.defaultStyle;-- if (_toString$2.call(type.represent) === '[object Function]') {- _result = type.represent(object, style);- } else if (_hasOwnProperty$3.call(type.represent, style)) {- _result = type.represent[style](object, style);- } else {- throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');- }-- state.dump = _result;- }-- return true;- }- }-- return false;-}--// Serializes `object` and writes it to global `result`.-// Returns true on success, or false on invalid object.-//-function writeNode(state, level, object, block, compact, iskey) {- state.tag = null;- state.dump = object;-- if (!detectType(state, object, false)) {- detectType(state, object, true);- }-- var type = _toString$2.call(state.dump);-- if (block) {- block = (state.flowLevel < 0 || state.flowLevel > level);- }-- var objectOrArray = type === '[object Object]' || type === '[object Array]',- duplicateIndex,- duplicate;-- if (objectOrArray) {- duplicateIndex = state.duplicates.indexOf(object);- duplicate = duplicateIndex !== -1;- }-- if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {- compact = false;- }-- if (duplicate && state.usedDuplicates[duplicateIndex]) {- state.dump = '*ref_' + duplicateIndex;- } else {- if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {- state.usedDuplicates[duplicateIndex] = true;- }- if (type === '[object Object]') {- if (block && (Object.keys(state.dump).length !== 0)) {- writeBlockMapping(state, level, state.dump, compact);- if (duplicate) {- state.dump = '&ref_' + duplicateIndex + state.dump;- }- } else {- writeFlowMapping(state, level, state.dump);- if (duplicate) {- state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;- }- }- } else if (type === '[object Array]') {- var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;- if (block && (state.dump.length !== 0)) {- writeBlockSequence(state, arrayLevel, state.dump, compact);- if (duplicate) {- state.dump = '&ref_' + duplicateIndex + state.dump;- }- } else {- writeFlowSequence(state, arrayLevel, state.dump);- if (duplicate) {- state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;- }- }- } else if (type === '[object String]') {- if (state.tag !== '?') {- writeScalar(state, state.dump, level, iskey);- }- } else {- if (state.skipInvalid) return false;- throw new exception('unacceptable kind of an object to dump ' + type);- }-- if (state.tag !== null && state.tag !== '?') {- state.dump = '!<' + state.tag + '> ' + state.dump;- }- }-- return true;-}--function getDuplicateReferences(object, state) {- var objects = [],- duplicatesIndexes = [],- index,- length;-- inspectNode(object, objects, duplicatesIndexes);-- for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {- state.duplicates.push(objects[duplicatesIndexes[index]]);- }- state.usedDuplicates = new Array(length);-}--function inspectNode(object, objects, duplicatesIndexes) {- var objectKeyList,- index,- length;-- if (object !== null && typeof object === 'object') {- index = objects.indexOf(object);- if (index !== -1) {- if (duplicatesIndexes.indexOf(index) === -1) {- duplicatesIndexes.push(index);- }- } else {- objects.push(object);-- if (Array.isArray(object)) {- for (index = 0, length = object.length; index < length; index += 1) {- inspectNode(object[index], objects, duplicatesIndexes);- }- } else {- objectKeyList = Object.keys(object);-- for (index = 0, length = objectKeyList.length; index < length; index += 1) {- inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);- }- }- }- }-}--function dump(input, options) {- options = options || {};-- var state = new State$1(options);-- if (!state.noRefs) getDuplicateReferences(input, state);-- if (writeNode(state, 0, input, true, true)) return state.dump + '\n';-- return '';-}--function safeDump(input, options) {- return dump(input, common$1.extend({ schema: default_safe }, options));-}--var dump_1 = dump;-var safeDump_1 = safeDump;--var dumper = {- dump: dump_1,- safeDump: safeDump_1-};--function deprecated(name) {- return function () {- throw new Error('Function ' + name + ' is deprecated and cannot be used.');- };-}---var Type$1 = type;-var Schema$1 = schema;-var FAILSAFE_SCHEMA = failsafe;-var JSON_SCHEMA = json$1;-var CORE_SCHEMA = core;-var DEFAULT_SAFE_SCHEMA = default_safe;-var DEFAULT_FULL_SCHEMA = default_full;-var load$1 = loader.load;-var loadAll$1 = loader.loadAll;-var safeLoad$1 = loader.safeLoad;-var safeLoadAll$1 = loader.safeLoadAll;-var dump$1 = dumper.dump;-var safeDump$1 = dumper.safeDump;-var YAMLException$1 = exception;--// Deprecated schema names from JS-YAML 2.0.x-var MINIMAL_SCHEMA = failsafe;-var SAFE_SCHEMA = default_safe;-var DEFAULT_SCHEMA = default_full;--// Deprecated functions from JS-YAML 1.x.x-var scan$1 = deprecated('scan');-var parse$4 = deprecated('parse');-var compose = deprecated('compose');-var addConstructor = deprecated('addConstructor');--var jsYaml = {- Type: Type$1,- Schema: Schema$1,- FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,- JSON_SCHEMA: JSON_SCHEMA,- CORE_SCHEMA: CORE_SCHEMA,- DEFAULT_SAFE_SCHEMA: DEFAULT_SAFE_SCHEMA,- DEFAULT_FULL_SCHEMA: DEFAULT_FULL_SCHEMA,- load: load$1,- loadAll: loadAll$1,- safeLoad: safeLoad$1,- safeLoadAll: safeLoadAll$1,- dump: dump$1,- safeDump: safeDump$1,- YAMLException: YAMLException$1,- MINIMAL_SCHEMA: MINIMAL_SCHEMA,- SAFE_SCHEMA: SAFE_SCHEMA,- DEFAULT_SCHEMA: DEFAULT_SCHEMA,- scan: scan$1,- parse: parse$4,- compose: compose,- addConstructor: addConstructor-};--var jsYaml$1 = jsYaml;--function _extends() {- _extends = Object.assign || function (target) {- for (var i = 1; i < arguments.length; i++) {- var source = arguments[i];-- for (var key in source) {- if (Object.prototype.hasOwnProperty.call(source, key)) {- target[key] = source[key];- }- }- }-- return target;- };-- return _extends.apply(this, arguments);-}--function _defineProperties$5(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);- }-}--function _createClass$5(Constructor, protoProps, staticProps) {- if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);- if (staticProps) _defineProperties$5(Constructor, staticProps);- return Constructor;-}--/** Used for built-in method references. */-var objectProto = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$1 = objectProto.hasOwnProperty;--/**- * The base implementation of `_.has` without support for deep paths.- *- * @private- * @param {Object} [object] The object to query.- * @param {Array|string} key The key to check.- * @returns {boolean} Returns `true` if `key` exists, else `false`.- */-function baseHas(object, key) {- return object != null && hasOwnProperty$1.call(object, key);-}--/**- * Checks if `value` is classified as an `Array` object.- *- * @static- * @memberOf _- * @since 0.1.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is an array, else `false`.- * @example- *- * _.isArray([1, 2, 3]);- * // => true- *- * _.isArray(document.body.children);- * // => false- *- * _.isArray('abc');- * // => false- *- * _.isArray(_.noop);- * // => false- */-var isArray = Array.isArray;--/** Detect free variable `global` from Node.js. */-var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;--/** Detect free variable `self`. */-var freeSelf = typeof self == 'object' && self && self.Object === Object && self;--/** Used as a reference to the global object. */-var root$1 = freeGlobal || freeSelf || Function('return this')();--/** Built-in value references. */-var Symbol$1 = root$1.Symbol;--/** Used for built-in method references. */-var objectProto$1 = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$2 = objectProto$1.hasOwnProperty;--/**- * Used to resolve the- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)- * of values.- */-var nativeObjectToString = objectProto$1.toString;--/** Built-in value references. */-var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;--/**- * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.- *- * @private- * @param {*} value The value to query.- * @returns {string} Returns the raw `toStringTag`.- */-function getRawTag(value) {- var isOwn = hasOwnProperty$2.call(value, symToStringTag),- tag = value[symToStringTag];-- try {- value[symToStringTag] = undefined;- var unmasked = true;- } catch (e) {}-- var result = nativeObjectToString.call(value);- if (unmasked) {- if (isOwn) {- value[symToStringTag] = tag;- } else {- delete value[symToStringTag];- }- }- return result;-}--/** Used for built-in method references. */-var objectProto$2 = Object.prototype;--/**- * Used to resolve the- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)- * of values.- */-var nativeObjectToString$1 = objectProto$2.toString;--/**- * Converts `value` to a string using `Object.prototype.toString`.- *- * @private- * @param {*} value The value to convert.- * @returns {string} Returns the converted string.- */-function objectToString(value) {- return nativeObjectToString$1.call(value);-}--/** `Object#toString` result references. */-var nullTag = '[object Null]',- undefinedTag = '[object Undefined]';--/** Built-in value references. */-var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;--/**- * The base implementation of `getTag` without fallbacks for buggy environments.- *- * @private- * @param {*} value The value to query.- * @returns {string} Returns the `toStringTag`.- */-function baseGetTag(value) {- if (value == null) {- return value === undefined ? undefinedTag : nullTag;- }- return (symToStringTag$1 && symToStringTag$1 in Object(value))- ? getRawTag(value)- : objectToString(value);-}--/**- * Checks if `value` is object-like. A value is object-like if it's not `null`- * and has a `typeof` result of "object".- *- * @static- * @memberOf _- * @since 4.0.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.- * @example- *- * _.isObjectLike({});- * // => true- *- * _.isObjectLike([1, 2, 3]);- * // => true- *- * _.isObjectLike(_.noop);- * // => false- *- * _.isObjectLike(null);- * // => false- */-function isObjectLike$1(value) {- return value != null && typeof value == 'object';-}--/** `Object#toString` result references. */-var symbolTag = '[object Symbol]';--/**- * Checks if `value` is classified as a `Symbol` primitive or object.- *- * @static- * @memberOf _- * @since 4.0.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.- * @example- *- * _.isSymbol(Symbol.iterator);- * // => true- *- * _.isSymbol('abc');- * // => false- */-function isSymbol(value) {- return typeof value == 'symbol' ||- (isObjectLike$1(value) && baseGetTag(value) == symbolTag);-}--/** Used to match property names within property paths. */-var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,- reIsPlainProp = /^\w*$/;--/**- * Checks if `value` is a property name and not a property path.- *- * @private- * @param {*} value The value to check.- * @param {Object} [object] The object to query keys on.- * @returns {boolean} Returns `true` if `value` is a property name, else `false`.- */-function isKey(value, object) {- if (isArray(value)) {- return false;- }- var type = typeof value;- if (type == 'number' || type == 'symbol' || type == 'boolean' ||- value == null || isSymbol(value)) {- return true;- }- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||- (object != null && value in Object(object));-}--/**- * Checks if `value` is the- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)- *- * @static- * @memberOf _- * @since 0.1.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is an object, else `false`.- * @example- *- * _.isObject({});- * // => true- *- * _.isObject([1, 2, 3]);- * // => true- *- * _.isObject(_.noop);- * // => true- *- * _.isObject(null);- * // => false- */-function isObject$4(value) {- var type = typeof value;- return value != null && (type == 'object' || type == 'function');-}--/** `Object#toString` result references. */-var asyncTag = '[object AsyncFunction]',- funcTag = '[object Function]',- genTag = '[object GeneratorFunction]',- proxyTag = '[object Proxy]';--/**- * Checks if `value` is classified as a `Function` object.- *- * @static- * @memberOf _- * @since 0.1.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a function, else `false`.- * @example- *- * _.isFunction(_);- * // => true- *- * _.isFunction(/abc/);- * // => false- */-function isFunction$1(value) {- if (!isObject$4(value)) {- return false;- }- // The use of `Object#toString` avoids issues with the `typeof` operator- // in Safari 9 which returns 'object' for typed arrays and other constructors.- var tag = baseGetTag(value);- return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;-}--/** Used to detect overreaching core-js shims. */-var coreJsData = root$1['__core-js_shared__'];--/** Used to detect methods masquerading as native. */-var maskSrcKey = (function() {- var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');- return uid ? ('Symbol(src)_1.' + uid) : '';-}());--/**- * Checks if `func` has its source masked.- *- * @private- * @param {Function} func The function to check.- * @returns {boolean} Returns `true` if `func` is masked, else `false`.- */-function isMasked(func) {- return !!maskSrcKey && (maskSrcKey in func);-}--/** Used for built-in method references. */-var funcProto = Function.prototype;--/** Used to resolve the decompiled source of functions. */-var funcToString = funcProto.toString;--/**- * Converts `func` to its source code.- *- * @private- * @param {Function} func The function to convert.- * @returns {string} Returns the source code.- */-function toSource(func) {- if (func != null) {- try {- return funcToString.call(func);- } catch (e) {}- try {- return (func + '');- } catch (e) {}- }- return '';-}--/**- * Used to match `RegExp`- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).- */-var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;--/** Used to detect host constructors (Safari). */-var reIsHostCtor = /^\[object .+?Constructor\]$/;--/** Used for built-in method references. */-var funcProto$1 = Function.prototype,- objectProto$3 = Object.prototype;--/** Used to resolve the decompiled source of functions. */-var funcToString$1 = funcProto$1.toString;--/** Used to check objects for own properties. */-var hasOwnProperty$3 = objectProto$3.hasOwnProperty;--/** Used to detect if a method is native. */-var reIsNative = RegExp('^' +- funcToString$1.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&')- .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'-);--/**- * The base implementation of `_.isNative` without bad shim checks.- *- * @private- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a native function,- * else `false`.- */-function baseIsNative(value) {- if (!isObject$4(value) || isMasked(value)) {- return false;- }- var pattern = isFunction$1(value) ? reIsNative : reIsHostCtor;- return pattern.test(toSource(value));-}--/**- * Gets the value at `key` of `object`.- *- * @private- * @param {Object} [object] The object to query.- * @param {string} key The key of the property to get.- * @returns {*} Returns the property value.- */-function getValue(object, key) {- return object == null ? undefined : object[key];-}--/**- * Gets the native function at `key` of `object`.- *- * @private- * @param {Object} object The object to query.- * @param {string} key The key of the method to get.- * @returns {*} Returns the function if it's native, else `undefined`.- */-function getNative(object, key) {- var value = getValue(object, key);- return baseIsNative(value) ? value : undefined;-}--/* Built-in method references that are verified to be native. */-var nativeCreate = getNative(Object, 'create');--/**- * Removes all key-value entries from the hash.- *- * @private- * @name clear- * @memberOf Hash- */-function hashClear() {- this.__data__ = nativeCreate ? nativeCreate(null) : {};- this.size = 0;-}--/**- * Removes `key` and its value from the hash.- *- * @private- * @name delete- * @memberOf Hash- * @param {Object} hash The hash to modify.- * @param {string} key The key of the value to remove.- * @returns {boolean} Returns `true` if the entry was removed, else `false`.- */-function hashDelete(key) {- var result = this.has(key) && delete this.__data__[key];- this.size -= result ? 1 : 0;- return result;-}--/** Used to stand-in for `undefined` hash values. */-var HASH_UNDEFINED = '__lodash_hash_undefined__';--/** Used for built-in method references. */-var objectProto$4 = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$4 = objectProto$4.hasOwnProperty;--/**- * Gets the hash value for `key`.- *- * @private- * @name get- * @memberOf Hash- * @param {string} key The key of the value to get.- * @returns {*} Returns the entry value.- */-function hashGet(key) {- var data = this.__data__;- if (nativeCreate) {- var result = data[key];- return result === HASH_UNDEFINED ? undefined : result;- }- return hasOwnProperty$4.call(data, key) ? data[key] : undefined;-}--/** Used for built-in method references. */-var objectProto$5 = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$5 = objectProto$5.hasOwnProperty;--/**- * Checks if a hash value for `key` exists.- *- * @private- * @name has- * @memberOf Hash- * @param {string} key The key of the entry to check.- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.- */-function hashHas(key) {- var data = this.__data__;- return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$5.call(data, key);-}--/** Used to stand-in for `undefined` hash values. */-var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';--/**- * Sets the hash `key` to `value`.- *- * @private- * @name set- * @memberOf Hash- * @param {string} key The key of the value to set.- * @param {*} value The value to set.- * @returns {Object} Returns the hash instance.- */-function hashSet(key, value) {- var data = this.__data__;- this.size += this.has(key) ? 0 : 1;- data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;- return this;-}--/**- * Creates a hash object.- *- * @private- * @constructor- * @param {Array} [entries] The key-value pairs to cache.- */-function Hash(entries) {- var index = -1,- length = entries == null ? 0 : entries.length;-- this.clear();- while (++index < length) {- var entry = entries[index];- this.set(entry[0], entry[1]);- }-}--// Add methods to `Hash`.-Hash.prototype.clear = hashClear;-Hash.prototype['delete'] = hashDelete;-Hash.prototype.get = hashGet;-Hash.prototype.has = hashHas;-Hash.prototype.set = hashSet;--/**- * Removes all key-value entries from the list cache.- *- * @private- * @name clear- * @memberOf ListCache- */-function listCacheClear() {- this.__data__ = [];- this.size = 0;-}--/**- * Performs a- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)- * comparison between two values to determine if they are equivalent.- *- * @static- * @memberOf _- * @since 4.0.0- * @category Lang- * @param {*} value The value to compare.- * @param {*} other The other value to compare.- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.- * @example- *- * var object = { 'a': 1 };- * var other = { 'a': 1 };- *- * _.eq(object, object);- * // => true- *- * _.eq(object, other);- * // => false- *- * _.eq('a', 'a');- * // => true- *- * _.eq('a', Object('a'));- * // => false- *- * _.eq(NaN, NaN);- * // => true- */-function eq(value, other) {- return value === other || (value !== value && other !== other);-}--/**- * Gets the index at which the `key` is found in `array` of key-value pairs.- *- * @private- * @param {Array} array The array to inspect.- * @param {*} key The key to search for.- * @returns {number} Returns the index of the matched value, else `-1`.- */-function assocIndexOf(array, key) {- var length = array.length;- while (length--) {- if (eq(array[length][0], key)) {- return length;- }- }- return -1;-}--/** Used for built-in method references. */-var arrayProto = Array.prototype;--/** Built-in value references. */-var splice = arrayProto.splice;--/**- * Removes `key` and its value from the list cache.- *- * @private- * @name delete- * @memberOf ListCache- * @param {string} key The key of the value to remove.- * @returns {boolean} Returns `true` if the entry was removed, else `false`.- */-function listCacheDelete(key) {- var data = this.__data__,- index = assocIndexOf(data, key);-- if (index < 0) {- return false;- }- var lastIndex = data.length - 1;- if (index == lastIndex) {- data.pop();- } else {- splice.call(data, index, 1);- }- --this.size;- return true;-}--/**- * Gets the list cache value for `key`.- *- * @private- * @name get- * @memberOf ListCache- * @param {string} key The key of the value to get.- * @returns {*} Returns the entry value.- */-function listCacheGet(key) {- var data = this.__data__,- index = assocIndexOf(data, key);-- return index < 0 ? undefined : data[index][1];-}--/**- * Checks if a list cache value for `key` exists.- *- * @private- * @name has- * @memberOf ListCache- * @param {string} key The key of the entry to check.- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.- */-function listCacheHas(key) {- return assocIndexOf(this.__data__, key) > -1;-}--/**- * Sets the list cache `key` to `value`.- *- * @private- * @name set- * @memberOf ListCache- * @param {string} key The key of the value to set.- * @param {*} value The value to set.- * @returns {Object} Returns the list cache instance.- */-function listCacheSet(key, value) {- var data = this.__data__,- index = assocIndexOf(data, key);-- if (index < 0) {- ++this.size;- data.push([key, value]);- } else {- data[index][1] = value;- }- return this;-}--/**- * Creates an list cache object.- *- * @private- * @constructor- * @param {Array} [entries] The key-value pairs to cache.- */-function ListCache(entries) {- var index = -1,- length = entries == null ? 0 : entries.length;-- this.clear();- while (++index < length) {- var entry = entries[index];- this.set(entry[0], entry[1]);- }-}--// Add methods to `ListCache`.-ListCache.prototype.clear = listCacheClear;-ListCache.prototype['delete'] = listCacheDelete;-ListCache.prototype.get = listCacheGet;-ListCache.prototype.has = listCacheHas;-ListCache.prototype.set = listCacheSet;--/* Built-in method references that are verified to be native. */-var Map$1 = getNative(root$1, 'Map');--/**- * Removes all key-value entries from the map.- *- * @private- * @name clear- * @memberOf MapCache- */-function mapCacheClear() {- this.size = 0;- this.__data__ = {- 'hash': new Hash,- 'map': new (Map$1 || ListCache),- 'string': new Hash- };-}--/**- * Checks if `value` is suitable for use as unique object key.- *- * @private- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is suitable, else `false`.- */-function isKeyable(value) {- var type = typeof value;- return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')- ? (value !== '__proto__')- : (value === null);-}--/**- * Gets the data for `map`.- *- * @private- * @param {Object} map The map to query.- * @param {string} key The reference key.- * @returns {*} Returns the map data.- */-function getMapData(map, key) {- var data = map.__data__;- return isKeyable(key)- ? data[typeof key == 'string' ? 'string' : 'hash']- : data.map;-}--/**- * Removes `key` and its value from the map.- *- * @private- * @name delete- * @memberOf MapCache- * @param {string} key The key of the value to remove.- * @returns {boolean} Returns `true` if the entry was removed, else `false`.- */-function mapCacheDelete(key) {- var result = getMapData(this, key)['delete'](key);- this.size -= result ? 1 : 0;- return result;-}--/**- * Gets the map value for `key`.- *- * @private- * @name get- * @memberOf MapCache- * @param {string} key The key of the value to get.- * @returns {*} Returns the entry value.- */-function mapCacheGet(key) {- return getMapData(this, key).get(key);-}--/**- * Checks if a map value for `key` exists.- *- * @private- * @name has- * @memberOf MapCache- * @param {string} key The key of the entry to check.- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.- */-function mapCacheHas(key) {- return getMapData(this, key).has(key);-}--/**- * Sets the map `key` to `value`.- *- * @private- * @name set- * @memberOf MapCache- * @param {string} key The key of the value to set.- * @param {*} value The value to set.- * @returns {Object} Returns the map cache instance.- */-function mapCacheSet(key, value) {- var data = getMapData(this, key),- size = data.size;-- data.set(key, value);- this.size += data.size == size ? 0 : 1;- return this;-}--/**- * Creates a map cache object to store key-value pairs.- *- * @private- * @constructor- * @param {Array} [entries] The key-value pairs to cache.- */-function MapCache(entries) {- var index = -1,- length = entries == null ? 0 : entries.length;-- this.clear();- while (++index < length) {- var entry = entries[index];- this.set(entry[0], entry[1]);- }-}--// Add methods to `MapCache`.-MapCache.prototype.clear = mapCacheClear;-MapCache.prototype['delete'] = mapCacheDelete;-MapCache.prototype.get = mapCacheGet;-MapCache.prototype.has = mapCacheHas;-MapCache.prototype.set = mapCacheSet;--/** Error message constants. */-var FUNC_ERROR_TEXT = 'Expected a function';--/**- * Creates a function that memoizes the result of `func`. If `resolver` is- * provided, it determines the cache key for storing the result based on the- * arguments provided to the memoized function. By default, the first argument- * provided to the memoized function is used as the map cache key. The `func`- * is invoked with the `this` binding of the memoized function.- *- * **Note:** The cache is exposed as the `cache` property on the memoized- * function. Its creation may be customized by replacing the `_.memoize.Cache`- * constructor with one whose instances implement the- * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)- * method interface of `clear`, `delete`, `get`, `has`, and `set`.- *- * @static- * @memberOf _- * @since 0.1.0- * @category Function- * @param {Function} func The function to have its output memoized.- * @param {Function} [resolver] The function to resolve the cache key.- * @returns {Function} Returns the new memoized function.- * @example- *- * var object = { 'a': 1, 'b': 2 };- * var other = { 'c': 3, 'd': 4 };- *- * var values = _.memoize(_.values);- * values(object);- * // => [1, 2]- *- * values(other);- * // => [3, 4]- *- * object.a = 2;- * values(object);- * // => [1, 2]- *- * // Modify the result cache.- * values.cache.set(object, ['a', 'b']);- * values(object);- * // => ['a', 'b']- *- * // Replace `_.memoize.Cache`.- * _.memoize.Cache = WeakMap;- */-function memoize(func, resolver) {- if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {- throw new TypeError(FUNC_ERROR_TEXT);- }- var memoized = function() {- var args = arguments,- key = resolver ? resolver.apply(this, args) : args[0],- cache = memoized.cache;-- if (cache.has(key)) {- return cache.get(key);- }- var result = func.apply(this, args);- memoized.cache = cache.set(key, result) || cache;- return result;- };- memoized.cache = new (memoize.Cache || MapCache);- return memoized;-}--// Expose `MapCache`.-memoize.Cache = MapCache;--/** Used as the maximum memoize cache size. */-var MAX_MEMOIZE_SIZE = 500;--/**- * A specialized version of `_.memoize` which clears the memoized function's- * cache when it exceeds `MAX_MEMOIZE_SIZE`.- *- * @private- * @param {Function} func The function to have its output memoized.- * @returns {Function} Returns the new memoized function.- */-function memoizeCapped(func) {- var result = memoize(func, function(key) {- if (cache.size === MAX_MEMOIZE_SIZE) {- cache.clear();- }- return key;- });-- var cache = result.cache;- return result;-}--/** Used to match property names within property paths. */-var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;--/** Used to match backslashes in property paths. */-var reEscapeChar = /\\(\\)?/g;--/**- * Converts `string` to a property path array.- *- * @private- * @param {string} string The string to convert.- * @returns {Array} Returns the property path array.- */-var stringToPath = memoizeCapped(function(string) {- var result = [];- if (string.charCodeAt(0) === 46 /* . */) {- result.push('');- }- string.replace(rePropName, function(match, number, quote, subString) {- result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));- });- return result;-});--/**- * A specialized version of `_.map` for arrays without support for iteratee- * shorthands.- *- * @private- * @param {Array} [array] The array to iterate over.- * @param {Function} iteratee The function invoked per iteration.- * @returns {Array} Returns the new mapped array.- */-function arrayMap(array, iteratee) {- var index = -1,- length = array == null ? 0 : array.length,- result = Array(length);-- while (++index < length) {- result[index] = iteratee(array[index], index, array);- }- return result;-}--/** Used as references for various `Number` constants. */-var INFINITY = 1 / 0;--/** Used to convert symbols to primitives and strings. */-var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,- symbolToString = symbolProto ? symbolProto.toString : undefined;--/**- * The base implementation of `_.toString` which doesn't convert nullish- * values to empty strings.- *- * @private- * @param {*} value The value to process.- * @returns {string} Returns the string.- */-function baseToString(value) {- // Exit early for strings to avoid a performance hit in some environments.- if (typeof value == 'string') {- return value;- }- if (isArray(value)) {- // Recursively convert values (susceptible to call stack limits).- return arrayMap(value, baseToString) + '';- }- if (isSymbol(value)) {- return symbolToString ? symbolToString.call(value) : '';- }- var result = (value + '');- return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;-}--/**- * Converts `value` to a string. An empty string is returned for `null`- * and `undefined` values. The sign of `-0` is preserved.- *- * @static- * @memberOf _- * @since 4.0.0- * @category Lang- * @param {*} value The value to convert.- * @returns {string} Returns the converted string.- * @example- *- * _.toString(null);- * // => ''- *- * _.toString(-0);- * // => '-0'- *- * _.toString([1, 2, 3]);- * // => '1,2,3'- */-function toString(value) {- return value == null ? '' : baseToString(value);-}--/**- * Casts `value` to a path array if it's not one.- *- * @private- * @param {*} value The value to inspect.- * @param {Object} [object] The object to query keys on.- * @returns {Array} Returns the cast property path array.- */-function castPath(value, object) {- if (isArray(value)) {- return value;- }- return isKey(value, object) ? [value] : stringToPath(toString(value));-}--/** `Object#toString` result references. */-var argsTag = '[object Arguments]';--/**- * The base implementation of `_.isArguments`.- *- * @private- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is an `arguments` object,- */-function baseIsArguments(value) {- return isObjectLike$1(value) && baseGetTag(value) == argsTag;-}--/** Used for built-in method references. */-var objectProto$6 = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$6 = objectProto$6.hasOwnProperty;--/** Built-in value references. */-var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;--/**- * Checks if `value` is likely an `arguments` object.- *- * @static- * @memberOf _- * @since 0.1.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is an `arguments` object,- * else `false`.- * @example- *- * _.isArguments(function() { return arguments; }());- * // => true- *- * _.isArguments([1, 2, 3]);- * // => false- */-var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {- return isObjectLike$1(value) && hasOwnProperty$6.call(value, 'callee') &&- !propertyIsEnumerable.call(value, 'callee');-};--/** Used as references for various `Number` constants. */-var MAX_SAFE_INTEGER = 9007199254740991;--/** Used to detect unsigned integer values. */-var reIsUint = /^(?:0|[1-9]\d*)$/;--/**- * Checks if `value` is a valid array-like index.- *- * @private- * @param {*} value The value to check.- * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.- * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.- */-function isIndex(value, length) {- var type = typeof value;- length = length == null ? MAX_SAFE_INTEGER : length;-- return !!length &&- (type == 'number' ||- (type != 'symbol' && reIsUint.test(value))) &&- (value > -1 && value % 1 == 0 && value < length);-}--/** Used as references for various `Number` constants. */-var MAX_SAFE_INTEGER$1 = 9007199254740991;--/**- * Checks if `value` is a valid array-like length.- *- * **Note:** This method is loosely based on- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).- *- * @static- * @memberOf _- * @since 4.0.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.- * @example- *- * _.isLength(3);- * // => true- *- * _.isLength(Number.MIN_VALUE);- * // => false- *- * _.isLength(Infinity);- * // => false- *- * _.isLength('3');- * // => false- */-function isLength(value) {- return typeof value == 'number' &&- value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;-}--/** Used as references for various `Number` constants. */-var INFINITY$1 = 1 / 0;--/**- * Converts `value` to a string key if it's not a string or symbol.- *- * @private- * @param {*} value The value to inspect.- * @returns {string|symbol} Returns the key.- */-function toKey(value) {- if (typeof value == 'string' || isSymbol(value)) {- return value;- }- var result = (value + '');- return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;-}--/**- * Checks if `path` exists on `object`.- *- * @private- * @param {Object} object The object to query.- * @param {Array|string} path The path to check.- * @param {Function} hasFunc The function to check properties.- * @returns {boolean} Returns `true` if `path` exists, else `false`.- */-function hasPath(object, path, hasFunc) {- path = castPath(path, object);-- var index = -1,- length = path.length,- result = false;-- while (++index < length) {- var key = toKey(path[index]);- if (!(result = object != null && hasFunc(object, key))) {- break;- }- object = object[key];- }- if (result || ++index != length) {- return result;- }- length = object == null ? 0 : object.length;- return !!length && isLength(length) && isIndex(key, length) &&- (isArray(object) || isArguments(object));-}--/**- * Checks if `path` is a direct property of `object`.- *- * @static- * @since 0.1.0- * @memberOf _- * @category Object- * @param {Object} object The object to query.- * @param {Array|string} path The path to check.- * @returns {boolean} Returns `true` if `path` exists, else `false`.- * @example- *- * var object = { 'a': { 'b': 2 } };- * var other = _.create({ 'a': _.create({ 'b': 2 }) });- *- * _.has(object, 'a');- * // => true- *- * _.has(object, 'a.b');- * // => true- *- * _.has(object, ['a', 'b']);- * // => true- *- * _.has(other, 'a');- * // => false- */-function has(object, path) {- return object != null && hasPath(object, path, baseHas);-}--/**- * Removes all key-value entries from the stack.- *- * @private- * @name clear- * @memberOf Stack- */-function stackClear() {- this.__data__ = new ListCache;- this.size = 0;-}--/**- * Removes `key` and its value from the stack.- *- * @private- * @name delete- * @memberOf Stack- * @param {string} key The key of the value to remove.- * @returns {boolean} Returns `true` if the entry was removed, else `false`.- */-function stackDelete(key) {- var data = this.__data__,- result = data['delete'](key);-- this.size = data.size;- return result;-}--/**- * Gets the stack value for `key`.- *- * @private- * @name get- * @memberOf Stack- * @param {string} key The key of the value to get.- * @returns {*} Returns the entry value.- */-function stackGet(key) {- return this.__data__.get(key);-}--/**- * Checks if a stack value for `key` exists.- *- * @private- * @name has- * @memberOf Stack- * @param {string} key The key of the entry to check.- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.- */-function stackHas(key) {- return this.__data__.has(key);-}--/** Used as the size to enable large array optimizations. */-var LARGE_ARRAY_SIZE = 200;--/**- * Sets the stack `key` to `value`.- *- * @private- * @name set- * @memberOf Stack- * @param {string} key The key of the value to set.- * @param {*} value The value to set.- * @returns {Object} Returns the stack cache instance.- */-function stackSet(key, value) {- var data = this.__data__;- if (data instanceof ListCache) {- var pairs = data.__data__;- if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) {- pairs.push([key, value]);- this.size = ++data.size;- return this;- }- data = this.__data__ = new MapCache(pairs);- }- data.set(key, value);- this.size = data.size;- return this;-}--/**- * Creates a stack cache object to store key-value pairs.- *- * @private- * @constructor- * @param {Array} [entries] The key-value pairs to cache.- */-function Stack(entries) {- var data = this.__data__ = new ListCache(entries);- this.size = data.size;-}--// Add methods to `Stack`.-Stack.prototype.clear = stackClear;-Stack.prototype['delete'] = stackDelete;-Stack.prototype.get = stackGet;-Stack.prototype.has = stackHas;-Stack.prototype.set = stackSet;--/**- * A specialized version of `_.forEach` for arrays without support for- * iteratee shorthands.- *- * @private- * @param {Array} [array] The array to iterate over.- * @param {Function} iteratee The function invoked per iteration.- * @returns {Array} Returns `array`.- */-function arrayEach(array, iteratee) {- var index = -1,- length = array == null ? 0 : array.length;-- while (++index < length) {- if (iteratee(array[index], index, array) === false) {- break;- }- }- return array;-}--var defineProperty = (function() {- try {- var func = getNative(Object, 'defineProperty');- func({}, '', {});- return func;- } catch (e) {}-}());--/**- * The base implementation of `assignValue` and `assignMergeValue` without- * value checks.- *- * @private- * @param {Object} object The object to modify.- * @param {string} key The key of the property to assign.- * @param {*} value The value to assign.- */-function baseAssignValue(object, key, value) {- if (key == '__proto__' && defineProperty) {- defineProperty(object, key, {- 'configurable': true,- 'enumerable': true,- 'value': value,- 'writable': true- });- } else {- object[key] = value;- }-}--/** Used for built-in method references. */-var objectProto$7 = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$7 = objectProto$7.hasOwnProperty;--/**- * Assigns `value` to `key` of `object` if the existing value is not equivalent- * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)- * for equality comparisons.- *- * @private- * @param {Object} object The object to modify.- * @param {string} key The key of the property to assign.- * @param {*} value The value to assign.- */-function assignValue(object, key, value) {- var objValue = object[key];- if (!(hasOwnProperty$7.call(object, key) && eq(objValue, value)) ||- (value === undefined && !(key in object))) {- baseAssignValue(object, key, value);- }-}--/**- * Copies properties of `source` to `object`.- *- * @private- * @param {Object} source The object to copy properties from.- * @param {Array} props The property identifiers to copy.- * @param {Object} [object={}] The object to copy properties to.- * @param {Function} [customizer] The function to customize copied values.- * @returns {Object} Returns `object`.- */-function copyObject(source, props, object, customizer) {- var isNew = !object;- object || (object = {});-- var index = -1,- length = props.length;-- while (++index < length) {- var key = props[index];-- var newValue = customizer- ? customizer(object[key], source[key], key, object, source)- : undefined;-- if (newValue === undefined) {- newValue = source[key];- }- if (isNew) {- baseAssignValue(object, key, newValue);- } else {- assignValue(object, key, newValue);- }- }- return object;-}--/**- * The base implementation of `_.times` without support for iteratee shorthands- * or max array length checks.- *- * @private- * @param {number} n The number of times to invoke `iteratee`.- * @param {Function} iteratee The function invoked per iteration.- * @returns {Array} Returns the array of results.- */-function baseTimes(n, iteratee) {- var index = -1,- result = Array(n);-- while (++index < n) {- result[index] = iteratee(index);- }- return result;-}--/**- * This method returns `false`.- *- * @static- * @memberOf _- * @since 4.13.0- * @category Util- * @returns {boolean} Returns `false`.- * @example- *- * _.times(2, _.stubFalse);- * // => [false, false]- */-function stubFalse() {- return false;-}--/** Detect free variable `exports`. */-var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;--/** Detect free variable `module`. */-var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;--/** Detect the popular CommonJS extension `module.exports`. */-var moduleExports = freeModule && freeModule.exports === freeExports;--/** Built-in value references. */-var Buffer$1 = moduleExports ? root$1.Buffer : undefined;--/* Built-in method references for those with the same name as other `lodash` methods. */-var nativeIsBuffer = Buffer$1 ? Buffer$1.isBuffer : undefined;--/**- * Checks if `value` is a buffer.- *- * @static- * @memberOf _- * @since 4.3.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.- * @example- *- * _.isBuffer(new Buffer(2));- * // => true- *- * _.isBuffer(new Uint8Array(2));- * // => false- */-var isBuffer = nativeIsBuffer || stubFalse;--/** `Object#toString` result references. */-var argsTag$1 = '[object Arguments]',- arrayTag = '[object Array]',- boolTag = '[object Boolean]',- dateTag = '[object Date]',- errorTag = '[object Error]',- funcTag$1 = '[object Function]',- mapTag = '[object Map]',- numberTag = '[object Number]',- objectTag = '[object Object]',- regexpTag = '[object RegExp]',- setTag = '[object Set]',- stringTag = '[object String]',- weakMapTag = '[object WeakMap]';--var arrayBufferTag = '[object ArrayBuffer]',- dataViewTag = '[object DataView]',- float32Tag = '[object Float32Array]',- float64Tag = '[object Float64Array]',- int8Tag = '[object Int8Array]',- int16Tag = '[object Int16Array]',- int32Tag = '[object Int32Array]',- uint8Tag = '[object Uint8Array]',- uint8ClampedTag = '[object Uint8ClampedArray]',- uint16Tag = '[object Uint16Array]',- uint32Tag = '[object Uint32Array]';--/** Used to identify `toStringTag` values of typed arrays. */-var typedArrayTags = {};-typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =-typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =-typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =-typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =-typedArrayTags[uint32Tag] = true;-typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =-typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =-typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =-typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =-typedArrayTags[mapTag] = typedArrayTags[numberTag] =-typedArrayTags[objectTag] = typedArrayTags[regexpTag] =-typedArrayTags[setTag] = typedArrayTags[stringTag] =-typedArrayTags[weakMapTag] = false;--/**- * The base implementation of `_.isTypedArray` without Node.js optimizations.- *- * @private- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.- */-function baseIsTypedArray(value) {- return isObjectLike$1(value) &&- isLength(value.length) && !!typedArrayTags[baseGetTag(value)];-}--/**- * The base implementation of `_.unary` without support for storing metadata.- *- * @private- * @param {Function} func The function to cap arguments for.- * @returns {Function} Returns the new capped function.- */-function baseUnary(func) {- return function(value) {- return func(value);- };-}--/** Detect free variable `exports`. */-var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;--/** Detect free variable `module`. */-var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;--/** Detect the popular CommonJS extension `module.exports`. */-var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;--/** Detect free variable `process` from Node.js. */-var freeProcess = moduleExports$1 && freeGlobal.process;--/** Used to access faster Node.js helpers. */-var nodeUtil = (function() {- try {- // Use `util.types` for Node.js 10+.- var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;-- if (types) {- return types;- }-- // Legacy `process.binding('util')` for Node.js < 10.- return freeProcess && freeProcess.binding && freeProcess.binding('util');- } catch (e) {}-}());--/* Node.js helper references. */-var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;--/**- * Checks if `value` is classified as a typed array.- *- * @static- * @memberOf _- * @since 3.0.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.- * @example- *- * _.isTypedArray(new Uint8Array);- * // => true- *- * _.isTypedArray([]);- * // => false- */-var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;--/** Used for built-in method references. */-var objectProto$8 = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$8 = objectProto$8.hasOwnProperty;--/**- * Creates an array of the enumerable property names of the array-like `value`.- *- * @private- * @param {*} value The value to query.- * @param {boolean} inherited Specify returning inherited property names.- * @returns {Array} Returns the array of property names.- */-function arrayLikeKeys(value, inherited) {- var isArr = isArray(value),- isArg = !isArr && isArguments(value),- isBuff = !isArr && !isArg && isBuffer(value),- isType = !isArr && !isArg && !isBuff && isTypedArray(value),- skipIndexes = isArr || isArg || isBuff || isType,- result = skipIndexes ? baseTimes(value.length, String) : [],- length = result.length;-- for (var key in value) {- if ((inherited || hasOwnProperty$8.call(value, key)) &&- !(skipIndexes && (- // Safari 9 has enumerable `arguments.length` in strict mode.- key == 'length' ||- // Node.js 0.10 has enumerable non-index properties on buffers.- (isBuff && (key == 'offset' || key == 'parent')) ||- // PhantomJS 2 has enumerable non-index properties on typed arrays.- (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||- // Skip index properties.- isIndex(key, length)- ))) {- result.push(key);- }- }- return result;-}--/** Used for built-in method references. */-var objectProto$9 = Object.prototype;--/**- * Checks if `value` is likely a prototype object.- *- * @private- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.- */-function isPrototype(value) {- var Ctor = value && value.constructor,- proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9;-- return value === proto;-}--/**- * Creates a unary function that invokes `func` with its argument transformed.- *- * @private- * @param {Function} func The function to wrap.- * @param {Function} transform The argument transform.- * @returns {Function} Returns the new function.- */-function overArg(func, transform) {- return function(arg) {- return func(transform(arg));- };-}--/* Built-in method references for those with the same name as other `lodash` methods. */-var nativeKeys = overArg(Object.keys, Object);--/** Used for built-in method references. */-var objectProto$a = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$9 = objectProto$a.hasOwnProperty;--/**- * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.- *- * @private- * @param {Object} object The object to query.- * @returns {Array} Returns the array of property names.- */-function baseKeys(object) {- if (!isPrototype(object)) {- return nativeKeys(object);- }- var result = [];- for (var key in Object(object)) {- if (hasOwnProperty$9.call(object, key) && key != 'constructor') {- result.push(key);- }- }- return result;-}--/**- * Checks if `value` is array-like. A value is considered array-like if it's- * not a function and has a `value.length` that's an integer greater than or- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.- *- * @static- * @memberOf _- * @since 4.0.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.- * @example- *- * _.isArrayLike([1, 2, 3]);- * // => true- *- * _.isArrayLike(document.body.children);- * // => true- *- * _.isArrayLike('abc');- * // => true- *- * _.isArrayLike(_.noop);- * // => false- */-function isArrayLike$1(value) {- return value != null && isLength(value.length) && !isFunction$1(value);-}--/**- * Creates an array of the own enumerable property names of `object`.- *- * **Note:** Non-object values are coerced to objects. See the- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)- * for more details.- *- * @static- * @since 0.1.0- * @memberOf _- * @category Object- * @param {Object} object The object to query.- * @returns {Array} Returns the array of property names.- * @example- *- * function Foo() {- * this.a = 1;- * this.b = 2;- * }- *- * Foo.prototype.c = 3;- *- * _.keys(new Foo);- * // => ['a', 'b'] (iteration order is not guaranteed)- *- * _.keys('hi');- * // => ['0', '1']- */-function keys(object) {- return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys(object);-}--/**- * The base implementation of `_.assign` without support for multiple sources- * or `customizer` functions.- *- * @private- * @param {Object} object The destination object.- * @param {Object} source The source object.- * @returns {Object} Returns `object`.- */-function baseAssign(object, source) {- return object && copyObject(source, keys(source), object);-}--/**- * This function is like- * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)- * except that it includes inherited enumerable properties.- *- * @private- * @param {Object} object The object to query.- * @returns {Array} Returns the array of property names.- */-function nativeKeysIn(object) {- var result = [];- if (object != null) {- for (var key in Object(object)) {- result.push(key);- }- }- return result;-}--/** Used for built-in method references. */-var objectProto$b = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$a = objectProto$b.hasOwnProperty;--/**- * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.- *- * @private- * @param {Object} object The object to query.- * @returns {Array} Returns the array of property names.- */-function baseKeysIn(object) {- if (!isObject$4(object)) {- return nativeKeysIn(object);- }- var isProto = isPrototype(object),- result = [];-- for (var key in object) {- if (!(key == 'constructor' && (isProto || !hasOwnProperty$a.call(object, key)))) {- result.push(key);- }- }- return result;-}--/**- * Creates an array of the own and inherited enumerable property names of `object`.- *- * **Note:** Non-object values are coerced to objects.- *- * @static- * @memberOf _- * @since 3.0.0- * @category Object- * @param {Object} object The object to query.- * @returns {Array} Returns the array of property names.- * @example- *- * function Foo() {- * this.a = 1;- * this.b = 2;- * }- *- * Foo.prototype.c = 3;- *- * _.keysIn(new Foo);- * // => ['a', 'b', 'c'] (iteration order is not guaranteed)- */-function keysIn$1(object) {- return isArrayLike$1(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);-}--/**- * The base implementation of `_.assignIn` without support for multiple sources- * or `customizer` functions.- *- * @private- * @param {Object} object The destination object.- * @param {Object} source The source object.- * @returns {Object} Returns `object`.- */-function baseAssignIn(object, source) {- return object && copyObject(source, keysIn$1(source), object);-}--/** Detect free variable `exports`. */-var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports;--/** Detect free variable `module`. */-var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module;--/** Detect the popular CommonJS extension `module.exports`. */-var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2;--/** Built-in value references. */-var Buffer$2 = moduleExports$2 ? root$1.Buffer : undefined,- allocUnsafe = Buffer$2 ? Buffer$2.allocUnsafe : undefined;--/**- * Creates a clone of `buffer`.- *- * @private- * @param {Buffer} buffer The buffer to clone.- * @param {boolean} [isDeep] Specify a deep clone.- * @returns {Buffer} Returns the cloned buffer.- */-function cloneBuffer(buffer, isDeep) {- if (isDeep) {- return buffer.slice();- }- var length = buffer.length,- result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);-- buffer.copy(result);- return result;-}--/**- * Copies the values of `source` to `array`.- *- * @private- * @param {Array} source The array to copy values from.- * @param {Array} [array=[]] The array to copy values to.- * @returns {Array} Returns `array`.- */-function copyArray(source, array) {- var index = -1,- length = source.length;-- array || (array = Array(length));- while (++index < length) {- array[index] = source[index];- }- return array;-}--/**- * A specialized version of `_.filter` for arrays without support for- * iteratee shorthands.- *- * @private- * @param {Array} [array] The array to iterate over.- * @param {Function} predicate The function invoked per iteration.- * @returns {Array} Returns the new filtered array.- */-function arrayFilter(array, predicate) {- var index = -1,- length = array == null ? 0 : array.length,- resIndex = 0,- result = [];-- while (++index < length) {- var value = array[index];- if (predicate(value, index, array)) {- result[resIndex++] = value;- }- }- return result;-}--/**- * This method returns a new empty array.- *- * @static- * @memberOf _- * @since 4.13.0- * @category Util- * @returns {Array} Returns the new empty array.- * @example- *- * var arrays = _.times(2, _.stubArray);- *- * console.log(arrays);- * // => [[], []]- *- * console.log(arrays[0] === arrays[1]);- * // => false- */-function stubArray() {- return [];-}--/** Used for built-in method references. */-var objectProto$c = Object.prototype;--/** Built-in value references. */-var propertyIsEnumerable$1 = objectProto$c.propertyIsEnumerable;--/* Built-in method references for those with the same name as other `lodash` methods. */-var nativeGetSymbols = Object.getOwnPropertySymbols;--/**- * Creates an array of the own enumerable symbols of `object`.- *- * @private- * @param {Object} object The object to query.- * @returns {Array} Returns the array of symbols.- */-var getSymbols = !nativeGetSymbols ? stubArray : function(object) {- if (object == null) {- return [];- }- object = Object(object);- return arrayFilter(nativeGetSymbols(object), function(symbol) {- return propertyIsEnumerable$1.call(object, symbol);- });-};--/**- * Copies own symbols of `source` to `object`.- *- * @private- * @param {Object} source The object to copy symbols from.- * @param {Object} [object={}] The object to copy symbols to.- * @returns {Object} Returns `object`.- */-function copySymbols(source, object) {- return copyObject(source, getSymbols(source), object);-}--/**- * Appends the elements of `values` to `array`.- *- * @private- * @param {Array} array The array to modify.- * @param {Array} values The values to append.- * @returns {Array} Returns `array`.- */-function arrayPush(array, values) {- var index = -1,- length = values.length,- offset = array.length;-- while (++index < length) {- array[offset + index] = values[index];- }- return array;-}--/** Built-in value references. */-var getPrototype = overArg(Object.getPrototypeOf, Object);--/* Built-in method references for those with the same name as other `lodash` methods. */-var nativeGetSymbols$1 = Object.getOwnPropertySymbols;--/**- * Creates an array of the own and inherited enumerable symbols of `object`.- *- * @private- * @param {Object} object The object to query.- * @returns {Array} Returns the array of symbols.- */-var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) {- var result = [];- while (object) {- arrayPush(result, getSymbols(object));- object = getPrototype(object);- }- return result;-};--/**- * Copies own and inherited symbols of `source` to `object`.- *- * @private- * @param {Object} source The object to copy symbols from.- * @param {Object} [object={}] The object to copy symbols to.- * @returns {Object} Returns `object`.- */-function copySymbolsIn(source, object) {- return copyObject(source, getSymbolsIn(source), object);-}--/**- * The base implementation of `getAllKeys` and `getAllKeysIn` which uses- * `keysFunc` and `symbolsFunc` to get the enumerable property names and- * symbols of `object`.- *- * @private- * @param {Object} object The object to query.- * @param {Function} keysFunc The function to get the keys of `object`.- * @param {Function} symbolsFunc The function to get the symbols of `object`.- * @returns {Array} Returns the array of property names and symbols.- */-function baseGetAllKeys(object, keysFunc, symbolsFunc) {- var result = keysFunc(object);- return isArray(object) ? result : arrayPush(result, symbolsFunc(object));-}--/**- * Creates an array of own enumerable property names and symbols of `object`.- *- * @private- * @param {Object} object The object to query.- * @returns {Array} Returns the array of property names and symbols.- */-function getAllKeys(object) {- return baseGetAllKeys(object, keys, getSymbols);-}--/**- * Creates an array of own and inherited enumerable property names and- * symbols of `object`.- *- * @private- * @param {Object} object The object to query.- * @returns {Array} Returns the array of property names and symbols.- */-function getAllKeysIn(object) {- return baseGetAllKeys(object, keysIn$1, getSymbolsIn);-}--/* Built-in method references that are verified to be native. */-var DataView = getNative(root$1, 'DataView');--/* Built-in method references that are verified to be native. */-var Promise$1 = getNative(root$1, 'Promise');--/* Built-in method references that are verified to be native. */-var Set$1 = getNative(root$1, 'Set');--/* Built-in method references that are verified to be native. */-var WeakMap$1 = getNative(root$1, 'WeakMap');--/** `Object#toString` result references. */-var mapTag$1 = '[object Map]',- objectTag$1 = '[object Object]',- promiseTag = '[object Promise]',- setTag$1 = '[object Set]',- weakMapTag$1 = '[object WeakMap]';--var dataViewTag$1 = '[object DataView]';--/** Used to detect maps, sets, and weakmaps. */-var dataViewCtorString = toSource(DataView),- mapCtorString = toSource(Map$1),- promiseCtorString = toSource(Promise$1),- setCtorString = toSource(Set$1),- weakMapCtorString = toSource(WeakMap$1);--/**- * Gets the `toStringTag` of `value`.- *- * @private- * @param {*} value The value to query.- * @returns {string} Returns the `toStringTag`.- */-var getTag = baseGetTag;--// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.-if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$1) ||- (Map$1 && getTag(new Map$1) != mapTag$1) ||- (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) ||- (Set$1 && getTag(new Set$1) != setTag$1) ||- (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) {- getTag = function(value) {- var result = baseGetTag(value),- Ctor = result == objectTag$1 ? value.constructor : undefined,- ctorString = Ctor ? toSource(Ctor) : '';-- if (ctorString) {- switch (ctorString) {- case dataViewCtorString: return dataViewTag$1;- case mapCtorString: return mapTag$1;- case promiseCtorString: return promiseTag;- case setCtorString: return setTag$1;- case weakMapCtorString: return weakMapTag$1;- }- }- return result;- };-}--var getTag$1 = getTag;--/** Used for built-in method references. */-var objectProto$d = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$b = objectProto$d.hasOwnProperty;--/**- * Initializes an array clone.- *- * @private- * @param {Array} array The array to clone.- * @returns {Array} Returns the initialized clone.- */-function initCloneArray(array) {- var length = array.length,- result = new array.constructor(length);-- // Add properties assigned by `RegExp#exec`.- if (length && typeof array[0] == 'string' && hasOwnProperty$b.call(array, 'index')) {- result.index = array.index;- result.input = array.input;- }- return result;-}--/** Built-in value references. */-var Uint8Array = root$1.Uint8Array;--/**- * Creates a clone of `arrayBuffer`.- *- * @private- * @param {ArrayBuffer} arrayBuffer The array buffer to clone.- * @returns {ArrayBuffer} Returns the cloned array buffer.- */-function cloneArrayBuffer(arrayBuffer) {- var result = new arrayBuffer.constructor(arrayBuffer.byteLength);- new Uint8Array(result).set(new Uint8Array(arrayBuffer));- return result;-}--/**- * Creates a clone of `dataView`.- *- * @private- * @param {Object} dataView The data view to clone.- * @param {boolean} [isDeep] Specify a deep clone.- * @returns {Object} Returns the cloned data view.- */-function cloneDataView(dataView, isDeep) {- var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;- return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);-}--/** Used to match `RegExp` flags from their coerced string values. */-var reFlags = /\w*$/;--/**- * Creates a clone of `regexp`.- *- * @private- * @param {Object} regexp The regexp to clone.- * @returns {Object} Returns the cloned regexp.- */-function cloneRegExp(regexp) {- var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));- result.lastIndex = regexp.lastIndex;- return result;-}--/** Used to convert symbols to primitives and strings. */-var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined,- symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;--/**- * Creates a clone of the `symbol` object.- *- * @private- * @param {Object} symbol The symbol object to clone.- * @returns {Object} Returns the cloned symbol object.- */-function cloneSymbol(symbol) {- return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};-}--/**- * Creates a clone of `typedArray`.- *- * @private- * @param {Object} typedArray The typed array to clone.- * @param {boolean} [isDeep] Specify a deep clone.- * @returns {Object} Returns the cloned typed array.- */-function cloneTypedArray(typedArray, isDeep) {- var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;- return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);-}--/** `Object#toString` result references. */-var boolTag$1 = '[object Boolean]',- dateTag$1 = '[object Date]',- mapTag$2 = '[object Map]',- numberTag$1 = '[object Number]',- regexpTag$1 = '[object RegExp]',- setTag$2 = '[object Set]',- stringTag$1 = '[object String]',- symbolTag$1 = '[object Symbol]';--var arrayBufferTag$1 = '[object ArrayBuffer]',- dataViewTag$2 = '[object DataView]',- float32Tag$1 = '[object Float32Array]',- float64Tag$1 = '[object Float64Array]',- int8Tag$1 = '[object Int8Array]',- int16Tag$1 = '[object Int16Array]',- int32Tag$1 = '[object Int32Array]',- uint8Tag$1 = '[object Uint8Array]',- uint8ClampedTag$1 = '[object Uint8ClampedArray]',- uint16Tag$1 = '[object Uint16Array]',- uint32Tag$1 = '[object Uint32Array]';--/**- * Initializes an object clone based on its `toStringTag`.- *- * **Note:** This function only supports cloning values with tags of- * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.- *- * @private- * @param {Object} object The object to clone.- * @param {string} tag The `toStringTag` of the object to clone.- * @param {boolean} [isDeep] Specify a deep clone.- * @returns {Object} Returns the initialized clone.- */-function initCloneByTag(object, tag, isDeep) {- var Ctor = object.constructor;- switch (tag) {- case arrayBufferTag$1:- return cloneArrayBuffer(object);-- case boolTag$1:- case dateTag$1:- return new Ctor(+object);-- case dataViewTag$2:- return cloneDataView(object, isDeep);-- case float32Tag$1: case float64Tag$1:- case int8Tag$1: case int16Tag$1: case int32Tag$1:- case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:- return cloneTypedArray(object, isDeep);-- case mapTag$2:- return new Ctor;-- case numberTag$1:- case stringTag$1:- return new Ctor(object);-- case regexpTag$1:- return cloneRegExp(object);-- case setTag$2:- return new Ctor;-- case symbolTag$1:- return cloneSymbol(object);- }-}--/** Built-in value references. */-var objectCreate = Object.create;--/**- * The base implementation of `_.create` without support for assigning- * properties to the created object.- *- * @private- * @param {Object} proto The object to inherit from.- * @returns {Object} Returns the new object.- */-var baseCreate = (function() {- function object() {}- return function(proto) {- if (!isObject$4(proto)) {- return {};- }- if (objectCreate) {- return objectCreate(proto);- }- object.prototype = proto;- var result = new object;- object.prototype = undefined;- return result;- };-}());--/**- * Initializes an object clone.- *- * @private- * @param {Object} object The object to clone.- * @returns {Object} Returns the initialized clone.- */-function initCloneObject(object) {- return (typeof object.constructor == 'function' && !isPrototype(object))- ? baseCreate(getPrototype(object))- : {};-}--/** `Object#toString` result references. */-var mapTag$3 = '[object Map]';--/**- * The base implementation of `_.isMap` without Node.js optimizations.- *- * @private- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a map, else `false`.- */-function baseIsMap(value) {- return isObjectLike$1(value) && getTag$1(value) == mapTag$3;-}--/* Node.js helper references. */-var nodeIsMap = nodeUtil && nodeUtil.isMap;--/**- * Checks if `value` is classified as a `Map` object.- *- * @static- * @memberOf _- * @since 4.3.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a map, else `false`.- * @example- *- * _.isMap(new Map);- * // => true- *- * _.isMap(new WeakMap);- * // => false- */-var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;--/** `Object#toString` result references. */-var setTag$3 = '[object Set]';--/**- * The base implementation of `_.isSet` without Node.js optimizations.- *- * @private- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a set, else `false`.- */-function baseIsSet(value) {- return isObjectLike$1(value) && getTag$1(value) == setTag$3;-}--/* Node.js helper references. */-var nodeIsSet = nodeUtil && nodeUtil.isSet;--/**- * Checks if `value` is classified as a `Set` object.- *- * @static- * @memberOf _- * @since 4.3.0- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a set, else `false`.- * @example- *- * _.isSet(new Set);- * // => true- *- * _.isSet(new WeakSet);- * // => false- */-var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;--/** Used to compose bitmasks for cloning. */-var CLONE_DEEP_FLAG = 1,- CLONE_FLAT_FLAG = 2,- CLONE_SYMBOLS_FLAG = 4;--/** `Object#toString` result references. */-var argsTag$2 = '[object Arguments]',- arrayTag$1 = '[object Array]',- boolTag$2 = '[object Boolean]',- dateTag$2 = '[object Date]',- errorTag$1 = '[object Error]',- funcTag$2 = '[object Function]',- genTag$1 = '[object GeneratorFunction]',- mapTag$4 = '[object Map]',- numberTag$2 = '[object Number]',- objectTag$2 = '[object Object]',- regexpTag$2 = '[object RegExp]',- setTag$4 = '[object Set]',- stringTag$2 = '[object String]',- symbolTag$2 = '[object Symbol]',- weakMapTag$2 = '[object WeakMap]';--var arrayBufferTag$2 = '[object ArrayBuffer]',- dataViewTag$3 = '[object DataView]',- float32Tag$2 = '[object Float32Array]',- float64Tag$2 = '[object Float64Array]',- int8Tag$2 = '[object Int8Array]',- int16Tag$2 = '[object Int16Array]',- int32Tag$2 = '[object Int32Array]',- uint8Tag$2 = '[object Uint8Array]',- uint8ClampedTag$2 = '[object Uint8ClampedArray]',- uint16Tag$2 = '[object Uint16Array]',- uint32Tag$2 = '[object Uint32Array]';--/** Used to identify `toStringTag` values supported by `_.clone`. */-var cloneableTags = {};-cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] =-cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] =-cloneableTags[boolTag$2] = cloneableTags[dateTag$2] =-cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =-cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =-cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] =-cloneableTags[numberTag$2] = cloneableTags[objectTag$2] =-cloneableTags[regexpTag$2] = cloneableTags[setTag$4] =-cloneableTags[stringTag$2] = cloneableTags[symbolTag$2] =-cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =-cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;-cloneableTags[errorTag$1] = cloneableTags[funcTag$2] =-cloneableTags[weakMapTag$2] = false;--/**- * The base implementation of `_.clone` and `_.cloneDeep` which tracks- * traversed objects.- *- * @private- * @param {*} value The value to clone.- * @param {boolean} bitmask The bitmask flags.- * 1 - Deep clone- * 2 - Flatten inherited properties- * 4 - Clone symbols- * @param {Function} [customizer] The function to customize cloning.- * @param {string} [key] The key of `value`.- * @param {Object} [object] The parent object of `value`.- * @param {Object} [stack] Tracks traversed objects and their clone counterparts.- * @returns {*} Returns the cloned value.- */-function baseClone(value, bitmask, customizer, key, object, stack) {- var result,- isDeep = bitmask & CLONE_DEEP_FLAG,- isFlat = bitmask & CLONE_FLAT_FLAG,- isFull = bitmask & CLONE_SYMBOLS_FLAG;-- if (customizer) {- result = object ? customizer(value, key, object, stack) : customizer(value);- }- if (result !== undefined) {- return result;- }- if (!isObject$4(value)) {- return value;- }- var isArr = isArray(value);- if (isArr) {- result = initCloneArray(value);- if (!isDeep) {- return copyArray(value, result);- }- } else {- var tag = getTag$1(value),- isFunc = tag == funcTag$2 || tag == genTag$1;-- if (isBuffer(value)) {- return cloneBuffer(value, isDeep);- }- if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) {- result = (isFlat || isFunc) ? {} : initCloneObject(value);- if (!isDeep) {- return isFlat- ? copySymbolsIn(value, baseAssignIn(result, value))- : copySymbols(value, baseAssign(result, value));- }- } else {- if (!cloneableTags[tag]) {- return object ? value : {};- }- result = initCloneByTag(value, tag, isDeep);- }- }- // Check for circular references and return its corresponding clone.- stack || (stack = new Stack);- var stacked = stack.get(value);- if (stacked) {- return stacked;- }- stack.set(value, result);-- if (isSet(value)) {- value.forEach(function(subValue) {- result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));- });- } else if (isMap(value)) {- value.forEach(function(subValue, key) {- result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));- });- }-- var keysFunc = isFull- ? (isFlat ? getAllKeysIn : getAllKeys)- : (isFlat ? keysIn : keys);-- var props = isArr ? undefined : keysFunc(value);- arrayEach(props || value, function(subValue, key) {- if (props) {- key = subValue;- subValue = value[key];- }- // Recursively populate clone (susceptible to call stack limits).- assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));- });- return result;-}--/** Used to compose bitmasks for cloning. */-var CLONE_DEEP_FLAG$1 = 1,- CLONE_SYMBOLS_FLAG$1 = 4;--/**- * This method is like `_.cloneWith` except that it recursively clones `value`.- *- * @static- * @memberOf _- * @since 4.0.0- * @category Lang- * @param {*} value The value to recursively clone.- * @param {Function} [customizer] The function to customize cloning.- * @returns {*} Returns the deep cloned value.- * @see _.cloneWith- * @example- *- * function customizer(value) {- * if (_.isElement(value)) {- * return value.cloneNode(true);- * }- * }- *- * var el = _.cloneDeepWith(document.body, customizer);- *- * console.log(el === document.body);- * // => false- * console.log(el.nodeName);- * // => 'BODY'- * console.log(el.childNodes.length);- * // => 20- */-function cloneDeepWith(value, customizer) {- customizer = typeof customizer == 'function' ? customizer : undefined;- return baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$1, customizer);-}--/** `Object#toString` result references. */-var stringTag$3 = '[object String]';--/**- * Checks if `value` is classified as a `String` primitive or object.- *- * @static- * @since 0.1.0- * @memberOf _- * @category Lang- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` is a string, else `false`.- * @example- *- * _.isString('abc');- * // => true- *- * _.isString(1);- * // => false- */-function isString$2(value) {- return typeof value == 'string' ||- (!isArray(value) && isObjectLike$1(value) && baseGetTag(value) == stringTag$3);-}--/**- * Converts `iterator` to an array.- *- * @private- * @param {Object} iterator The iterator to convert.- * @returns {Array} Returns the converted array.- */-function iteratorToArray(iterator) {- var data,- result = [];-- while (!(data = iterator.next()).done) {- result.push(data.value);- }- return result;-}--/**- * Converts `map` to its key-value pairs.- *- * @private- * @param {Object} map The map to convert.- * @returns {Array} Returns the key-value pairs.- */-function mapToArray(map) {- var index = -1,- result = Array(map.size);-- map.forEach(function(value, key) {- result[++index] = [key, value];- });- return result;-}--/**- * Converts `set` to an array of its values.- *- * @private- * @param {Object} set The set to convert.- * @returns {Array} Returns the values.- */-function setToArray(set) {- var index = -1,- result = Array(set.size);-- set.forEach(function(value) {- result[++index] = value;- });- return result;-}--/**- * Converts an ASCII `string` to an array.- *- * @private- * @param {string} string The string to convert.- * @returns {Array} Returns the converted array.- */-function asciiToArray(string) {- return string.split('');-}--/** Used to compose unicode character classes. */-var rsAstralRange = '\\ud800-\\udfff',- rsComboMarksRange = '\\u0300-\\u036f',- reComboHalfMarksRange = '\\ufe20-\\ufe2f',- rsComboSymbolsRange = '\\u20d0-\\u20ff',- rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,- rsVarRange = '\\ufe0e\\ufe0f';--/** Used to compose unicode capture groups. */-var rsZWJ = '\\u200d';--/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */-var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');--/**- * Checks if `string` contains Unicode symbols.- *- * @private- * @param {string} string The string to inspect.- * @returns {boolean} Returns `true` if a symbol is found, else `false`.- */-function hasUnicode(string) {- return reHasUnicode.test(string);-}--/** Used to compose unicode character classes. */-var rsAstralRange$1 = '\\ud800-\\udfff',- rsComboMarksRange$1 = '\\u0300-\\u036f',- reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f',- rsComboSymbolsRange$1 = '\\u20d0-\\u20ff',- rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1,- rsVarRange$1 = '\\ufe0e\\ufe0f';--/** Used to compose unicode capture groups. */-var rsAstral = '[' + rsAstralRange$1 + ']',- rsCombo = '[' + rsComboRange$1 + ']',- rsFitz = '\\ud83c[\\udffb-\\udfff]',- rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',- rsNonAstral = '[^' + rsAstralRange$1 + ']',- rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',- rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',- rsZWJ$1 = '\\u200d';--/** Used to compose unicode regexes. */-var reOptMod = rsModifier + '?',- rsOptVar = '[' + rsVarRange$1 + ']?',- rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',- rsSeq = rsOptVar + reOptMod + rsOptJoin,- rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';--/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */-var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');--/**- * Converts a Unicode `string` to an array.- *- * @private- * @param {string} string The string to convert.- * @returns {Array} Returns the converted array.- */-function unicodeToArray(string) {- return string.match(reUnicode) || [];-}--/**- * Converts `string` to an array.- *- * @private- * @param {string} string The string to convert.- * @returns {Array} Returns the converted array.- */-function stringToArray$1(string) {- return hasUnicode(string)- ? unicodeToArray(string)- : asciiToArray(string);-}--/**- * The base implementation of `_.values` and `_.valuesIn` which creates an- * array of `object` property values corresponding to the property names- * of `props`.- *- * @private- * @param {Object} object The object to query.- * @param {Array} props The property names to get values for.- * @returns {Object} Returns the array of property values.- */-function baseValues(object, props) {- return arrayMap(props, function(key) {- return object[key];- });-}--/**- * Creates an array of the own enumerable string keyed property values of `object`.- *- * **Note:** Non-object values are coerced to objects.- *- * @static- * @since 0.1.0- * @memberOf _- * @category Object- * @param {Object} object The object to query.- * @returns {Array} Returns the array of property values.- * @example- *- * function Foo() {- * this.a = 1;- * this.b = 2;- * }- *- * Foo.prototype.c = 3;- *- * _.values(new Foo);- * // => [1, 2] (iteration order is not guaranteed)- *- * _.values('hi');- * // => ['h', 'i']- */-function values(object) {- return object == null ? [] : baseValues(object, keys(object));-}--/** `Object#toString` result references. */-var mapTag$5 = '[object Map]',- setTag$5 = '[object Set]';--/** Built-in value references. */-var symIterator = Symbol$1 ? Symbol$1.iterator : undefined;--/**- * Converts `value` to an array.- *- * @static- * @since 0.1.0- * @memberOf _- * @category Lang- * @param {*} value The value to convert.- * @returns {Array} Returns the converted array.- * @example- *- * _.toArray({ 'a': 1, 'b': 2 });- * // => [1, 2]- *- * _.toArray('abc');- * // => ['a', 'b', 'c']- *- * _.toArray(1);- * // => []- *- * _.toArray(null);- * // => []- */-function toArray$1(value) {- if (!value) {- return [];- }- if (isArrayLike$1(value)) {- return isString$2(value) ? stringToArray$1(value) : copyArray(value);- }- if (symIterator && value[symIterator]) {- return iteratorToArray(value[symIterator]());- }- var tag = getTag$1(value),- func = tag == mapTag$5 ? mapToArray : (tag == setTag$5 ? setToArray : values);-- return func(value);-}--var toString$1 = Object.prototype.toString;-var errorToString = Error.prototype.toString;-var regExpToString = RegExp.prototype.toString;-var symbolToString$1 = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : function () {- return '';-};-var SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;--function printNumber(val) {- if (val != +val) return 'NaN';- var isNegativeZero = val === 0 && 1 / val < 0;- return isNegativeZero ? '-0' : '' + val;-}--function printSimpleValue(val, quoteStrings) {- if (quoteStrings === void 0) {- quoteStrings = false;- }-- if (val == null || val === true || val === false) return '' + val;- var typeOf = typeof val;- if (typeOf === 'number') return printNumber(val);- if (typeOf === 'string') return quoteStrings ? "\"" + val + "\"" : val;- if (typeOf === 'function') return '[Function ' + (val.name || 'anonymous') + ']';- if (typeOf === 'symbol') return symbolToString$1.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');- var tag = toString$1.call(val).slice(8, -1);- if (tag === 'Date') return isNaN(val.getTime()) ? '' + val : val.toISOString(val);- if (tag === 'Error' || val instanceof Error) return '[' + errorToString.call(val) + ']';- if (tag === 'RegExp') return regExpToString.call(val);- return null;-}--function printValue(value, quoteStrings) {- var result = printSimpleValue(value, quoteStrings);- if (result !== null) return result;- return JSON.stringify(value, function (key, value) {- var result = printSimpleValue(this[key], quoteStrings);- if (result !== null) return result;- return value;- }, 2);-}--var mixed = {- default: '${path} is invalid',- required: '${path} is a required field',- oneOf: '${path} must be one of the following values: ${values}',- notOneOf: '${path} must not be one of the following values: ${values}',- notType: function notType(_ref) {- var path = _ref.path,- type = _ref.type,- value = _ref.value,- originalValue = _ref.originalValue;- var isCast = originalValue != null && originalValue !== value;- var msg = path + " must be a `" + type + "` type, " + ("but the final value was: `" + printValue(value, true) + "`") + (isCast ? " (cast from the value `" + printValue(originalValue, true) + "`)." : '.');-- if (value === null) {- msg += "\n If \"null\" is intended as an empty value be sure to mark the schema as `.nullable()`";- }-- return msg;- },- defined: '${path} must be defined'-};-var string = {- length: '${path} must be exactly ${length} characters',- min: '${path} must be at least ${min} characters',- max: '${path} must be at most ${max} characters',- matches: '${path} must match the following: "${regex}"',- email: '${path} must be a valid email',- url: '${path} must be a valid URL',- uuid: '${path} must be a valid UUID',- trim: '${path} must be a trimmed string',- lowercase: '${path} must be a lowercase string',- uppercase: '${path} must be a upper case string'-};-var number = {- min: '${path} must be greater than or equal to ${min}',- max: '${path} must be less than or equal to ${max}',- lessThan: '${path} must be less than ${less}',- moreThan: '${path} must be greater than ${more}',- notEqual: '${path} must be not equal to ${notEqual}',- positive: '${path} must be a positive number',- negative: '${path} must be a negative number',- integer: '${path} must be an integer'-};-var date = {- min: '${path} field must be later than ${min}',- max: '${path} field must be at earlier than ${max}'-};-var object = {- noUnknown: '${path} field has unspecified keys: ${unknown}'-};-var array$1 = {- min: '${path} field must have at least ${min} items',- max: '${path} field must have less than or equal to ${max} items'-};--var isSchema$1 = (function (obj) {- return obj && obj.__isYupSchema__;-});--var Condition = /*#__PURE__*/function () {- function Condition(refs, options) {- this.refs = refs;-- if (typeof options === 'function') {- this.fn = options;- return;- }-- if (!has(options, 'is')) throw new TypeError('`is:` is required for `when()` conditions');- if (!options.then && !options.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');- var is = options.is,- then = options.then,- otherwise = options.otherwise;- var check = typeof is === 'function' ? is : function () {- for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {- values[_key] = arguments[_key];- }-- return values.every(function (value) {- return value === is;- });- };-- this.fn = function () {- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {- args[_key2] = arguments[_key2];- }-- var options = args.pop();- var schema = args.pop();- var branch = check.apply(void 0, args) ? then : otherwise;- if (!branch) return undefined;- if (typeof branch === 'function') return branch(schema);- return schema.concat(branch.resolve(options));- };- }-- var _proto = Condition.prototype;-- _proto.resolve = function resolve(base, options) {- var values = this.refs.map(function (ref) {- return ref.getValue(options);- });- var schema = this.fn.apply(base, values.concat(base, options));- if (schema === undefined || schema === base) return base;- if (!isSchema$1(schema)) throw new TypeError('conditions must return a schema object');- return schema.resolve(options);- };-- return Condition;-}();--function _objectWithoutPropertiesLoose(source, excluded) {- if (source == null) return {};- var target = {};- var sourceKeys = Object.keys(source);- var key, i;-- for (i = 0; i < sourceKeys.length; i++) {- key = sourceKeys[i];- if (excluded.indexOf(key) >= 0) continue;- target[key] = source[key];- }-- return target;-}--/* jshint node: true */ -function makeArrayFrom(obj) { - return Array.prototype.slice.apply(obj); -} -var - PENDING = "pending", - RESOLVED = "resolved", - REJECTED = "rejected"; - -function SynchronousPromise(handler) { - this.status = PENDING; - this._continuations = []; - this._parent = null; - this._paused = false; - if (handler) { - handler.call( - this, - this._continueWith.bind(this), - this._failWith.bind(this) - ); - } -} - -function looksLikeAPromise(obj) { - return obj && typeof (obj.then) === "function"; -} - -function passThrough(value) { - return value; -} - -SynchronousPromise.prototype = { - then: function (nextFn, catchFn) { - var next = SynchronousPromise.unresolved()._setParent(this); - if (this._isRejected()) { - if (this._paused) { - this._continuations.push({ - promise: next, - nextFn: nextFn, - catchFn: catchFn - }); - return next; - } - if (catchFn) { - try { - var catchResult = catchFn(this._error); - if (looksLikeAPromise(catchResult)) { - this._chainPromiseData(catchResult, next); - return next; - } else { - return SynchronousPromise.resolve(catchResult)._setParent(this); - } - } catch (e) { - return SynchronousPromise.reject(e)._setParent(this); - } - } - return SynchronousPromise.reject(this._error)._setParent(this); - } - this._continuations.push({ - promise: next, - nextFn: nextFn, - catchFn: catchFn - }); - this._runResolutions(); - return next; - }, - catch: function (handler) { - if (this._isResolved()) { - return SynchronousPromise.resolve(this._data)._setParent(this); - } - var next = SynchronousPromise.unresolved()._setParent(this); - this._continuations.push({ - promise: next, - catchFn: handler - }); - this._runRejections(); - return next; - }, - finally: function(callback) { - var ran = false; - function runFinally(result, err) { - if (!ran) { - ran = true; - if (!callback) { - callback = passThrough; - } - var callbackResult = callback(result); - if (looksLikeAPromise(callbackResult)) { - return callbackResult.then(function() { - if (err) { - throw err; - } - return result; - }); - } else { - return result; - } - } - } - return this - .then(function(result) { - return runFinally(result); - }) - .catch(function(err) { - return runFinally(null, err); - }); - }, - pause: function () { - this._paused = true; - return this; - }, - resume: function () { - var firstPaused = this._findFirstPaused(); - if (firstPaused) { - firstPaused._paused = false; - firstPaused._runResolutions(); - firstPaused._runRejections(); - } - return this; - }, - _findAncestry: function () { - return this._continuations.reduce(function (acc, cur) { - if (cur.promise) { - var node = { - promise: cur.promise, - children: cur.promise._findAncestry() - }; - acc.push(node); - } - return acc; - }, []); - }, - _setParent: function (parent) { - if (this._parent) { - throw new Error("parent already set"); - } - this._parent = parent; - return this; - }, - _continueWith: function (data) { - var firstPending = this._findFirstPending(); - if (firstPending) { - firstPending._data = data; - firstPending._setResolved(); - } - }, - _findFirstPending: function () { - return this._findFirstAncestor(function (test) { - return test._isPending && test._isPending(); - }); - }, - _findFirstPaused: function () { - return this._findFirstAncestor(function (test) { - return test._paused; - }); - }, - _findFirstAncestor: function (matching) { - var test = this; - var result; - while (test) { - if (matching(test)) { - result = test; - } - test = test._parent; - } - return result; - }, - _failWith: function (error) { - var firstRejected = this._findFirstPending(); - if (firstRejected) { - firstRejected._error = error; - firstRejected._setRejected(); - } - }, - _takeContinuations: function () { - return this._continuations.splice(0, this._continuations.length); - }, - _runRejections: function () { - if (this._paused || !this._isRejected()) { - return; - } - var - error = this._error, - continuations = this._takeContinuations(), - self = this; - continuations.forEach(function (cont) { - if (cont.catchFn) { - try { - var catchResult = cont.catchFn(error); - self._handleUserFunctionResult(catchResult, cont.promise); - } catch (e) { - cont.promise.reject(e); - } - } else { - cont.promise.reject(error); - } - }); - }, - _runResolutions: function () { - if (this._paused || !this._isResolved() || this._isPending()) { - return; - } - var continuations = this._takeContinuations(); - if (looksLikeAPromise(this._data)) { - return this._handleWhenResolvedDataIsPromise(this._data); - } - var data = this._data; - var self = this; - continuations.forEach(function (cont) { - if (cont.nextFn) { - try { - var result = cont.nextFn(data); - self._handleUserFunctionResult(result, cont.promise); - } catch (e) { - self._handleResolutionError(e, cont); - } - } else if (cont.promise) { - cont.promise.resolve(data); - } - }); - }, - _handleResolutionError: function (e, continuation) { - this._setRejected(); - if (continuation.catchFn) { - try { - continuation.catchFn(e); - return; - } catch (e2) { - e = e2; - } - } - if (continuation.promise) { - continuation.promise.reject(e); - } - }, - _handleWhenResolvedDataIsPromise: function (data) { - var self = this; - return data.then(function (result) { - self._data = result; - self._runResolutions(); - }).catch(function (error) { - self._error = error; - self._setRejected(); - self._runRejections(); - }); - }, - _handleUserFunctionResult: function (data, nextSynchronousPromise) { - if (looksLikeAPromise(data)) { - this._chainPromiseData(data, nextSynchronousPromise); - } else { - nextSynchronousPromise.resolve(data); - } - }, - _chainPromiseData: function (promiseData, nextSynchronousPromise) { - promiseData.then(function (newData) { - nextSynchronousPromise.resolve(newData); - }).catch(function (newError) { - nextSynchronousPromise.reject(newError); - }); - }, - _setResolved: function () { - this.status = RESOLVED; - if (!this._paused) { - this._runResolutions(); - } - }, - _setRejected: function () { - this.status = REJECTED; - if (!this._paused) { - this._runRejections(); - } - }, - _isPending: function () { - return this.status === PENDING; - }, - _isResolved: function () { - return this.status === RESOLVED; - }, - _isRejected: function () { - return this.status === REJECTED; - } -}; - -SynchronousPromise.resolve = function (result) { - return new SynchronousPromise(function (resolve, reject) { - if (looksLikeAPromise(result)) { - result.then(function (newResult) { - resolve(newResult); - }).catch(function (error) { - reject(error); - }); - } else { - resolve(result); - } - }); -}; - -SynchronousPromise.reject = function (result) { - return new SynchronousPromise(function (resolve, reject) { - reject(result); - }); -}; - -SynchronousPromise.unresolved = function () { - return new SynchronousPromise(function (resolve, reject) { - this.resolve = resolve; - this.reject = reject; - }); -}; - -SynchronousPromise.all = function () { - var args = makeArrayFrom(arguments); - if (Array.isArray(args[0])) { - args = args[0]; - } - if (!args.length) { - return SynchronousPromise.resolve([]); - } - return new SynchronousPromise(function (resolve, reject) { - var - allData = [], - numResolved = 0, - doResolve = function () { - if (numResolved === args.length) { - resolve(allData); - } - }, - rejected = false, - doReject = function (err) { - if (rejected) { - return; - } - rejected = true; - reject(err); - }; - args.forEach(function (arg, idx) { - SynchronousPromise.resolve(arg).then(function (thisResult) { - allData[idx] = thisResult; - numResolved += 1; - doResolve(); - }).catch(function (err) { - doReject(err); - }); - }); - }); -}; - -/* jshint ignore:start */ -if (Promise === SynchronousPromise) { - throw new Error("Please use SynchronousPromise.installGlobally() to install globally"); -} -var RealPromise = Promise; -SynchronousPromise.installGlobally = function(__awaiter) { - if (Promise === SynchronousPromise) { - return __awaiter; - } - var result = patchAwaiterIfRequired(__awaiter); - Promise = SynchronousPromise; - return result; -}; - -SynchronousPromise.uninstallGlobally = function() { - if (Promise === SynchronousPromise) { - Promise = RealPromise; - } -}; - -function patchAwaiterIfRequired(__awaiter) { - if (typeof(__awaiter) === "undefined" || __awaiter.__patched) { - return __awaiter; - } - var originalAwaiter = __awaiter; - __awaiter = function() { - originalAwaiter.apply(this, makeArrayFrom(arguments)); - }; - __awaiter.__patched = true; - return __awaiter; -} -/* jshint ignore:end */ - -var synchronousPromise = { - SynchronousPromise: SynchronousPromise -};--var strReg = /\$\{\s*(\w+)\s*\}/g;--var replace = function replace(str) {- return function (params) {- return str.replace(strReg, function (_, key) {- return printValue(params[key]);- });- };-};--function ValidationError(errors, value, field, type) {- var _this = this;-- this.name = 'ValidationError';- this.value = value;- this.path = field;- this.type = type;- this.errors = [];- this.inner = [];- if (errors) [].concat(errors).forEach(function (err) {- _this.errors = _this.errors.concat(err.errors || err);- if (err.inner) _this.inner = _this.inner.concat(err.inner.length ? err.inner : err);- });- this.message = this.errors.length > 1 ? this.errors.length + " errors occurred" : this.errors[0];- if (Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);-}-ValidationError.prototype = Object.create(Error.prototype);-ValidationError.prototype.constructor = ValidationError;--ValidationError.isError = function (err) {- return err && err.name === 'ValidationError';-};--ValidationError.formatError = function (message, params) {- if (typeof message === 'string') message = replace(message);-- var fn = function fn(params) {- params.path = params.label || params.path || 'this';- return typeof message === 'function' ? message(params) : message;- };-- return arguments.length === 1 ? fn : fn(params);-};--var promise = function promise(sync) {- return sync ? synchronousPromise.SynchronousPromise : Promise;-};--var unwrapError = function unwrapError(errors) {- if (errors === void 0) {- errors = [];- }-- return errors.inner && errors.inner.length ? errors.inner : [].concat(errors);-};--function scopeToValue(promises, value, sync) {- //console.log('scopeToValue', promises, value)- var p = promise(sync).all(promises); //console.log('scopeToValue B', p)-- var b = p.catch(function (err) {- if (err.name === 'ValidationError') err.value = value;- throw err;- }); //console.log('scopeToValue c', b)-- var c = b.then(function () {- return value;- }); //console.log('scopeToValue d', c)-- return c;-}-/**- * If not failing on the first error, catch the errors- * and collect them in an array- */---function propagateErrors(endEarly, errors) {- return endEarly ? null : function (err) {- errors.push(err);- return err.value;- };-}-function settled(promises, sync) {- var Promise = promise(sync);- return Promise.all(promises.map(function (p) {- return Promise.resolve(p).then(function (value) {- return {- fulfilled: true,- value: value- };- }, function (value) {- return {- fulfilled: false,- value: value- };- });- }));-}-function collectErrors(_ref) {- var validations = _ref.validations,- value = _ref.value,- path = _ref.path,- sync = _ref.sync,- errors = _ref.errors,- sort = _ref.sort;- errors = unwrapError(errors);- return settled(validations, sync).then(function (results) {- var nestedErrors = results.filter(function (r) {- return !r.fulfilled;- }).reduce(function (arr, _ref2) {- var error = _ref2.value;-- // we are only collecting validation errors- if (!ValidationError.isError(error)) {- throw error;- }-- return arr.concat(error);- }, []);- if (sort) nestedErrors.sort(sort); //show parent errors after the nested ones: name.first, name-- errors = nestedErrors.concat(errors);- if (errors.length) throw new ValidationError(errors, value, path);- return value;- });-}-function runValidations(_ref3) {- var endEarly = _ref3.endEarly,- options = _objectWithoutPropertiesLoose(_ref3, ["endEarly"]);-- if (endEarly) return scopeToValue(options.validations, options.value, options.sync);- return collectErrors(options);-}--var isObject$5 = function isObject(obj) {- return Object.prototype.toString.call(obj) === '[object Object]';-};--function prependDeep(target, source) {- for (var key in source) {- if (has(source, key)) {- var sourceVal = source[key],- targetVal = target[key];-- if (targetVal === undefined) {- target[key] = sourceVal;- } else if (targetVal === sourceVal) {- continue;- } else if (isSchema$1(targetVal)) {- if (isSchema$1(sourceVal)) target[key] = sourceVal.concat(targetVal);- } else if (isObject$5(targetVal)) {- if (isObject$5(sourceVal)) target[key] = prependDeep(targetVal, sourceVal);- } else if (Array.isArray(targetVal)) {- if (Array.isArray(sourceVal)) target[key] = sourceVal.concat(targetVal);- }- }- }-- return target;-}--/**- * Creates a base function for methods like `_.forIn` and `_.forOwn`.- *- * @private- * @param {boolean} [fromRight] Specify iterating from right to left.- * @returns {Function} Returns the new base function.- */-function createBaseFor(fromRight) {- return function(object, iteratee, keysFunc) {- var index = -1,- iterable = Object(object),- props = keysFunc(object),- length = props.length;-- while (length--) {- var key = props[fromRight ? length : ++index];- if (iteratee(iterable[key], key, iterable) === false) {- break;- }- }- return object;- };-}--/**- * The base implementation of `baseForOwn` which iterates over `object`- * properties returned by `keysFunc` and invokes `iteratee` for each property.- * Iteratee functions may exit iteration early by explicitly returning `false`.- *- * @private- * @param {Object} object The object to iterate over.- * @param {Function} iteratee The function invoked per iteration.- * @param {Function} keysFunc The function to get the keys of `object`.- * @returns {Object} Returns `object`.- */-var baseFor = createBaseFor();--/**- * The base implementation of `_.forOwn` without support for iteratee shorthands.- *- * @private- * @param {Object} object The object to iterate over.- * @param {Function} iteratee The function invoked per iteration.- * @returns {Object} Returns `object`.- */-function baseForOwn(object, iteratee) {- return object && baseFor(object, iteratee, keys);-}--/** Used to stand-in for `undefined` hash values. */-var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';--/**- * Adds `value` to the array cache.- *- * @private- * @name add- * @memberOf SetCache- * @alias push- * @param {*} value The value to cache.- * @returns {Object} Returns the cache instance.- */-function setCacheAdd(value) {- this.__data__.set(value, HASH_UNDEFINED$2);- return this;-}--/**- * Checks if `value` is in the array cache.- *- * @private- * @name has- * @memberOf SetCache- * @param {*} value The value to search for.- * @returns {number} Returns `true` if `value` is found, else `false`.- */-function setCacheHas(value) {- return this.__data__.has(value);-}--/**- *- * Creates an array cache object to store unique values.- *- * @private- * @constructor- * @param {Array} [values] The values to cache.- */-function SetCache(values) {- var index = -1,- length = values == null ? 0 : values.length;-- this.__data__ = new MapCache;- while (++index < length) {- this.add(values[index]);- }-}--// Add methods to `SetCache`.-SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;-SetCache.prototype.has = setCacheHas;--/**- * A specialized version of `_.some` for arrays without support for iteratee- * shorthands.- *- * @private- * @param {Array} [array] The array to iterate over.- * @param {Function} predicate The function invoked per iteration.- * @returns {boolean} Returns `true` if any element passes the predicate check,- * else `false`.- */-function arraySome(array, predicate) {- var index = -1,- length = array == null ? 0 : array.length;-- while (++index < length) {- if (predicate(array[index], index, array)) {- return true;- }- }- return false;-}--/**- * Checks if a `cache` value for `key` exists.- *- * @private- * @param {Object} cache The cache to query.- * @param {string} key The key of the entry to check.- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.- */-function cacheHas(cache, key) {- return cache.has(key);-}--/** Used to compose bitmasks for value comparisons. */-var COMPARE_PARTIAL_FLAG = 1,- COMPARE_UNORDERED_FLAG = 2;--/**- * A specialized version of `baseIsEqualDeep` for arrays with support for- * partial deep comparisons.- *- * @private- * @param {Array} array The array to compare.- * @param {Array} other The other array to compare.- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.- * @param {Function} customizer The function to customize comparisons.- * @param {Function} equalFunc The function to determine equivalents of values.- * @param {Object} stack Tracks traversed `array` and `other` objects.- * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.- */-function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {- var isPartial = bitmask & COMPARE_PARTIAL_FLAG,- arrLength = array.length,- othLength = other.length;-- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {- return false;- }- // Assume cyclic values are equal.- var stacked = stack.get(array);- if (stacked && stack.get(other)) {- return stacked == other;- }- var index = -1,- result = true,- seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;-- stack.set(array, other);- stack.set(other, array);-- // Ignore non-index properties.- while (++index < arrLength) {- var arrValue = array[index],- othValue = other[index];-- if (customizer) {- var compared = isPartial- ? customizer(othValue, arrValue, index, other, array, stack)- : customizer(arrValue, othValue, index, array, other, stack);- }- if (compared !== undefined) {- if (compared) {- continue;- }- result = false;- break;- }- // Recursively compare arrays (susceptible to call stack limits).- if (seen) {- if (!arraySome(other, function(othValue, othIndex) {- if (!cacheHas(seen, othIndex) &&- (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {- return seen.push(othIndex);- }- })) {- result = false;- break;- }- } else if (!(- arrValue === othValue ||- equalFunc(arrValue, othValue, bitmask, customizer, stack)- )) {- result = false;- break;- }- }- stack['delete'](array);- stack['delete'](other);- return result;-}--/** Used to compose bitmasks for value comparisons. */-var COMPARE_PARTIAL_FLAG$1 = 1,- COMPARE_UNORDERED_FLAG$1 = 2;--/** `Object#toString` result references. */-var boolTag$3 = '[object Boolean]',- dateTag$3 = '[object Date]',- errorTag$2 = '[object Error]',- mapTag$6 = '[object Map]',- numberTag$3 = '[object Number]',- regexpTag$3 = '[object RegExp]',- setTag$6 = '[object Set]',- stringTag$4 = '[object String]',- symbolTag$3 = '[object Symbol]';--var arrayBufferTag$3 = '[object ArrayBuffer]',- dataViewTag$4 = '[object DataView]';--/** Used to convert symbols to primitives and strings. */-var symbolProto$2 = Symbol$1 ? Symbol$1.prototype : undefined,- symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;--/**- * A specialized version of `baseIsEqualDeep` for comparing objects of- * the same `toStringTag`.- *- * **Note:** This function only supports comparing values with tags of- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.- *- * @private- * @param {Object} object The object to compare.- * @param {Object} other The other object to compare.- * @param {string} tag The `toStringTag` of the objects to compare.- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.- * @param {Function} customizer The function to customize comparisons.- * @param {Function} equalFunc The function to determine equivalents of values.- * @param {Object} stack Tracks traversed `object` and `other` objects.- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.- */-function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {- switch (tag) {- case dataViewTag$4:- if ((object.byteLength != other.byteLength) ||- (object.byteOffset != other.byteOffset)) {- return false;- }- object = object.buffer;- other = other.buffer;-- case arrayBufferTag$3:- if ((object.byteLength != other.byteLength) ||- !equalFunc(new Uint8Array(object), new Uint8Array(other))) {- return false;- }- return true;-- case boolTag$3:- case dateTag$3:- case numberTag$3:- // Coerce booleans to `1` or `0` and dates to milliseconds.- // Invalid dates are coerced to `NaN`.- return eq(+object, +other);-- case errorTag$2:- return object.name == other.name && object.message == other.message;-- case regexpTag$3:- case stringTag$4:- // Coerce regexes to strings and treat strings, primitives and objects,- // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring- // for more details.- return object == (other + '');-- case mapTag$6:- var convert = mapToArray;-- case setTag$6:- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;- convert || (convert = setToArray);-- if (object.size != other.size && !isPartial) {- return false;- }- // Assume cyclic values are equal.- var stacked = stack.get(object);- if (stacked) {- return stacked == other;- }- bitmask |= COMPARE_UNORDERED_FLAG$1;-- // Recursively compare objects (susceptible to call stack limits).- stack.set(object, other);- var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);- stack['delete'](object);- return result;-- case symbolTag$3:- if (symbolValueOf$1) {- return symbolValueOf$1.call(object) == symbolValueOf$1.call(other);- }- }- return false;-}--/** Used to compose bitmasks for value comparisons. */-var COMPARE_PARTIAL_FLAG$2 = 1;--/** Used for built-in method references. */-var objectProto$e = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$c = objectProto$e.hasOwnProperty;--/**- * A specialized version of `baseIsEqualDeep` for objects with support for- * partial deep comparisons.- *- * @private- * @param {Object} object The object to compare.- * @param {Object} other The other object to compare.- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.- * @param {Function} customizer The function to customize comparisons.- * @param {Function} equalFunc The function to determine equivalents of values.- * @param {Object} stack Tracks traversed `object` and `other` objects.- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.- */-function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {- var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,- objProps = getAllKeys(object),- objLength = objProps.length,- othProps = getAllKeys(other),- othLength = othProps.length;-- if (objLength != othLength && !isPartial) {- return false;- }- var index = objLength;- while (index--) {- var key = objProps[index];- if (!(isPartial ? key in other : hasOwnProperty$c.call(other, key))) {- return false;- }- }- // Assume cyclic values are equal.- var stacked = stack.get(object);- if (stacked && stack.get(other)) {- return stacked == other;- }- var result = true;- stack.set(object, other);- stack.set(other, object);-- var skipCtor = isPartial;- while (++index < objLength) {- key = objProps[index];- var objValue = object[key],- othValue = other[key];-- if (customizer) {- var compared = isPartial- ? customizer(othValue, objValue, key, other, object, stack)- : customizer(objValue, othValue, key, object, other, stack);- }- // Recursively compare objects (susceptible to call stack limits).- if (!(compared === undefined- ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))- : compared- )) {- result = false;- break;- }- skipCtor || (skipCtor = key == 'constructor');- }- if (result && !skipCtor) {- var objCtor = object.constructor,- othCtor = other.constructor;-- // Non `Object` object instances with different constructors are not equal.- if (objCtor != othCtor &&- ('constructor' in object && 'constructor' in other) &&- !(typeof objCtor == 'function' && objCtor instanceof objCtor &&- typeof othCtor == 'function' && othCtor instanceof othCtor)) {- result = false;- }- }- stack['delete'](object);- stack['delete'](other);- return result;-}--/** Used to compose bitmasks for value comparisons. */-var COMPARE_PARTIAL_FLAG$3 = 1;--/** `Object#toString` result references. */-var argsTag$3 = '[object Arguments]',- arrayTag$2 = '[object Array]',- objectTag$3 = '[object Object]';--/** Used for built-in method references. */-var objectProto$f = Object.prototype;--/** Used to check objects for own properties. */-var hasOwnProperty$d = objectProto$f.hasOwnProperty;--/**- * A specialized version of `baseIsEqual` for arrays and objects which performs- * deep comparisons and tracks traversed objects enabling objects with circular- * references to be compared.- *- * @private- * @param {Object} object The object to compare.- * @param {Object} other The other object to compare.- * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.- * @param {Function} customizer The function to customize comparisons.- * @param {Function} equalFunc The function to determine equivalents of values.- * @param {Object} [stack] Tracks traversed `object` and `other` objects.- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.- */-function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {- var objIsArr = isArray(object),- othIsArr = isArray(other),- objTag = objIsArr ? arrayTag$2 : getTag$1(object),- othTag = othIsArr ? arrayTag$2 : getTag$1(other);-- objTag = objTag == argsTag$3 ? objectTag$3 : objTag;- othTag = othTag == argsTag$3 ? objectTag$3 : othTag;-- var objIsObj = objTag == objectTag$3,- othIsObj = othTag == objectTag$3,- isSameTag = objTag == othTag;-- if (isSameTag && isBuffer(object)) {- if (!isBuffer(other)) {- return false;- }- objIsArr = true;- objIsObj = false;- }- if (isSameTag && !objIsObj) {- stack || (stack = new Stack);- return (objIsArr || isTypedArray(object))- ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)- : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);- }- if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {- var objIsWrapped = objIsObj && hasOwnProperty$d.call(object, '__wrapped__'),- othIsWrapped = othIsObj && hasOwnProperty$d.call(other, '__wrapped__');-- if (objIsWrapped || othIsWrapped) {- var objUnwrapped = objIsWrapped ? object.value() : object,- othUnwrapped = othIsWrapped ? other.value() : other;-- stack || (stack = new Stack);- return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);- }- }- if (!isSameTag) {- return false;- }- stack || (stack = new Stack);- return equalObjects(object, other, bitmask, customizer, equalFunc, stack);-}--/**- * The base implementation of `_.isEqual` which supports partial comparisons- * and tracks traversed objects.- *- * @private- * @param {*} value The value to compare.- * @param {*} other The other value to compare.- * @param {boolean} bitmask The bitmask flags.- * 1 - Unordered comparison- * 2 - Partial comparison- * @param {Function} [customizer] The function to customize comparisons.- * @param {Object} [stack] Tracks traversed `value` and `other` objects.- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.- */-function baseIsEqual(value, other, bitmask, customizer, stack) {- if (value === other) {- return true;- }- if (value == null || other == null || (!isObjectLike$1(value) && !isObjectLike$1(other))) {- return value !== value && other !== other;- }- return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);-}--/** Used to compose bitmasks for value comparisons. */-var COMPARE_PARTIAL_FLAG$4 = 1,- COMPARE_UNORDERED_FLAG$2 = 2;--/**- * The base implementation of `_.isMatch` without support for iteratee shorthands.- *- * @private- * @param {Object} object The object to inspect.- * @param {Object} source The object of property values to match.- * @param {Array} matchData The property names, values, and compare flags to match.- * @param {Function} [customizer] The function to customize comparisons.- * @returns {boolean} Returns `true` if `object` is a match, else `false`.- */-function baseIsMatch(object, source, matchData, customizer) {- var index = matchData.length,- length = index,- noCustomizer = !customizer;-- if (object == null) {- return !length;- }- object = Object(object);- while (index--) {- var data = matchData[index];- if ((noCustomizer && data[2])- ? data[1] !== object[data[0]]- : !(data[0] in object)- ) {- return false;- }- }- while (++index < length) {- data = matchData[index];- var key = data[0],- objValue = object[key],- srcValue = data[1];-- if (noCustomizer && data[2]) {- if (objValue === undefined && !(key in object)) {- return false;- }- } else {- var stack = new Stack;- if (customizer) {- var result = customizer(objValue, srcValue, key, object, source, stack);- }- if (!(result === undefined- ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack)- : result- )) {- return false;- }- }- }- return true;-}--/**- * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.- *- * @private- * @param {*} value The value to check.- * @returns {boolean} Returns `true` if `value` if suitable for strict- * equality comparisons, else `false`.- */-function isStrictComparable(value) {- return value === value && !isObject$4(value);-}--/**- * Gets the property names, values, and compare flags of `object`.- *- * @private- * @param {Object} object The object to query.- * @returns {Array} Returns the match data of `object`.- */-function getMatchData(object) {- var result = keys(object),- length = result.length;-- while (length--) {- var key = result[length],- value = object[key];-- result[length] = [key, value, isStrictComparable(value)];- }- return result;-}--/**- * A specialized version of `matchesProperty` for source values suitable- * for strict equality comparisons, i.e. `===`.- *- * @private- * @param {string} key The key of the property to get.- * @param {*} srcValue The value to match.- * @returns {Function} Returns the new spec function.- */-function matchesStrictComparable(key, srcValue) {- return function(object) {- if (object == null) {- return false;- }- return object[key] === srcValue &&- (srcValue !== undefined || (key in Object(object)));- };-}--/**- * The base implementation of `_.matches` which doesn't clone `source`.- *- * @private- * @param {Object} source The object of property values to match.- * @returns {Function} Returns the new spec function.- */-function baseMatches(source) {- var matchData = getMatchData(source);- if (matchData.length == 1 && matchData[0][2]) {- return matchesStrictComparable(matchData[0][0], matchData[0][1]);- }- return function(object) {- return object === source || baseIsMatch(object, source, matchData);- };-}--/**- * The base implementation of `_.get` without support for default values.- *- * @private- * @param {Object} object The object to query.- * @param {Array|string} path The path of the property to get.- * @returns {*} Returns the resolved value.- */-function baseGet(object, path) {- path = castPath(path, object);-- var index = 0,- length = path.length;-- while (object != null && index < length) {- object = object[toKey(path[index++])];- }- return (index && index == length) ? object : undefined;-}--/**- * Gets the value at `path` of `object`. If the resolved value is- * `undefined`, the `defaultValue` is returned in its place.- *- * @static- * @memberOf _- * @since 3.7.0- * @category Object- * @param {Object} object The object to query.- * @param {Array|string} path The path of the property to get.- * @param {*} [defaultValue] The value returned for `undefined` resolved values.- * @returns {*} Returns the resolved value.- * @example- *- * var object = { 'a': [{ 'b': { 'c': 3 } }] };- *- * _.get(object, 'a[0].b.c');- * // => 3- *- * _.get(object, ['a', '0', 'b', 'c']);- * // => 3- *- * _.get(object, 'a.b.c', 'default');- * // => 'default'- */-function get(object, path, defaultValue) {- var result = object == null ? undefined : baseGet(object, path);- return result === undefined ? defaultValue : result;-}--/**- * The base implementation of `_.hasIn` without support for deep paths.- *- * @private- * @param {Object} [object] The object to query.- * @param {Array|string} key The key to check.- * @returns {boolean} Returns `true` if `key` exists, else `false`.- */-function baseHasIn(object, key) {- return object != null && key in Object(object);-}--/**- * Checks if `path` is a direct or inherited property of `object`.- *- * @static- * @memberOf _- * @since 4.0.0- * @category Object- * @param {Object} object The object to query.- * @param {Array|string} path The path to check.- * @returns {boolean} Returns `true` if `path` exists, else `false`.- * @example- *- * var object = _.create({ 'a': _.create({ 'b': 2 }) });- *- * _.hasIn(object, 'a');- * // => true- *- * _.hasIn(object, 'a.b');- * // => true- *- * _.hasIn(object, ['a', 'b']);- * // => true- *- * _.hasIn(object, 'b');- * // => false- */-function hasIn(object, path) {- return object != null && hasPath(object, path, baseHasIn);-}--/** Used to compose bitmasks for value comparisons. */-var COMPARE_PARTIAL_FLAG$5 = 1,- COMPARE_UNORDERED_FLAG$3 = 2;--/**- * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.- *- * @private- * @param {string} path The path of the property to get.- * @param {*} srcValue The value to match.- * @returns {Function} Returns the new spec function.- */-function baseMatchesProperty(path, srcValue) {- if (isKey(path) && isStrictComparable(srcValue)) {- return matchesStrictComparable(toKey(path), srcValue);- }- return function(object) {- var objValue = get(object, path);- return (objValue === undefined && objValue === srcValue)- ? hasIn(object, path)- : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);- };-}--/**- * This method returns the first argument it receives.- *- * @static- * @since 0.1.0- * @memberOf _- * @category Util- * @param {*} value Any value.- * @returns {*} Returns `value`.- * @example- *- * var object = { 'a': 1 };- *- * console.log(_.identity(object) === object);- * // => true- */-function identity(value) {- return value;-}--/**- * The base implementation of `_.property` without support for deep paths.- *- * @private- * @param {string} key The key of the property to get.- * @returns {Function} Returns the new accessor function.- */-function baseProperty(key) {- return function(object) {- return object == null ? undefined : object[key];- };-}--/**- * A specialized version of `baseProperty` which supports deep paths.- *- * @private- * @param {Array|string} path The path of the property to get.- * @returns {Function} Returns the new accessor function.- */-function basePropertyDeep(path) {- return function(object) {- return baseGet(object, path);- };-}--/**- * Creates a function that returns the value at `path` of a given object.- *- * @static- * @memberOf _- * @since 2.4.0- * @category Util- * @param {Array|string} path The path of the property to get.- * @returns {Function} Returns the new accessor function.- * @example- *- * var objects = [- * { 'a': { 'b': 2 } },- * { 'a': { 'b': 1 } }- * ];- *- * _.map(objects, _.property('a.b'));- * // => [2, 1]- *- * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');- * // => [1, 2]- */-function property(path) {- return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);-}--/**- * The base implementation of `_.iteratee`.- *- * @private- * @param {*} [value=_.identity] The value to convert to an iteratee.- * @returns {Function} Returns the iteratee.- */-function baseIteratee(value) {- // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.- // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.- if (typeof value == 'function') {- return value;- }- if (value == null) {- return identity;- }- if (typeof value == 'object') {- return isArray(value)- ? baseMatchesProperty(value[0], value[1])- : baseMatches(value);- }- return property(value);-}--/**- * Creates an object with the same keys as `object` and values generated- * by running each own enumerable string keyed property of `object` thru- * `iteratee`. The iteratee is invoked with three arguments:- * (value, key, object).- *- * @static- * @memberOf _- * @since 2.4.0- * @category Object- * @param {Object} object The object to iterate over.- * @param {Function} [iteratee=_.identity] The function invoked per iteration.- * @returns {Object} Returns the new mapped object.- * @see _.mapKeys- * @example- *- * var users = {- * 'fred': { 'user': 'fred', 'age': 40 },- * 'pebbles': { 'user': 'pebbles', 'age': 1 }- * };- *- * _.mapValues(users, function(o) { return o.age; });- * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)- *- * // The `_.property` iteratee shorthand.- * _.mapValues(users, 'age');- * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)- */-function mapValues(object, iteratee) {- var result = {};- iteratee = baseIteratee(iteratee);-- baseForOwn(object, function(value, key, object) {- baseAssignValue(result, key, iteratee(value, key, object));- });- return result;-}--/**- * Based on Kendo UI Core expression code <https://github.com/telerik/kendo-ui-core#license-information>- */--function Cache(maxSize) {- this._maxSize = maxSize;- this.clear();-}-Cache.prototype.clear = function() {- this._size = 0;- this._values = Object.create(null);-};-Cache.prototype.get = function(key) {- return this._values[key]-};-Cache.prototype.set = function(key, value) {- this._size >= this._maxSize && this.clear();- if (!(key in this._values)) this._size++;-- return (this._values[key] = value)-};--var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g,- DIGIT_REGEX = /^\d+$/,- LEAD_DIGIT_REGEX = /^\d/,- SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,- CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/,- MAX_CACHE_SIZE = 512;--var pathCache = new Cache(MAX_CACHE_SIZE),- setCache = new Cache(MAX_CACHE_SIZE),- getCache = new Cache(MAX_CACHE_SIZE);--var propertyExpr = {- Cache: Cache,-- split: split,-- normalizePath: normalizePath$1,-- setter: function(path) {- var parts = normalizePath$1(path);-- return (- setCache.get(path) ||- setCache.set(path, function setter(data, value) {- var index = 0,- len = parts.length;- while (index < len - 1) {- data = data[parts[index++]];- }- data[parts[index]] = value;- })- )- },-- getter: function(path, safe) {- var parts = normalizePath$1(path);- return (- getCache.get(path) ||- getCache.set(path, function getter(data) {- var index = 0,- len = parts.length;- while (index < len) {- if (data != null || !safe) data = data[parts[index++]];- else return- }- return data- })- )- },-- join: function(segments) {- return segments.reduce(function(path, part) {- return (- path +- (isQuoted(part) || DIGIT_REGEX.test(part)- ? '[' + part + ']'- : (path ? '.' : '') + part)- )- }, '')- },-- forEach: function(path, cb, thisArg) {- forEach$1(Array.isArray(path) ? path : split(path), cb, thisArg);- }-};--function normalizePath$1(path) {- return (- pathCache.get(path) ||- pathCache.set(- path,- split(path).map(function(part) {- return part.replace(CLEAN_QUOTES_REGEX, '$2')- })- )- )-}--function split(path) {- return path.match(SPLIT_REGEX)-}--function forEach$1(parts, iter, thisArg) {- var len = parts.length,- part,- idx,- isArray,- isBracket;-- for (idx = 0; idx < len; idx++) {- part = parts[idx];-- if (part) {- if (shouldBeQuoted(part)) {- part = '"' + part + '"';- }-- isBracket = isQuoted(part);- isArray = !isBracket && /^\d+$/.test(part);-- iter.call(thisArg, part, isBracket, isArray, idx, parts);- }- }-}--function isQuoted(str) {- return (- typeof str === 'string' && str && ["'", '"'].indexOf(str.charAt(0)) !== -1- )-}--function hasLeadingNumber(part) {- return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)-}--function hasSpecialChars(part) {- return SPEC_CHAR_REGEX.test(part)-}--function shouldBeQuoted(part) {- return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))-}--var prefixes = {- context: '$',- value: '.'-};--var Reference = /*#__PURE__*/function () {- function Reference(key, options) {- if (options === void 0) {- options = {};- }-- if (typeof key !== 'string') throw new TypeError('ref must be a string, got: ' + key);- this.key = key.trim();- if (key === '') throw new TypeError('ref must be a non-empty string');- this.isContext = this.key[0] === prefixes.context;- this.isValue = this.key[0] === prefixes.value;- this.isSibling = !this.isContext && !this.isValue;- var prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : '';- this.path = this.key.slice(prefix.length);- this.getter = this.path && propertyExpr.getter(this.path, true);- this.map = options.map;- }-- var _proto = Reference.prototype;-- _proto.getValue = function getValue(options) {- var result = this.isContext ? options.context : this.isValue ? options.value : options.parent;- if (this.getter) result = this.getter(result || {});- if (this.map) result = this.map(result);- return result;- };-- _proto.cast = function cast(value, options) {- return this.getValue(_extends({}, options, {- value: value- }));- };-- _proto.resolve = function resolve() {- return this;- };-- _proto.describe = function describe() {- return {- type: 'ref',- key: this.key- };- };-- _proto.toString = function toString() {- return "Ref(" + this.key + ")";- };-- Reference.isRef = function isRef(value) {- return value && value.__isYupRef;- };-- return Reference;-}();-Reference.prototype.__isYupRef = true;--var formatError$1 = ValidationError.formatError;--var thenable = function thenable(p) {- return p && typeof p.then === 'function' && typeof p.catch === 'function';-};--function runTest(testFn, ctx, value, sync) {- var result = testFn.call(ctx, value);- if (!sync) return Promise.resolve(result);-- if (thenable(result)) {- throw new Error("Validation test of type: \"" + ctx.type + "\" returned a Promise during a synchronous validate. " + "This test will finish after the validate call has returned");- }-- return synchronousPromise.SynchronousPromise.resolve(result);-}--function resolveParams(oldParams, newParams, resolve) {- return mapValues(_extends({}, oldParams, newParams), resolve);-}--function createErrorFactory(_ref) {- var value = _ref.value,- label = _ref.label,- resolve = _ref.resolve,- originalValue = _ref.originalValue,- opts = _objectWithoutPropertiesLoose(_ref, ["value", "label", "resolve", "originalValue"]);-- return function createError(_temp) {- var _ref2 = _temp === void 0 ? {} : _temp,- _ref2$path = _ref2.path,- path = _ref2$path === void 0 ? opts.path : _ref2$path,- _ref2$message = _ref2.message,- message = _ref2$message === void 0 ? opts.message : _ref2$message,- _ref2$type = _ref2.type,- type = _ref2$type === void 0 ? opts.name : _ref2$type,- params = _ref2.params;-- params = _extends({- path: path,- value: value,- originalValue: originalValue,- label: label- }, resolveParams(opts.params, params, resolve));- return _extends(new ValidationError(formatError$1(message, params), value, path, type), {- params: params- });- };-}-function createValidation(options) {- var name = options.name,- message = options.message,- test = options.test,- params = options.params;-- function validate(_ref3) {- var value = _ref3.value,- path = _ref3.path,- label = _ref3.label,- options = _ref3.options,- originalValue = _ref3.originalValue,- sync = _ref3.sync,- rest = _objectWithoutPropertiesLoose(_ref3, ["value", "path", "label", "options", "originalValue", "sync"]);-- var parent = options.parent;-- var resolve = function resolve(item) {- return Reference.isRef(item) ? item.getValue({- value: value,- parent: parent,- context: options.context- }) : item;- };-- var createError = createErrorFactory({- message: message,- path: path,- value: value,- originalValue: originalValue,- params: params,- label: label,- resolve: resolve,- name: name- });-- var ctx = _extends({- path: path,- parent: parent,- type: name,- createError: createError,- resolve: resolve,- options: options- }, rest);-- return runTest(test, ctx, value, sync).then(function (validOrError) {- if (ValidationError.isError(validOrError)) throw validOrError;else if (!validOrError) throw createError();- });- }-- validate.OPTIONS = options;- return validate;-}--var trim = function trim(part) {- return part.substr(0, part.length - 1).substr(1);-};--function getIn(schema, path, value, context) {- if (context === void 0) {- context = value;- }-- var parent, lastPart, lastPartDebug; // root path: ''-- if (!path) return {- parent: parent,- parentPath: path,- schema: schema- };- propertyExpr.forEach(path, function (_part, isBracket, isArray) {- var part = isBracket ? trim(_part) : _part;- schema = schema.resolve({- context: context,- parent: parent,- value: value- });-- if (schema.innerType) {- var idx = isArray ? parseInt(part, 10) : 0;-- if (value && idx >= value.length) {- throw new Error("Yup.reach cannot resolve an array item at index: " + _part + ", in the path: " + path + ". " + "because there is no value at that index. ");- }-- parent = value;- value = value && value[idx];- schema = schema.innerType;- } // sometimes the array index part of a path doesn't exist: "nested.arr.child"- // in these cases the current part is the next schema and should be processed- // in this iteration. For cases where the index signature is included this- // check will fail and we'll handle the `child` part on the next iteration like normal--- if (!isArray) {- if (!schema.fields || !schema.fields[part]) throw new Error("The schema does not contain the path: " + path + ". " + ("(failed at: " + lastPartDebug + " which is a type: \"" + schema._type + "\")"));- parent = value;- value = value && value[part];- schema = schema.fields[part];- }-- lastPart = part;- lastPartDebug = isBracket ? '[' + _part + ']' : '.' + _part;- });- return {- schema: schema,- parent: parent,- parentPath: lastPart- };-}--function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }--function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }--function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }--var RefSet = /*#__PURE__*/function () {- function RefSet() {- this.list = new Set();- this.refs = new Map();- }-- var _proto = RefSet.prototype;-- _proto.describe = function describe() {- var description = [];-- for (var _iterator = _createForOfIteratorHelperLoose(this.list), _step; !(_step = _iterator()).done;) {- var item = _step.value;- description.push(item);- }-- for (var _iterator2 = _createForOfIteratorHelperLoose(this.refs), _step2; !(_step2 = _iterator2()).done;) {- var _step2$value = _step2.value,- ref = _step2$value[1];- description.push(ref.describe());- }-- return description;- };-- _proto.toArray = function toArray() {- return toArray$1(this.list).concat(toArray$1(this.refs.values()));- };-- _proto.add = function add(value) {- Reference.isRef(value) ? this.refs.set(value.key, value) : this.list.add(value);- };-- _proto.delete = function _delete(value) {- Reference.isRef(value) ? this.refs.delete(value.key) : this.list.delete(value);- };-- _proto.has = function has(value, resolve) {- if (this.list.has(value)) return true;- var item,- values = this.refs.values();-- while (item = values.next(), !item.done) {- if (resolve(item.value) === value) return true;- }-- return false;- };-- _proto.clone = function clone() {- var next = new RefSet();- next.list = new Set(this.list);- next.refs = new Map(this.refs);- return next;- };-- _proto.merge = function merge(newItems, removeItems) {- var next = this.clone();- newItems.list.forEach(function (value) {- return next.add(value);- });- newItems.refs.forEach(function (value) {- return next.add(value);- });- removeItems.list.forEach(function (value) {- return next.delete(value);- });- removeItems.refs.forEach(function (value) {- return next.delete(value);- });- return next;- };-- _createClass$5(RefSet, [{- key: "size",- get: function get() {- return this.list.size + this.refs.size;- }- }]);-- return RefSet;-}();--function SchemaType(options) {- var _this = this;-- if (options === void 0) {- options = {};- }-- if (!(this instanceof SchemaType)) return new SchemaType();- this._deps = [];- this._conditions = [];- this._options = {- abortEarly: true,- recursive: true- };- this._exclusive = Object.create(null);- this._whitelist = new RefSet();- this._blacklist = new RefSet();- this.tests = [];- this.transforms = [];- this.withMutation(function () {- _this.typeError(mixed.notType);- });- if (has(options, 'default')) this._defaultDefault = options.default;- this.type = options.type || 'mixed'; // TODO: remove-- this._type = options.type || 'mixed';-}-var proto = SchemaType.prototype = {- __isYupSchema__: true,- constructor: SchemaType,- clone: function clone() {- var _this2 = this;-- if (this._mutate) return this; // if the nested value is a schema we can skip cloning, since- // they are already immutable-- return cloneDeepWith(this, function (value) {- if (isSchema$1(value) && value !== _this2) return value;- });- },- label: function label(_label) {- var next = this.clone();- next._label = _label;- return next;- },- meta: function meta(obj) {- if (arguments.length === 0) return this._meta;- var next = this.clone();- next._meta = _extends(next._meta || {}, obj);- return next;- },- withMutation: function withMutation(fn) {- var before = this._mutate;- this._mutate = true;- var result = fn(this);- this._mutate = before;- return result;- },- concat: function concat(schema) {- if (!schema || schema === this) return this;- if (schema._type !== this._type && this._type !== 'mixed') throw new TypeError("You cannot `concat()` schema's of different types: " + this._type + " and " + schema._type);- var next = prependDeep(schema.clone(), this); // new undefined default is overridden by old non-undefined one, revert-- if (has(schema, '_default')) next._default = schema._default;- next.tests = this.tests;- next._exclusive = this._exclusive; // manually merge the blacklist/whitelist (the other `schema` takes- // precedence in case of conflicts)-- next._whitelist = this._whitelist.merge(schema._whitelist, schema._blacklist);- next._blacklist = this._blacklist.merge(schema._blacklist, schema._whitelist); // manually add the new tests to ensure- // the deduping logic is consistent-- next.withMutation(function (next) {- schema.tests.forEach(function (fn) {- next.test(fn.OPTIONS);- });- });- return next;- },- isType: function isType(v) {- if (this._nullable && v === null) return true;- return !this._typeCheck || this._typeCheck(v);- },- resolve: function resolve(options) {- var schema = this;-- if (schema._conditions.length) {- var conditions = schema._conditions;- schema = schema.clone();- schema._conditions = [];- schema = conditions.reduce(function (schema, condition) {- return condition.resolve(schema, options);- }, schema);- schema = schema.resolve(options);- }-- return schema;- },- cast: function cast(value, options) {- if (options === void 0) {- options = {};- }-- var resolvedSchema = this.resolve(_extends({}, options, {- value: value- }));-- var result = resolvedSchema._cast(value, options);-- if (value !== undefined && options.assert !== false && resolvedSchema.isType(result) !== true) {- var formattedValue = printValue(value);- var formattedResult = printValue(result);- throw new TypeError("The value of " + (options.path || 'field') + " could not be cast to a value " + ("that satisfies the schema type: \"" + resolvedSchema._type + "\". \n\n") + ("attempted value: " + formattedValue + " \n") + (formattedResult !== formattedValue ? "result of cast: " + formattedResult : ''));- }-- return result;- },- _cast: function _cast(rawValue) {- var _this3 = this;-- var value = rawValue === undefined ? rawValue : this.transforms.reduce(function (value, fn) {- return fn.call(_this3, value, rawValue);- }, rawValue);-- if (value === undefined && has(this, '_default')) {- value = this.default();- }-- return value;- },- _validate: function _validate(_value, options) {- var _this4 = this;-- if (options === void 0) {- options = {};- }-- var value = _value;- var originalValue = options.originalValue != null ? options.originalValue : _value;-- var isStrict = this._option('strict', options);-- var endEarly = this._option('abortEarly', options);-- var sync = options.sync;- var path = options.path;- var label = this._label;-- if (!isStrict) {- value = this._cast(value, _extends({- assert: false- }, options));- } // value is cast, we can check if it meets type requirements--- var validationParams = {- value: value,- path: path,- schema: this,- options: options,- label: label,- originalValue: originalValue,- sync: sync- };-- if (options.from) {- validationParams.from = options.from;- }-- var initialTests = [];- if (this._typeError) initialTests.push(this._typeError(validationParams));- if (this._whitelistError) initialTests.push(this._whitelistError(validationParams));- if (this._blacklistError) initialTests.push(this._blacklistError(validationParams));- return runValidations({- validations: initialTests,- endEarly: endEarly,- value: value,- path: path,- sync: sync- }).then(function (value) {- return runValidations({- path: path,- sync: sync,- value: value,- endEarly: endEarly,- validations: _this4.tests.map(function (fn) {- return fn(validationParams);- })- });- });- },- validate: function validate(value, options) {- if (options === void 0) {- options = {};- }-- var schema = this.resolve(_extends({}, options, {- value: value- }));- return schema._validate(value, options);- },- validateSync: function validateSync(value, options) {- if (options === void 0) {- options = {};- }-- var schema = this.resolve(_extends({}, options, {- value: value- }));- var result, err;-- schema._validate(value, _extends({}, options, {- sync: true- })).then(function (r) {- return result = r;- }).catch(function (e) {- return err = e;- });-- if (err) throw err;- return result;- },- isValid: function isValid(value, options) {- return this.validate(value, options).then(function () {- return true;- }).catch(function (err) {- if (err.name === 'ValidationError') return false;- throw err;- });- },- isValidSync: function isValidSync(value, options) {- try {- this.validateSync(value, options);- return true;- } catch (err) {- if (err.name === 'ValidationError') return false;- throw err;- }- },- getDefault: function getDefault(options) {- if (options === void 0) {- options = {};- }-- var schema = this.resolve(options);- return schema.default();- },- default: function _default(def) {- if (arguments.length === 0) {- var defaultValue = has(this, '_default') ? this._default : this._defaultDefault;- return typeof defaultValue === 'function' ? defaultValue.call(this) : cloneDeepWith(defaultValue);- }-- var next = this.clone();- next._default = def;- return next;- },- strict: function strict(isStrict) {- if (isStrict === void 0) {- isStrict = true;- }-- var next = this.clone();- next._options.strict = isStrict;- return next;- },- _isPresent: function _isPresent(value) {- return value != null;- },- required: function required(message) {- if (message === void 0) {- message = mixed.required;- }-- return this.test({- message: message,- name: 'required',- exclusive: true,- test: function test(value) {- return this.schema._isPresent(value);- }- });- },- notRequired: function notRequired() {- var next = this.clone();- next.tests = next.tests.filter(function (test) {- return test.OPTIONS.name !== 'required';- });- return next;- },- nullable: function nullable(isNullable) {- if (isNullable === void 0) {- isNullable = true;- }-- var next = this.clone();- next._nullable = isNullable;- return next;- },- transform: function transform(fn) {- var next = this.clone();- next.transforms.push(fn);- return next;- },-- /**- * Adds a test function to the schema's queue of tests.- * tests can be exclusive or non-exclusive.- *- * - exclusive tests, will replace any existing tests of the same name.- * - non-exclusive: can be stacked- *- * If a non-exclusive test is added to a schema with an exclusive test of the same name- * the exclusive test is removed and further tests of the same name will be stacked.- *- * If an exclusive test is added to a schema with non-exclusive tests of the same name- * the previous tests are removed and further tests of the same name will replace each other.- */- test: function test() {- var opts;-- if (arguments.length === 1) {- if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'function') {- opts = {- test: arguments.length <= 0 ? undefined : arguments[0]- };- } else {- opts = arguments.length <= 0 ? undefined : arguments[0];- }- } else if (arguments.length === 2) {- opts = {- name: arguments.length <= 0 ? undefined : arguments[0],- test: arguments.length <= 1 ? undefined : arguments[1]- };- } else {- opts = {- name: arguments.length <= 0 ? undefined : arguments[0],- message: arguments.length <= 1 ? undefined : arguments[1],- test: arguments.length <= 2 ? undefined : arguments[2]- };- }-- if (opts.message === undefined) opts.message = mixed.default;- if (typeof opts.test !== 'function') throw new TypeError('`test` is a required parameters');- var next = this.clone();- var validate = createValidation(opts);- var isExclusive = opts.exclusive || opts.name && next._exclusive[opts.name] === true;-- if (opts.exclusive && !opts.name) {- throw new TypeError('Exclusive tests must provide a unique `name` identifying the test');- }-- next._exclusive[opts.name] = !!opts.exclusive;- next.tests = next.tests.filter(function (fn) {- if (fn.OPTIONS.name === opts.name) {- if (isExclusive) return false;- if (fn.OPTIONS.test === validate.OPTIONS.test) return false;- }-- return true;- });- next.tests.push(validate);- return next;- },- when: function when(keys, options) {- if (arguments.length === 1) {- options = keys;- keys = '.';- }-- var next = this.clone(),- deps = [].concat(keys).map(function (key) {- return new Reference(key);- });- deps.forEach(function (dep) {- if (dep.isSibling) next._deps.push(dep.key);- });-- next._conditions.push(new Condition(deps, options));-- return next;- },- typeError: function typeError(message) {- var next = this.clone();- next._typeError = createValidation({- message: message,- name: 'typeError',- test: function test(value) {- if (value !== undefined && !this.schema.isType(value)) return this.createError({- params: {- type: this.schema._type- }- });- return true;- }- });- return next;- },- oneOf: function oneOf(enums, message) {- if (message === void 0) {- message = mixed.oneOf;- }-- var next = this.clone();- enums.forEach(function (val) {- next._whitelist.add(val);-- next._blacklist.delete(val);- });- next._whitelistError = createValidation({- message: message,- name: 'oneOf',- test: function test(value) {- if (value === undefined) return true;- var valids = this.schema._whitelist;- return valids.has(value, this.resolve) ? true : this.createError({- params: {- values: valids.toArray().join(', ')- }- });- }- });- return next;- },- notOneOf: function notOneOf(enums, message) {- if (message === void 0) {- message = mixed.notOneOf;- }-- var next = this.clone();- enums.forEach(function (val) {- next._blacklist.add(val);-- next._whitelist.delete(val);- });- next._blacklistError = createValidation({- message: message,- name: 'notOneOf',- test: function test(value) {- var invalids = this.schema._blacklist;- if (invalids.has(value, this.resolve)) return this.createError({- params: {- values: invalids.toArray().join(', ')- }- });- return true;- }- });- return next;- },- strip: function strip(_strip) {- if (_strip === void 0) {- _strip = true;- }-- var next = this.clone();- next._strip = _strip;- return next;- },- _option: function _option(key, overrides) {- return has(overrides, key) ? overrides[key] : this._options[key];- },- describe: function describe() {- var next = this.clone();- var description = {- type: next._type,- meta: next._meta,- label: next._label,- tests: next.tests.map(function (fn) {- return {- name: fn.OPTIONS.name,- params: fn.OPTIONS.params- };- }).filter(function (n, idx, list) {- return list.findIndex(function (c) {- return c.name === n.name;- }) === idx;- })- };- if (next._whitelist.size) description.oneOf = next._whitelist.describe();- if (next._blacklist.size) description.notOneOf = next._blacklist.describe();- return description;- },- defined: function defined(message) {- if (message === void 0) {- message = mixed.defined;- }-- return this.nullable().test({- message: message,- name: 'defined',- exclusive: true,- test: function test(value) {- return value !== undefined;- }- });- }-};--var _loop = function _loop() {- var method = _arr[_i];-- proto[method + "At"] = function (path, value, options) {- if (options === void 0) {- options = {};- }-- var _getIn = getIn(this, path, value, options.context),- parent = _getIn.parent,- parentPath = _getIn.parentPath,- schema = _getIn.schema;-- return schema[method](parent && parent[parentPath], _extends({}, options, {- parent: parent,- path: path- }));- };-};--for (var _i = 0, _arr = ['validate', 'validateSync']; _i < _arr.length; _i++) {- _loop();-}--for (var _i2 = 0, _arr2 = ['equals', 'is']; _i2 < _arr2.length; _i2++) {- var alias = _arr2[_i2];- proto[alias] = proto.oneOf;-}--for (var _i3 = 0, _arr3 = ['not', 'nope']; _i3 < _arr3.length; _i3++) {- var _alias = _arr3[_i3];- proto[_alias] = proto.notOneOf;-}--proto.optional = proto.notRequired;--function inherits(ctor, superCtor, spec) {- ctor.prototype = Object.create(superCtor.prototype, {- constructor: {- value: ctor,- enumerable: false,- writable: true,- configurable: true- }- });-- _extends(ctor.prototype, spec);-}--function BooleanSchema() {- var _this = this;-- if (!(this instanceof BooleanSchema)) return new BooleanSchema();- SchemaType.call(this, {- type: 'boolean'- });- this.withMutation(function () {- _this.transform(function (value) {- if (!this.isType(value)) {- if (/^(true|1)$/i.test(value)) return true;- if (/^(false|0)$/i.test(value)) return false;- }-- return value;- });- });-}--inherits(BooleanSchema, SchemaType, {- _typeCheck: function _typeCheck(v) {- if (v instanceof Boolean) v = v.valueOf();- return typeof v === 'boolean';- }-});--var isAbsent = (function (value) {- return value == null;-});--var rEmail = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; // eslint-disable-next-line--var rUrl = /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i; // eslint-disable-next-line--var rUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i;--var isTrimmed = function isTrimmed(value) {- return isAbsent(value) || value === value.trim();-};--function StringSchema() {- var _this = this;-- if (!(this instanceof StringSchema)) return new StringSchema();- SchemaType.call(this, {- type: 'string'- });- this.withMutation(function () {- _this.transform(function (value) {- if (this.isType(value)) return value;- return value != null && value.toString ? value.toString() : value;- });- });-}-inherits(StringSchema, SchemaType, {- _typeCheck: function _typeCheck(value) {- if (value instanceof String) value = value.valueOf();- return typeof value === 'string';- },- _isPresent: function _isPresent(value) {- return SchemaType.prototype._isPresent.call(this, value) && value.length > 0;- },- length: function length(_length, message) {- if (message === void 0) {- message = string.length;- }-- return this.test({- message: message,- name: 'length',- exclusive: true,- params: {- length: _length- },- test: function test(value) {- return isAbsent(value) || value.length === this.resolve(_length);- }- });- },- min: function min(_min, message) {- if (message === void 0) {- message = string.min;- }-- return this.test({- message: message,- name: 'min',- exclusive: true,- params: {- min: _min- },- test: function test(value) {- return isAbsent(value) || value.length >= this.resolve(_min);- }- });- },- max: function max(_max, message) {- if (message === void 0) {- message = string.max;- }-- return this.test({- name: 'max',- exclusive: true,- message: message,- params: {- max: _max- },- test: function test(value) {- return isAbsent(value) || value.length <= this.resolve(_max);- }- });- },- matches: function matches(regex, options) {- var excludeEmptyString = false;- var message;- var name;-- if (options) {- if (typeof options === 'object') {- excludeEmptyString = options.excludeEmptyString;- message = options.message;- name = options.name;- } else {- message = options;- }- }-- return this.test({- name: name || 'matches',- message: message || string.matches,- params: {- regex: regex- },- test: function test(value) {- return isAbsent(value) || value === '' && excludeEmptyString || value.search(regex) !== -1;- }- });- },- email: function email(message) {- if (message === void 0) {- message = string.email;- }-- return this.matches(rEmail, {- name: 'email',- message: message,- excludeEmptyString: true- });- },- url: function url(message) {- if (message === void 0) {- message = string.url;- }-- return this.matches(rUrl, {- name: 'url',- message: message,- excludeEmptyString: true- });- },- uuid: function uuid(message) {- if (message === void 0) {- message = string.uuid;- }-- return this.matches(rUUID, {- name: 'uuid',- message: message,- excludeEmptyString: false- });- },- //-- transforms --- ensure: function ensure() {- return this.default('').transform(function (val) {- return val === null ? '' : val;- });- },- trim: function trim(message) {- if (message === void 0) {- message = string.trim;- }-- return this.transform(function (val) {- return val != null ? val.trim() : val;- }).test({- message: message,- name: 'trim',- test: isTrimmed- });- },- lowercase: function lowercase(message) {- if (message === void 0) {- message = string.lowercase;- }-- return this.transform(function (value) {- return !isAbsent(value) ? value.toLowerCase() : value;- }).test({- message: message,- name: 'string_case',- exclusive: true,- test: function test(value) {- return isAbsent(value) || value === value.toLowerCase();- }- });- },- uppercase: function uppercase(message) {- if (message === void 0) {- message = string.uppercase;+var path = require('path');+var fs$2 = require('fs');+var constants$4 = require('constants');+var Stream$1 = require('stream');+var util = require('util');+var assert = require('assert');+var process$1 = require('process');+var Module = require('module');+var require$$1 = require('os');+var EventEmitter = require('events');+var http = require('http');+var Url = require('url');+var https = require('https');+var zlib = require('zlib');+var crypto = require('crypto');+var net = require('net');+var tls = require('tls');+var websocket$1 = require('websocket');++function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }++function _interopNamespace(e) {+ if (e && e.__esModule) return e;+ var n = Object.create(null);+ if (e) {+ Object.keys(e).forEach(function (k) {+ if (k !== 'default') {+ var d = Object.getOwnPropertyDescriptor(e, k);+ Object.defineProperty(n, k, d.get ? d : {+ enumerable: true,+ get: function () {+ return e[k];+ }+ });+ }+ });+ }+ n['default'] = e;+ return Object.freeze(n);+}++var path__default = /*#__PURE__*/_interopDefaultLegacy(path);+var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$2);+var constants__default = /*#__PURE__*/_interopDefaultLegacy(constants$4);+var Stream__default = /*#__PURE__*/_interopDefaultLegacy(Stream$1);+var util__default = /*#__PURE__*/_interopDefaultLegacy(util);+var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);+var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module);+var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);+var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);+var http__default = /*#__PURE__*/_interopDefaultLegacy(http);+var Url__default = /*#__PURE__*/_interopDefaultLegacy(Url);+var https__default = /*#__PURE__*/_interopDefaultLegacy(https);+var zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib);+var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);+var net__default = /*#__PURE__*/_interopDefaultLegacy(net);+var tls__default = /*#__PURE__*/_interopDefaultLegacy(tls);++/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(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); +}; + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}++/**+ * Note: This file is autogenerated using "resources/gen-version.js" script and+ * automatically updated by "npm version" command.+ */++/**+ * A string containing the version of the GraphQL.js library+ */+var version = '15.3.0';+/**+ * An object containing the components of the GraphQL.js version string+ */++var versionInfo = Object.freeze({+ major: 15,+ minor: 3,+ patch: 0,+ preReleaseTag: null+});++/**+ * Returns true if the value acts like a Promise, i.e. has a "then" function,+ * otherwise returns false.+ */+// eslint-disable-next-line no-redeclare+function isPromise(value) {+ return typeof (value === null || value === void 0 ? void 0 : value.then) === 'function';+}++// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')+var nodejsCustomInspectSymbol = typeof Symbol === 'function' && typeof Symbol.for === 'function' ? Symbol.for('nodejs.util.inspect.custom') : undefined;++function _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); }+var MAX_ARRAY_LENGTH = 10;+var MAX_RECURSIVE_DEPTH = 2;+/**+ * Used to print values in error messages.+ */++function inspect(value) {+ return formatValue(value, []);+}++function formatValue(value, seenValues) {+ switch (_typeof(value)) {+ case 'string':+ return JSON.stringify(value);++ case 'function':+ return value.name ? "[function ".concat(value.name, "]") : '[function]';++ case 'object':+ if (value === null) {+ return 'null';+ }++ return formatObjectValue(value, seenValues);++ default:+ return String(value);+ }+}++function formatObjectValue(value, previouslySeenValues) {+ if (previouslySeenValues.indexOf(value) !== -1) {+ return '[Circular]';+ }++ var seenValues = [].concat(previouslySeenValues, [value]);+ var customInspectFn = getCustomFn(value);++ if (customInspectFn !== undefined) {+ // $FlowFixMe(>=0.90.0)+ var customValue = customInspectFn.call(value); // check for infinite recursion++ if (customValue !== value) {+ return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);+ }+ } else if (Array.isArray(value)) {+ return formatArray(value, seenValues);+ }++ return formatObject(value, seenValues);+}++function formatObject(object, seenValues) {+ var keys = Object.keys(object);++ if (keys.length === 0) {+ return '{}';+ }++ if (seenValues.length > MAX_RECURSIVE_DEPTH) {+ return '[' + getObjectTag(object) + ']';+ }++ var properties = keys.map(function (key) {+ var value = formatValue(object[key], seenValues);+ return key + ': ' + value;+ });+ return '{ ' + properties.join(', ') + ' }';+}++function formatArray(array, seenValues) {+ if (array.length === 0) {+ return '[]';+ }++ if (seenValues.length > MAX_RECURSIVE_DEPTH) {+ return '[Array]';+ }++ var len = Math.min(MAX_ARRAY_LENGTH, array.length);+ var remaining = array.length - len;+ var items = [];++ for (var i = 0; i < len; ++i) {+ items.push(formatValue(array[i], seenValues));+ }++ if (remaining === 1) {+ items.push('... 1 more item');+ } else if (remaining > 1) {+ items.push("... ".concat(remaining, " more items"));+ }++ return '[' + items.join(', ') + ']';+}++function getCustomFn(object) {+ var customInspectFn = object[String(nodejsCustomInspectSymbol)];++ if (typeof customInspectFn === 'function') {+ return customInspectFn;+ }++ if (typeof object.inspect === 'function') {+ return object.inspect;+ }+}++function getObjectTag(object) {+ var tag = Object.prototype.toString.call(object).replace(/^\[object /, '').replace(/]$/, '');++ if (tag === 'Object' && typeof object.constructor === 'function') {+ var name = object.constructor.name;++ if (typeof name === 'string' && name !== '') {+ return name;+ }+ }++ return tag;+}++function devAssert(condition, message) {+ var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')++ if (!booleanCondition) {+ throw new Error(message);+ }+}++function _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); }++/**+ * Return true if `value` is object-like. A value is object-like if it's not+ * `null` and has a `typeof` result of "object".+ */+function isObjectLike(value) {+ return _typeof$1(value) == 'object' && value !== null;+}++// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator+// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')+var SYMBOL_ITERATOR = typeof Symbol === 'function' ? Symbol.iterator : '@@iterator'; // In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator+// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')++var SYMBOL_ASYNC_ITERATOR = // $FlowFixMe Flow doesn't define `Symbol.asyncIterator` yet+typeof Symbol === 'function' ? Symbol.asyncIterator : '@@asyncIterator'; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')++var SYMBOL_TO_STRING_TAG = // $FlowFixMe Flow doesn't define `Symbol.toStringTag` yet+typeof Symbol === 'function' ? Symbol.toStringTag : '@@toStringTag';++/**+ * Represents a location in a Source.+ */++/**+ * Takes a Source and a UTF-8 character offset, and returns the corresponding+ * line and column as a SourceLocation.+ */+function getLocation(source, position) {+ var lineRegexp = /\r\n|[\n\r]/g;+ var line = 1;+ var column = position + 1;+ var match;++ while ((match = lineRegexp.exec(source.body)) && match.index < position) {+ line += 1;+ column = position + 1 - (match.index + match[0].length);+ }++ return {+ line: line,+ column: column+ };+}++/**+ * Render a helpful description of the location in the GraphQL Source document.+ */++function printLocation(location) {+ return printSourceLocation(location.source, getLocation(location.source, location.start));+}+/**+ * Render a helpful description of the location in the GraphQL Source document.+ */++function printSourceLocation(source, sourceLocation) {+ var firstLineColumnOffset = source.locationOffset.column - 1;+ var body = whitespace(firstLineColumnOffset) + source.body;+ var lineIndex = sourceLocation.line - 1;+ var lineOffset = source.locationOffset.line - 1;+ var lineNum = sourceLocation.line + lineOffset;+ var columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;+ var columnNum = sourceLocation.column + columnOffset;+ var locationStr = "".concat(source.name, ":").concat(lineNum, ":").concat(columnNum, "\n");+ var lines = body.split(/\r\n|[\n\r]/g);+ var locationLine = lines[lineIndex]; // Special case for minified documents++ if (locationLine.length > 120) {+ var subLineIndex = Math.floor(columnNum / 80);+ var subLineColumnNum = columnNum % 80;+ var subLines = [];++ for (var i = 0; i < locationLine.length; i += 80) {+ subLines.push(locationLine.slice(i, i + 80));+ }++ return locationStr + printPrefixedLines([["".concat(lineNum), subLines[0]]].concat(subLines.slice(1, subLineIndex + 1).map(function (subLine) {+ return ['', subLine];+ }), [[' ', whitespace(subLineColumnNum - 1) + '^'], ['', subLines[subLineIndex + 1]]]));+ }++ return locationStr + printPrefixedLines([// Lines specified like this: ["prefix", "string"],+ ["".concat(lineNum - 1), lines[lineIndex - 1]], ["".concat(lineNum), locationLine], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1), lines[lineIndex + 1]]]);+}++function printPrefixedLines(lines) {+ var existingLines = lines.filter(function (_ref) {+ var _ = _ref[0],+ line = _ref[1];+ return line !== undefined;+ });+ var padLen = Math.max.apply(Math, existingLines.map(function (_ref2) {+ var prefix = _ref2[0];+ return prefix.length;+ }));+ return existingLines.map(function (_ref3) {+ var prefix = _ref3[0],+ line = _ref3[1];+ return leftPad(padLen, prefix) + (line ? ' | ' + line : ' |');+ }).join('\n');+}++function whitespace(len) {+ return Array(len + 1).join(' ');+}++function leftPad(len, str) {+ return whitespace(len - str.length) + str;+}++function _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); }++function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }++function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }++function _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); }++function _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); }; }++function _possibleConstructorReturn(self, call) { if (call && (_typeof$2(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }++function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }++function _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); }++function _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); }++function _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; } }++function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }++function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }++function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }+/**+ * A GraphQLError describes an Error found during the parse, validate, or+ * execute phases of performing a GraphQL operation. In addition to a message+ * and stack trace, it also includes information about the locations in a+ * GraphQL document and/or execution result that correspond to the Error.+ */++var GraphQLError = /*#__PURE__*/function (_Error) {+ _inherits(GraphQLError, _Error);++ var _super = _createSuper(GraphQLError);++ /**+ * A message describing the Error for debugging purposes.+ *+ * Enumerable, and appears in the result of JSON.stringify().+ *+ * Note: should be treated as readonly, despite invariant usage.+ */++ /**+ * An array of { line, column } locations within the source GraphQL document+ * which correspond to this error.+ *+ * Errors during validation often contain multiple locations, for example to+ * point out two things with the same name. Errors during execution include a+ * single location, the field which produced the error.+ *+ * Enumerable, and appears in the result of JSON.stringify().+ */++ /**+ * An array describing the JSON-path into the execution response which+ * corresponds to this error. Only included for errors during execution.+ *+ * Enumerable, and appears in the result of JSON.stringify().+ */++ /**+ * An array of GraphQL AST Nodes corresponding to this error.+ */++ /**+ * The source GraphQL document for the first location of this error.+ *+ * Note that if this Error represents more than one node, the source may not+ * represent nodes after the first node.+ */++ /**+ * An array of character offsets within the source GraphQL document+ * which correspond to this error.+ */++ /**+ * The original error thrown from a field resolver during execution.+ */++ /**+ * Extension fields to add to the formatted error.+ */+ function GraphQLError(message, nodes, source, positions, path, originalError, extensions) {+ var _locations2, _source2, _positions2, _extensions2;++ var _this;++ _classCallCheck(this, GraphQLError);++ _this = _super.call(this, message); // Compute list of blame nodes.++ var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions.+++ var _source = source;++ if (!_source && _nodes) {+ var _nodes$0$loc;++ _source = (_nodes$0$loc = _nodes[0].loc) === null || _nodes$0$loc === void 0 ? void 0 : _nodes$0$loc.source;+ }++ var _positions = positions;++ if (!_positions && _nodes) {+ _positions = _nodes.reduce(function (list, node) {+ if (node.loc) {+ list.push(node.loc.start);+ }++ return list;+ }, []);+ }++ if (_positions && _positions.length === 0) {+ _positions = undefined;+ }++ var _locations;++ if (positions && source) {+ _locations = positions.map(function (pos) {+ return getLocation(source, pos);+ });+ } else if (_nodes) {+ _locations = _nodes.reduce(function (list, node) {+ if (node.loc) {+ list.push(getLocation(node.loc.source, node.loc.start));+ }++ return list;+ }, []);+ }++ var _extensions = extensions;++ if (_extensions == null && originalError != null) {+ var originalExtensions = originalError.extensions;++ if (isObjectLike(originalExtensions)) {+ _extensions = originalExtensions;+ }+ }++ Object.defineProperties(_assertThisInitialized(_this), {+ name: {+ value: 'GraphQLError'+ },+ message: {+ value: message,+ // By being enumerable, JSON.stringify will include `message` in the+ // resulting output. This ensures that the simplest possible GraphQL+ // service adheres to the spec.+ enumerable: true,+ writable: true+ },+ locations: {+ // Coercing falsy values to undefined ensures they will not be included+ // in JSON.stringify() when not provided.+ value: (_locations2 = _locations) !== null && _locations2 !== void 0 ? _locations2 : undefined,+ // By being enumerable, JSON.stringify will include `locations` in the+ // resulting output. This ensures that the simplest possible GraphQL+ // service adheres to the spec.+ enumerable: _locations != null+ },+ path: {+ // Coercing falsy values to undefined ensures they will not be included+ // in JSON.stringify() when not provided.+ value: path !== null && path !== void 0 ? path : undefined,+ // By being enumerable, JSON.stringify will include `path` in the+ // resulting output. This ensures that the simplest possible GraphQL+ // service adheres to the spec.+ enumerable: path != null+ },+ nodes: {+ value: _nodes !== null && _nodes !== void 0 ? _nodes : undefined+ },+ source: {+ value: (_source2 = _source) !== null && _source2 !== void 0 ? _source2 : undefined+ },+ positions: {+ value: (_positions2 = _positions) !== null && _positions2 !== void 0 ? _positions2 : undefined+ },+ originalError: {+ value: originalError+ },+ extensions: {+ // Coercing falsy values to undefined ensures they will not be included+ // in JSON.stringify() when not provided.+ value: (_extensions2 = _extensions) !== null && _extensions2 !== void 0 ? _extensions2 : undefined,+ // By being enumerable, JSON.stringify will include `path` in the+ // resulting output. This ensures that the simplest possible GraphQL+ // service adheres to the spec.+ enumerable: _extensions != null+ }+ }); // Include (non-enumerable) stack trace.++ if (originalError === null || originalError === void 0 ? void 0 : originalError.stack) {+ Object.defineProperty(_assertThisInitialized(_this), 'stack', {+ value: originalError.stack,+ writable: true,+ configurable: true+ });+ return _possibleConstructorReturn(_this);+ } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')+++ if (Error.captureStackTrace) {+ Error.captureStackTrace(_assertThisInitialized(_this), GraphQLError);+ } else {+ Object.defineProperty(_assertThisInitialized(_this), 'stack', {+ value: Error().stack,+ writable: true,+ configurable: true+ });+ }++ return _this;+ }++ _createClass(GraphQLError, [{+ key: "toString",+ value: function toString() {+ return printError(this);+ } // FIXME: workaround to not break chai comparisons, should be remove in v16+ // $FlowFixMe Flow doesn't support computed properties yet++ }, {+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'Object';+ }+ }]);++ return GraphQLError;+}( /*#__PURE__*/_wrapNativeSuper(Error));+/**+ * Prints a GraphQLError to a string, representing useful location information+ * about the error's position in the source.+ */++function printError(error) {+ var output = error.message;++ if (error.nodes) {+ for (var _i2 = 0, _error$nodes2 = error.nodes; _i2 < _error$nodes2.length; _i2++) {+ var node = _error$nodes2[_i2];++ if (node.loc) {+ output += '\n\n' + printLocation(node.loc);+ }+ }+ } else if (error.source && error.locations) {+ for (var _i4 = 0, _error$locations2 = error.locations; _i4 < _error$locations2.length; _i4++) {+ var location = _error$locations2[_i4];+ output += '\n\n' + printSourceLocation(error.source, location);+ }+ }++ return output;+}++/**+ * Produces a GraphQLError representing a syntax error, containing useful+ * descriptive information about the syntax error's position in the source.+ */++function syntaxError(source, position, description) {+ return new GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]);+}++/**+ * The set of allowed kind values for AST nodes.+ */+var Kind = Object.freeze({+ // Name+ NAME: 'Name',+ // Document+ DOCUMENT: 'Document',+ OPERATION_DEFINITION: 'OperationDefinition',+ VARIABLE_DEFINITION: 'VariableDefinition',+ SELECTION_SET: 'SelectionSet',+ FIELD: 'Field',+ ARGUMENT: 'Argument',+ // Fragments+ FRAGMENT_SPREAD: 'FragmentSpread',+ INLINE_FRAGMENT: 'InlineFragment',+ FRAGMENT_DEFINITION: 'FragmentDefinition',+ // Values+ VARIABLE: 'Variable',+ INT: 'IntValue',+ FLOAT: 'FloatValue',+ STRING: 'StringValue',+ BOOLEAN: 'BooleanValue',+ NULL: 'NullValue',+ ENUM: 'EnumValue',+ LIST: 'ListValue',+ OBJECT: 'ObjectValue',+ OBJECT_FIELD: 'ObjectField',+ // Directives+ DIRECTIVE: 'Directive',+ // Types+ NAMED_TYPE: 'NamedType',+ LIST_TYPE: 'ListType',+ NON_NULL_TYPE: 'NonNullType',+ // Type System Definitions+ SCHEMA_DEFINITION: 'SchemaDefinition',+ OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',+ // Type Definitions+ SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',+ OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',+ FIELD_DEFINITION: 'FieldDefinition',+ INPUT_VALUE_DEFINITION: 'InputValueDefinition',+ INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',+ UNION_TYPE_DEFINITION: 'UnionTypeDefinition',+ ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',+ ENUM_VALUE_DEFINITION: 'EnumValueDefinition',+ INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',+ // Directive Definitions+ DIRECTIVE_DEFINITION: 'DirectiveDefinition',+ // Type System Extensions+ SCHEMA_EXTENSION: 'SchemaExtension',+ // Type Extensions+ SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',+ OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',+ INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',+ UNION_TYPE_EXTENSION: 'UnionTypeExtension',+ ENUM_TYPE_EXTENSION: 'EnumTypeExtension',+ INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension'+});+/**+ * The enum type representing the possible kind values of AST nodes.+ */++function invariant(condition, message) {+ var booleanCondition = Boolean(condition); // istanbul ignore else (See transformation done in './resources/inlineInvariant.js')++ if (!booleanCondition) {+ throw new Error(message != null ? message : 'Unexpected invariant triggered.');+ }+}++/**+ * The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON`+ */++function defineInspect(classObject) {+ var fn = classObject.prototype.toJSON;+ typeof fn === 'function' || invariant(0);+ classObject.prototype.inspect = fn; // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2317')++ if (nodejsCustomInspectSymbol) {+ classObject.prototype[nodejsCustomInspectSymbol] = fn;+ }+}++/**+ * Contains a range of UTF-8 character offsets and token references that+ * identify the region of the source from which the AST derived.+ */+var Location = /*#__PURE__*/function () {+ /**+ * The character offset at which this Node begins.+ */++ /**+ * The character offset at which this Node ends.+ */++ /**+ * The Token at which this Node begins.+ */++ /**+ * The Token at which this Node ends.+ */++ /**+ * The Source document the AST represents.+ */+ function Location(startToken, endToken, source) {+ this.start = startToken.start;+ this.end = endToken.end;+ this.startToken = startToken;+ this.endToken = endToken;+ this.source = source;+ }++ var _proto = Location.prototype;++ _proto.toJSON = function toJSON() {+ return {+ start: this.start,+ end: this.end+ };+ };++ return Location;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(Location);+/**+ * Represents a range of characters represented by a lexical token+ * within a Source.+ */++var Token = /*#__PURE__*/function () {+ /**+ * The kind of Token.+ */++ /**+ * The character offset at which this Node begins.+ */++ /**+ * The character offset at which this Node ends.+ */++ /**+ * The 1-indexed line number on which this Token appears.+ */++ /**+ * The 1-indexed column number at which this Token begins.+ */++ /**+ * For non-punctuation tokens, represents the interpreted value of the token.+ */++ /**+ * Tokens exist as nodes in a double-linked-list amongst all tokens+ * including ignored tokens. <SOF> is always the first node and <EOF>+ * the last.+ */+ function Token(kind, start, end, line, column, prev, value) {+ this.kind = kind;+ this.start = start;+ this.end = end;+ this.line = line;+ this.column = column;+ this.value = value;+ this.prev = prev;+ this.next = null;+ }++ var _proto2 = Token.prototype;++ _proto2.toJSON = function toJSON() {+ return {+ kind: this.kind,+ value: this.value,+ line: this.line,+ column: this.column+ };+ };++ return Token;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(Token);+/**+ * @internal+ */++function isNode(maybeNode) {+ return maybeNode != null && typeof maybeNode.kind === 'string';+}+/**+ * The list of all possible AST node types.+ */++function _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); } }++function _createClass$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); return Constructor; }++/**+ * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are+ * optional, but they are useful for clients who store GraphQL documents in source files.+ * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might+ * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`.+ * The `line` and `column` properties in `locationOffset` are 1-indexed.+ */+var Source = /*#__PURE__*/function () {+ function Source(body) {+ var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GraphQL request';+ var locationOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {+ line: 1,+ column: 1+ };+ this.body = body;+ this.name = name;+ this.locationOffset = locationOffset;+ this.locationOffset.line > 0 || devAssert(0, 'line in locationOffset is 1-indexed and must be positive.');+ this.locationOffset.column > 0 || devAssert(0, 'column in locationOffset is 1-indexed and must be positive.');+ } // $FlowFixMe Flow doesn't support computed properties yet+++ _createClass$1(Source, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'Source';+ }+ }]);++ return Source;+}();++/**+ * An exported enum describing the different kinds of tokens that the+ * lexer emits.+ */+var TokenKind = Object.freeze({+ SOF: '<SOF>',+ EOF: '<EOF>',+ BANG: '!',+ DOLLAR: '$',+ AMP: '&',+ PAREN_L: '(',+ PAREN_R: ')',+ SPREAD: '...',+ COLON: ':',+ EQUALS: '=',+ AT: '@',+ BRACKET_L: '[',+ BRACKET_R: ']',+ BRACE_L: '{',+ PIPE: '|',+ BRACE_R: '}',+ NAME: 'Name',+ INT: 'Int',+ FLOAT: 'Float',+ STRING: 'String',+ BLOCK_STRING: 'BlockString',+ COMMENT: 'Comment'+});+/**+ * The enum type representing the token kinds values.+ */++/**+ * The set of allowed directive location values.+ */+var DirectiveLocation = Object.freeze({+ // Request Definitions+ QUERY: 'QUERY',+ MUTATION: 'MUTATION',+ SUBSCRIPTION: 'SUBSCRIPTION',+ FIELD: 'FIELD',+ FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION',+ FRAGMENT_SPREAD: 'FRAGMENT_SPREAD',+ INLINE_FRAGMENT: 'INLINE_FRAGMENT',+ VARIABLE_DEFINITION: 'VARIABLE_DEFINITION',+ // Type System Definitions+ SCHEMA: 'SCHEMA',+ SCALAR: 'SCALAR',+ OBJECT: 'OBJECT',+ FIELD_DEFINITION: 'FIELD_DEFINITION',+ ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION',+ INTERFACE: 'INTERFACE',+ UNION: 'UNION',+ ENUM: 'ENUM',+ ENUM_VALUE: 'ENUM_VALUE',+ INPUT_OBJECT: 'INPUT_OBJECT',+ INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION'+});+/**+ * The enum type representing the directive location values.+ */++/**+ * Produces the value of a block string from its parsed raw value, similar to+ * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.+ *+ * This implements the GraphQL spec's BlockStringValue() static algorithm.+ *+ * @internal+ */+function dedentBlockStringValue(rawString) {+ // Expand a block string's raw value into independent lines.+ var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.++ var commonIndent = getBlockStringIndentation(lines);++ if (commonIndent !== 0) {+ for (var i = 1; i < lines.length; i++) {+ lines[i] = lines[i].slice(commonIndent);+ }+ } // Remove leading and trailing blank lines.+++ while (lines.length > 0 && isBlank(lines[0])) {+ lines.shift();+ }++ while (lines.length > 0 && isBlank(lines[lines.length - 1])) {+ lines.pop();+ } // Return a string of the lines joined with U+000A.+++ return lines.join('\n');+}+/**+ * @internal+ */++function getBlockStringIndentation(lines) {+ var commonIndent = null;++ for (var i = 1; i < lines.length; i++) {+ var line = lines[i];+ var indent = leadingWhitespace(line);++ if (indent === line.length) {+ continue; // skip empty lines+ }++ if (commonIndent === null || indent < commonIndent) {+ commonIndent = indent;++ if (commonIndent === 0) {+ break;+ }+ }+ }++ return commonIndent === null ? 0 : commonIndent;+}++function leadingWhitespace(str) {+ var i = 0;++ while (i < str.length && (str[i] === ' ' || str[i] === '\t')) {+ i++;+ }++ return i;+}++function isBlank(str) {+ return leadingWhitespace(str) === str.length;+}+/**+ * 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.+ *+ * @internal+ */+++function printBlockString(value) {+ var indentation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';+ var preferMultipleLines = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;+ var isSingleLine = value.indexOf('\n') === -1;+ var hasLeadingSpace = value[0] === ' ' || value[0] === '\t';+ var hasTrailingQuote = value[value.length - 1] === '"';+ var hasTrailingSlash = value[value.length - 1] === '\\';+ var printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines;+ var result = ''; // Format a multi-line block quote to account for leading space.++ if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) {+ result += '\n' + indentation;+ }++ result += indentation ? value.replace(/\n/g, '\n' + indentation) : value;++ if (printAsMultipleLines) {+ result += '\n';+ }++ return '"""' + result.replace(/"""/g, '\\"""') + '"""';+}++/**+ * Given a Source object, creates a Lexer for that source.+ * A Lexer is a stateful stream generator in that every time+ * it is advanced, it returns the next token in the Source. Assuming the+ * source lexes, the final Token emitted by the lexer will be of kind+ * EOF, after which the lexer will repeatedly return the same EOF token+ * whenever called.+ */++var Lexer = /*#__PURE__*/function () {+ /**+ * The previously focused non-ignored token.+ */++ /**+ * The currently focused non-ignored token.+ */++ /**+ * The (1-indexed) line containing the current token.+ */++ /**+ * The character offset at which the current line begins.+ */+ function Lexer(source) {+ var startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0, null);+ this.source = source;+ this.lastToken = startOfFileToken;+ this.token = startOfFileToken;+ this.line = 1;+ this.lineStart = 0;+ }+ /**+ * Advances the token stream to the next non-ignored token.+ */+++ var _proto = Lexer.prototype;++ _proto.advance = function advance() {+ this.lastToken = this.token;+ var token = this.token = this.lookahead();+ return token;+ }+ /**+ * Looks ahead and returns the next non-ignored token, but does not change+ * the state of Lexer.+ */+ ;++ _proto.lookahead = function lookahead() {+ var token = this.token;++ if (token.kind !== TokenKind.EOF) {+ do {+ var _token$next;++ // Note: next is only mutable during parsing, so we cast to allow this.+ token = (_token$next = token.next) !== null && _token$next !== void 0 ? _token$next : token.next = readToken(this, token);+ } while (token.kind === TokenKind.COMMENT);+ }++ return token;+ };++ return Lexer;+}();+/**+ * @internal+ */++function isPunctuatorTokenKind(kind) {+ return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;+}++function printCharCode(code) {+ return (// NaN/undefined represents access beyond the end of the file.+ isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII.+ code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form.+ "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"")+ );+}+/**+ * Gets the next token from the source starting at the given position.+ *+ * This skips over whitespace until it finds the next lexable token, then lexes+ * punctuators immediately or calls the appropriate helper function for more+ * complicated tokens.+ */+++function readToken(lexer, prev) {+ var source = lexer.source;+ var body = source.body;+ var bodyLength = body.length;+ var pos = positionAfterWhitespace(body, prev.end, lexer);+ var line = lexer.line;+ var col = 1 + pos - lexer.lineStart;++ if (pos >= bodyLength) {+ return new Token(TokenKind.EOF, bodyLength, bodyLength, line, col, prev);+ }++ var code = body.charCodeAt(pos); // SourceCharacter++ switch (code) {+ // !+ case 33:+ return new Token(TokenKind.BANG, pos, pos + 1, line, col, prev);+ // #++ case 35:+ return readComment(source, pos, line, col, prev);+ // $++ case 36:+ return new Token(TokenKind.DOLLAR, pos, pos + 1, line, col, prev);+ // &++ case 38:+ return new Token(TokenKind.AMP, pos, pos + 1, line, col, prev);+ // (++ case 40:+ return new Token(TokenKind.PAREN_L, pos, pos + 1, line, col, prev);+ // )++ case 41:+ return new Token(TokenKind.PAREN_R, pos, pos + 1, line, col, prev);+ // .++ case 46:+ if (body.charCodeAt(pos + 1) === 46 && body.charCodeAt(pos + 2) === 46) {+ return new Token(TokenKind.SPREAD, pos, pos + 3, line, col, prev);+ }++ break;+ // :++ case 58:+ return new Token(TokenKind.COLON, pos, pos + 1, line, col, prev);+ // =++ case 61:+ return new Token(TokenKind.EQUALS, pos, pos + 1, line, col, prev);+ // @++ case 64:+ return new Token(TokenKind.AT, pos, pos + 1, line, col, prev);+ // [++ case 91:+ return new Token(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev);+ // ]++ case 93:+ return new Token(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev);+ // {++ case 123:+ return new Token(TokenKind.BRACE_L, pos, pos + 1, line, col, prev);+ // |++ case 124:+ return new Token(TokenKind.PIPE, pos, pos + 1, line, col, prev);+ // }++ case 125:+ return new Token(TokenKind.BRACE_R, pos, pos + 1, line, col, prev);+ // A-Z _ a-z++ case 65:+ case 66:+ case 67:+ case 68:+ case 69:+ case 70:+ case 71:+ case 72:+ case 73:+ case 74:+ case 75:+ case 76:+ case 77:+ case 78:+ case 79:+ case 80:+ case 81:+ case 82:+ case 83:+ case 84:+ case 85:+ case 86:+ case 87:+ case 88:+ case 89:+ case 90:+ case 95:+ case 97:+ case 98:+ case 99:+ case 100:+ case 101:+ case 102:+ case 103:+ case 104:+ case 105:+ case 106:+ case 107:+ case 108:+ case 109:+ case 110:+ case 111:+ case 112:+ case 113:+ case 114:+ case 115:+ case 116:+ case 117:+ case 118:+ case 119:+ case 120:+ case 121:+ case 122:+ return readName(source, pos, line, col, prev);+ // - 0-9++ case 45:+ case 48:+ case 49:+ case 50:+ case 51:+ case 52:+ case 53:+ case 54:+ case 55:+ case 56:+ case 57:+ return readNumber(source, pos, code, line, col, prev);+ // "++ case 34:+ if (body.charCodeAt(pos + 1) === 34 && body.charCodeAt(pos + 2) === 34) {+ return readBlockString(source, pos, line, col, prev, lexer);+ }++ return readString(source, pos, line, col, prev);+ }++ throw syntaxError(source, pos, unexpectedCharacterMessage(code));+}+/**+ * Report a message that an unexpected character was encountered.+ */+++function unexpectedCharacterMessage(code) {+ if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {+ return "Cannot contain the invalid character ".concat(printCharCode(code), ".");+ }++ if (code === 39) {+ // '+ return 'Unexpected single quote character (\'), did you mean to use a double quote (")?';+ }++ return "Cannot parse the unexpected character ".concat(printCharCode(code), ".");+}+/**+ * Reads from body starting at startPosition until it finds a non-whitespace+ * character, then returns the position of that character for lexing.+ */+++function positionAfterWhitespace(body, startPosition, lexer) {+ var bodyLength = body.length;+ var position = startPosition;++ while (position < bodyLength) {+ var code = body.charCodeAt(position); // tab | space | comma | BOM++ if (code === 9 || code === 32 || code === 44 || code === 0xfeff) {+ ++position;+ } else if (code === 10) {+ // new line+ ++position;+ ++lexer.line;+ lexer.lineStart = position;+ } else if (code === 13) {+ // carriage return+ if (body.charCodeAt(position + 1) === 10) {+ position += 2;+ } else {+ ++position;+ }++ ++lexer.line;+ lexer.lineStart = position;+ } else {+ break;+ }+ }++ return position;+}+/**+ * Reads a comment token from the source file.+ *+ * #[\u0009\u0020-\uFFFF]*+ */+++function readComment(source, start, line, col, prev) {+ var body = source.body;+ var code;+ var position = start;++ do {+ code = body.charCodeAt(++position);+ } while (!isNaN(code) && ( // SourceCharacter but not LineTerminator+ code > 0x001f || code === 0x0009));++ return new Token(TokenKind.COMMENT, start, position, line, col, prev, body.slice(start + 1, position));+}+/**+ * Reads a number token from the source file, either a float+ * or an int depending on whether a decimal point appears.+ *+ * Int: -?(0|[1-9][0-9]*)+ * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?+ */+++function readNumber(source, start, firstCode, line, col, prev) {+ var body = source.body;+ var code = firstCode;+ var position = start;+ var isFloat = false;++ if (code === 45) {+ // -+ code = body.charCodeAt(++position);+ }++ if (code === 48) {+ // 0+ code = body.charCodeAt(++position);++ if (code >= 48 && code <= 57) {+ throw syntaxError(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), "."));+ }+ } else {+ position = readDigits(source, position, code);+ code = body.charCodeAt(position);+ }++ if (code === 46) {+ // .+ isFloat = true;+ code = body.charCodeAt(++position);+ position = readDigits(source, position, code);+ code = body.charCodeAt(position);+ }++ if (code === 69 || code === 101) {+ // E e+ isFloat = true;+ code = body.charCodeAt(++position);++ if (code === 43 || code === 45) {+ // + -+ code = body.charCodeAt(++position);+ }++ position = readDigits(source, position, code);+ code = body.charCodeAt(position);+ } // Numbers cannot be followed by . or NameStart+++ if (code === 46 || isNameStart(code)) {+ throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));+ }++ return new Token(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, body.slice(start, position));+}+/**+ * Returns the new position in the source after reading digits.+ */+++function readDigits(source, start, firstCode) {+ var body = source.body;+ var position = start;+ var code = firstCode;++ if (code >= 48 && code <= 57) {+ // 0 - 9+ do {+ code = body.charCodeAt(++position);+ } while (code >= 48 && code <= 57); // 0 - 9+++ return position;+ }++ throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), "."));+}+/**+ * Reads a string token from the source file.+ *+ * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"+ */+++function readString(source, start, line, col, prev) {+ var body = source.body;+ var position = start + 1;+ var chunkStart = position;+ var code = 0;+ var value = '';++ while (position < body.length && !isNaN(code = body.charCodeAt(position)) && // not LineTerminator+ code !== 0x000a && code !== 0x000d) {+ // Closing Quote (")+ if (code === 34) {+ value += body.slice(chunkStart, position);+ return new Token(TokenKind.STRING, start, position + 1, line, col, prev, value);+ } // SourceCharacter+++ if (code < 0x0020 && code !== 0x0009) {+ throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));+ }++ ++position;++ if (code === 92) {+ // \+ value += body.slice(chunkStart, position - 1);+ code = body.charCodeAt(position);++ switch (code) {+ case 34:+ value += '"';+ break;++ case 47:+ value += '/';+ break;++ case 92:+ value += '\\';+ break;++ case 98:+ value += '\b';+ break;++ case 102:+ value += '\f';+ break;++ case 110:+ value += '\n';+ break;++ case 114:+ value += '\r';+ break;++ case 116:+ value += '\t';+ break;++ case 117:+ {+ // uXXXX+ var charCode = uniCharCode(body.charCodeAt(position + 1), body.charCodeAt(position + 2), body.charCodeAt(position + 3), body.charCodeAt(position + 4));++ if (charCode < 0) {+ var invalidSequence = body.slice(position + 1, position + 5);+ throw syntaxError(source, position, "Invalid character escape sequence: \\u".concat(invalidSequence, "."));+ }++ value += String.fromCharCode(charCode);+ position += 4;+ break;+ }++ default:+ throw syntaxError(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), "."));+ }++ ++position;+ chunkStart = position;+ }+ }++ throw syntaxError(source, position, 'Unterminated string.');+}+/**+ * Reads a block string token from the source file.+ *+ * """("?"?(\\"""|\\(?!=""")|[^"\\]))*"""+ */+++function readBlockString(source, start, line, col, prev, lexer) {+ var body = source.body;+ var position = start + 3;+ var chunkStart = position;+ var code = 0;+ var rawValue = '';++ while (position < body.length && !isNaN(code = body.charCodeAt(position))) {+ // Closing Triple-Quote (""")+ if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {+ rawValue += body.slice(chunkStart, position);+ return new Token(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, dedentBlockStringValue(rawValue));+ } // SourceCharacter+++ if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) {+ throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), "."));+ }++ if (code === 10) {+ // new line+ ++position;+ ++lexer.line;+ lexer.lineStart = position;+ } else if (code === 13) {+ // carriage return+ if (body.charCodeAt(position + 1) === 10) {+ position += 2;+ } else {+ ++position;+ }++ ++lexer.line;+ lexer.lineStart = position;+ } else if ( // Escape Triple-Quote (\""")+ code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {+ rawValue += body.slice(chunkStart, position) + '"""';+ position += 4;+ chunkStart = position;+ } else {+ ++position;+ }+ }++ throw syntaxError(source, position, 'Unterminated string.');+}+/**+ * Converts four hexadecimal chars to the integer that the+ * string represents. For example, uniCharCode('0','0','0','f')+ * will return 15, and uniCharCode('0','0','f','f') returns 255.+ *+ * Returns a negative number on error, if a char was invalid.+ *+ * This is implemented by noting that char2hex() returns -1 on error,+ * which means the result of ORing the char2hex() will also be negative.+ */+++function uniCharCode(a, b, c, d) {+ return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);+}+/**+ * Converts a hex character to its integer value.+ * '0' becomes 0, '9' becomes 9+ * 'A' becomes 10, 'F' becomes 15+ * 'a' becomes 10, 'f' becomes 15+ *+ * Returns -1 on error.+ */+++function char2hex(a) {+ return a >= 48 && a <= 57 ? a - 48 // 0-9+ : a >= 65 && a <= 70 ? a - 55 // A-F+ : a >= 97 && a <= 102 ? a - 87 // a-f+ : -1;+}+/**+ * Reads an alphanumeric + underscore name from the source.+ *+ * [_A-Za-z][_0-9A-Za-z]*+ */+++function readName(source, start, line, col, prev) {+ var body = source.body;+ var bodyLength = body.length;+ var position = start + 1;+ var code = 0;++ while (position !== bodyLength && !isNaN(code = body.charCodeAt(position)) && (code === 95 || // _+ code >= 48 && code <= 57 || // 0-9+ code >= 65 && code <= 90 || // A-Z+ code >= 97 && code <= 122) // a-z+ ) {+ ++position;+ }++ return new Token(TokenKind.NAME, start, position, line, col, prev, body.slice(start, position));+} // _ A-Z a-z+++function isNameStart(code) {+ return code === 95 || code >= 65 && code <= 90 || code >= 97 && code <= 122;+}++/**+ * Configuration options to control parser behavior+ */++/**+ * Given a GraphQL source, parses it into a Document.+ * Throws GraphQLError if a syntax error is encountered.+ */+function parse(source, options) {+ var parser = new Parser(source, options);+ return parser.parseDocument();+}+/**+ * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for+ * that value.+ * Throws GraphQLError if a syntax error is encountered.+ *+ * This is useful within tools that operate upon GraphQL Values directly and+ * in isolation of complete GraphQL documents.+ *+ * Consider providing the results to the utility function: valueFromAST().+ */++function parseValue(source, options) {+ var parser = new Parser(source, options);+ parser.expectToken(TokenKind.SOF);+ var value = parser.parseValueLiteral(false);+ parser.expectToken(TokenKind.EOF);+ return value;+}+/**+ * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for+ * that type.+ * Throws GraphQLError if a syntax error is encountered.+ *+ * This is useful within tools that operate upon GraphQL Types directly and+ * in isolation of complete GraphQL documents.+ *+ * Consider providing the results to the utility function: typeFromAST().+ */++function parseType(source, options) {+ var parser = new Parser(source, options);+ parser.expectToken(TokenKind.SOF);+ var type = parser.parseTypeReference();+ parser.expectToken(TokenKind.EOF);+ return type;+}++var Parser = /*#__PURE__*/function () {+ function Parser(source, options) {+ var sourceObj = typeof source === 'string' ? new Source(source) : source;+ sourceObj instanceof Source || devAssert(0, "Must provide Source. Received: ".concat(inspect(sourceObj), "."));+ this._lexer = new Lexer(sourceObj);+ this._options = options;+ }+ /**+ * Converts a name lex token into a name parse node.+ */+++ var _proto = Parser.prototype;++ _proto.parseName = function parseName() {+ var token = this.expectToken(TokenKind.NAME);+ return {+ kind: Kind.NAME,+ value: token.value,+ loc: this.loc(token)+ };+ } // Implements the parsing rules in the Document section.++ /**+ * Document : Definition++ */+ ;++ _proto.parseDocument = function parseDocument() {+ var start = this._lexer.token;+ return {+ kind: Kind.DOCUMENT,+ definitions: this.many(TokenKind.SOF, this.parseDefinition, TokenKind.EOF),+ loc: this.loc(start)+ };+ }+ /**+ * Definition :+ * - ExecutableDefinition+ * - TypeSystemDefinition+ * - TypeSystemExtension+ *+ * ExecutableDefinition :+ * - OperationDefinition+ * - FragmentDefinition+ */+ ;++ _proto.parseDefinition = function parseDefinition() {+ if (this.peek(TokenKind.NAME)) {+ switch (this._lexer.token.value) {+ case 'query':+ case 'mutation':+ case 'subscription':+ return this.parseOperationDefinition();++ case 'fragment':+ return this.parseFragmentDefinition();++ case 'schema':+ case 'scalar':+ case 'type':+ case 'interface':+ case 'union':+ case 'enum':+ case 'input':+ case 'directive':+ return this.parseTypeSystemDefinition();++ case 'extend':+ return this.parseTypeSystemExtension();+ }+ } else if (this.peek(TokenKind.BRACE_L)) {+ return this.parseOperationDefinition();+ } else if (this.peekDescription()) {+ return this.parseTypeSystemDefinition();+ }++ throw this.unexpected();+ } // Implements the parsing rules in the Operations section.++ /**+ * OperationDefinition :+ * - SelectionSet+ * - OperationType Name? VariableDefinitions? Directives? SelectionSet+ */+ ;++ _proto.parseOperationDefinition = function parseOperationDefinition() {+ var start = this._lexer.token;++ if (this.peek(TokenKind.BRACE_L)) {+ return {+ kind: Kind.OPERATION_DEFINITION,+ operation: 'query',+ name: undefined,+ variableDefinitions: [],+ directives: [],+ selectionSet: this.parseSelectionSet(),+ loc: this.loc(start)+ };+ }++ var operation = this.parseOperationType();+ var name;++ if (this.peek(TokenKind.NAME)) {+ name = this.parseName();+ }++ return {+ kind: Kind.OPERATION_DEFINITION,+ operation: operation,+ name: name,+ variableDefinitions: this.parseVariableDefinitions(),+ directives: this.parseDirectives(false),+ selectionSet: this.parseSelectionSet(),+ loc: this.loc(start)+ };+ }+ /**+ * OperationType : one of query mutation subscription+ */+ ;++ _proto.parseOperationType = function parseOperationType() {+ var operationToken = this.expectToken(TokenKind.NAME);++ switch (operationToken.value) {+ case 'query':+ return 'query';++ case 'mutation':+ return 'mutation';++ case 'subscription':+ return 'subscription';+ }++ throw this.unexpected(operationToken);+ }+ /**+ * VariableDefinitions : ( VariableDefinition+ )+ */+ ;++ _proto.parseVariableDefinitions = function parseVariableDefinitions() {+ return this.optionalMany(TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R);+ }+ /**+ * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?+ */+ ;++ _proto.parseVariableDefinition = function parseVariableDefinition() {+ var start = this._lexer.token;+ return {+ kind: Kind.VARIABLE_DEFINITION,+ variable: this.parseVariable(),+ type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),+ defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseValueLiteral(true) : undefined,+ directives: this.parseDirectives(true),+ loc: this.loc(start)+ };+ }+ /**+ * Variable : $ Name+ */+ ;++ _proto.parseVariable = function parseVariable() {+ var start = this._lexer.token;+ this.expectToken(TokenKind.DOLLAR);+ return {+ kind: Kind.VARIABLE,+ name: this.parseName(),+ loc: this.loc(start)+ };+ }+ /**+ * SelectionSet : { Selection+ }+ */+ ;++ _proto.parseSelectionSet = function parseSelectionSet() {+ var start = this._lexer.token;+ return {+ kind: Kind.SELECTION_SET,+ selections: this.many(TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R),+ loc: this.loc(start)+ };+ }+ /**+ * Selection :+ * - Field+ * - FragmentSpread+ * - InlineFragment+ */+ ;++ _proto.parseSelection = function parseSelection() {+ return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();+ }+ /**+ * Field : Alias? Name Arguments? Directives? SelectionSet?+ *+ * Alias : Name :+ */+ ;++ _proto.parseField = function parseField() {+ var start = this._lexer.token;+ var nameOrAlias = this.parseName();+ var alias;+ var name;++ if (this.expectOptionalToken(TokenKind.COLON)) {+ alias = nameOrAlias;+ name = this.parseName();+ } else {+ name = nameOrAlias;+ }++ return {+ kind: Kind.FIELD,+ alias: alias,+ name: name,+ arguments: this.parseArguments(false),+ directives: this.parseDirectives(false),+ selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined,+ loc: this.loc(start)+ };+ }+ /**+ * Arguments[Const] : ( Argument[?Const]+ )+ */+ ;++ _proto.parseArguments = function parseArguments(isConst) {+ var item = isConst ? this.parseConstArgument : this.parseArgument;+ return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);+ }+ /**+ * Argument[Const] : Name : Value[?Const]+ */+ ;++ _proto.parseArgument = function parseArgument() {+ var start = this._lexer.token;+ var name = this.parseName();+ this.expectToken(TokenKind.COLON);+ return {+ kind: Kind.ARGUMENT,+ name: name,+ value: this.parseValueLiteral(false),+ loc: this.loc(start)+ };+ };++ _proto.parseConstArgument = function parseConstArgument() {+ var start = this._lexer.token;+ return {+ kind: Kind.ARGUMENT,+ name: this.parseName(),+ value: (this.expectToken(TokenKind.COLON), this.parseValueLiteral(true)),+ loc: this.loc(start)+ };+ } // Implements the parsing rules in the Fragments section.++ /**+ * Corresponds to both FragmentSpread and InlineFragment in the spec.+ *+ * FragmentSpread : ... FragmentName Directives?+ *+ * InlineFragment : ... TypeCondition? Directives? SelectionSet+ */+ ;++ _proto.parseFragment = function parseFragment() {+ var start = this._lexer.token;+ this.expectToken(TokenKind.SPREAD);+ var hasTypeCondition = this.expectOptionalKeyword('on');++ if (!hasTypeCondition && this.peek(TokenKind.NAME)) {+ return {+ kind: Kind.FRAGMENT_SPREAD,+ name: this.parseFragmentName(),+ directives: this.parseDirectives(false),+ loc: this.loc(start)+ };+ }++ return {+ kind: Kind.INLINE_FRAGMENT,+ typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,+ directives: this.parseDirectives(false),+ selectionSet: this.parseSelectionSet(),+ loc: this.loc(start)+ };+ }+ /**+ * FragmentDefinition :+ * - fragment FragmentName on TypeCondition Directives? SelectionSet+ *+ * TypeCondition : NamedType+ */+ ;++ _proto.parseFragmentDefinition = function parseFragmentDefinition() {+ var _this$_options;++ var start = this._lexer.token;+ this.expectKeyword('fragment'); // Experimental support for defining variables within fragments changes+ // the grammar of FragmentDefinition:+ // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet++ if (((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.experimentalFragmentVariables) === true) {+ return {+ kind: Kind.FRAGMENT_DEFINITION,+ name: this.parseFragmentName(),+ variableDefinitions: this.parseVariableDefinitions(),+ typeCondition: (this.expectKeyword('on'), this.parseNamedType()),+ directives: this.parseDirectives(false),+ selectionSet: this.parseSelectionSet(),+ loc: this.loc(start)+ };+ }++ return {+ kind: Kind.FRAGMENT_DEFINITION,+ name: this.parseFragmentName(),+ typeCondition: (this.expectKeyword('on'), this.parseNamedType()),+ directives: this.parseDirectives(false),+ selectionSet: this.parseSelectionSet(),+ loc: this.loc(start)+ };+ }+ /**+ * FragmentName : Name but not `on`+ */+ ;++ _proto.parseFragmentName = function parseFragmentName() {+ if (this._lexer.token.value === 'on') {+ throw this.unexpected();+ }++ return this.parseName();+ } // Implements the parsing rules in the Values section.++ /**+ * Value[Const] :+ * - [~Const] Variable+ * - IntValue+ * - FloatValue+ * - StringValue+ * - BooleanValue+ * - NullValue+ * - EnumValue+ * - ListValue[?Const]+ * - ObjectValue[?Const]+ *+ * BooleanValue : one of `true` `false`+ *+ * NullValue : `null`+ *+ * EnumValue : Name but not `true`, `false` or `null`+ */+ ;++ _proto.parseValueLiteral = function parseValueLiteral(isConst) {+ var token = this._lexer.token;++ switch (token.kind) {+ case TokenKind.BRACKET_L:+ return this.parseList(isConst);++ case TokenKind.BRACE_L:+ return this.parseObject(isConst);++ case TokenKind.INT:+ this._lexer.advance();++ return {+ kind: Kind.INT,+ value: token.value,+ loc: this.loc(token)+ };++ case TokenKind.FLOAT:+ this._lexer.advance();++ return {+ kind: Kind.FLOAT,+ value: token.value,+ loc: this.loc(token)+ };++ case TokenKind.STRING:+ case TokenKind.BLOCK_STRING:+ return this.parseStringLiteral();++ case TokenKind.NAME:+ this._lexer.advance();++ switch (token.value) {+ case 'true':+ return {+ kind: Kind.BOOLEAN,+ value: true,+ loc: this.loc(token)+ };++ case 'false':+ return {+ kind: Kind.BOOLEAN,+ value: false,+ loc: this.loc(token)+ };++ case 'null':+ return {+ kind: Kind.NULL,+ loc: this.loc(token)+ };++ default:+ return {+ kind: Kind.ENUM,+ value: token.value,+ loc: this.loc(token)+ };+ }++ case TokenKind.DOLLAR:+ if (!isConst) {+ return this.parseVariable();+ }++ break;+ }++ throw this.unexpected();+ };++ _proto.parseStringLiteral = function parseStringLiteral() {+ var token = this._lexer.token;++ this._lexer.advance();++ return {+ kind: Kind.STRING,+ value: token.value,+ block: token.kind === TokenKind.BLOCK_STRING,+ loc: this.loc(token)+ };+ }+ /**+ * ListValue[Const] :+ * - [ ]+ * - [ Value[?Const]+ ]+ */+ ;++ _proto.parseList = function parseList(isConst) {+ var _this = this;++ var start = this._lexer.token;++ var item = function item() {+ return _this.parseValueLiteral(isConst);+ };++ return {+ kind: Kind.LIST,+ values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),+ loc: this.loc(start)+ };+ }+ /**+ * ObjectValue[Const] :+ * - { }+ * - { ObjectField[?Const]+ }+ */+ ;++ _proto.parseObject = function parseObject(isConst) {+ var _this2 = this;++ var start = this._lexer.token;++ var item = function item() {+ return _this2.parseObjectField(isConst);+ };++ return {+ kind: Kind.OBJECT,+ fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),+ loc: this.loc(start)+ };+ }+ /**+ * ObjectField[Const] : Name : Value[?Const]+ */+ ;++ _proto.parseObjectField = function parseObjectField(isConst) {+ var start = this._lexer.token;+ var name = this.parseName();+ this.expectToken(TokenKind.COLON);+ return {+ kind: Kind.OBJECT_FIELD,+ name: name,+ value: this.parseValueLiteral(isConst),+ loc: this.loc(start)+ };+ } // Implements the parsing rules in the Directives section.++ /**+ * Directives[Const] : Directive[?Const]++ */+ ;++ _proto.parseDirectives = function parseDirectives(isConst) {+ var directives = [];++ while (this.peek(TokenKind.AT)) {+ directives.push(this.parseDirective(isConst));+ }++ return directives;+ }+ /**+ * Directive[Const] : @ Name Arguments[?Const]?+ */+ ;++ _proto.parseDirective = function parseDirective(isConst) {+ var start = this._lexer.token;+ this.expectToken(TokenKind.AT);+ return {+ kind: Kind.DIRECTIVE,+ name: this.parseName(),+ arguments: this.parseArguments(isConst),+ loc: this.loc(start)+ };+ } // Implements the parsing rules in the Types section.++ /**+ * Type :+ * - NamedType+ * - ListType+ * - NonNullType+ */+ ;++ _proto.parseTypeReference = function parseTypeReference() {+ var start = this._lexer.token;+ var type;++ if (this.expectOptionalToken(TokenKind.BRACKET_L)) {+ type = this.parseTypeReference();+ this.expectToken(TokenKind.BRACKET_R);+ type = {+ kind: Kind.LIST_TYPE,+ type: type,+ loc: this.loc(start)+ };+ } else {+ type = this.parseNamedType();+ }++ if (this.expectOptionalToken(TokenKind.BANG)) {+ return {+ kind: Kind.NON_NULL_TYPE,+ type: type,+ loc: this.loc(start)+ };+ }++ return type;+ }+ /**+ * NamedType : Name+ */+ ;++ _proto.parseNamedType = function parseNamedType() {+ var start = this._lexer.token;+ return {+ kind: Kind.NAMED_TYPE,+ name: this.parseName(),+ loc: this.loc(start)+ };+ } // Implements the parsing rules in the Type Definition section.++ /**+ * TypeSystemDefinition :+ * - SchemaDefinition+ * - TypeDefinition+ * - DirectiveDefinition+ *+ * TypeDefinition :+ * - ScalarTypeDefinition+ * - ObjectTypeDefinition+ * - InterfaceTypeDefinition+ * - UnionTypeDefinition+ * - EnumTypeDefinition+ * - InputObjectTypeDefinition+ */+ ;++ _proto.parseTypeSystemDefinition = function parseTypeSystemDefinition() {+ // Many definitions begin with a description and require a lookahead.+ var keywordToken = this.peekDescription() ? this._lexer.lookahead() : this._lexer.token;++ if (keywordToken.kind === TokenKind.NAME) {+ switch (keywordToken.value) {+ case 'schema':+ return this.parseSchemaDefinition();++ case 'scalar':+ return this.parseScalarTypeDefinition();++ case 'type':+ return this.parseObjectTypeDefinition();++ case 'interface':+ return this.parseInterfaceTypeDefinition();++ case 'union':+ return this.parseUnionTypeDefinition();++ case 'enum':+ return this.parseEnumTypeDefinition();++ case 'input':+ return this.parseInputObjectTypeDefinition();++ case 'directive':+ return this.parseDirectiveDefinition();+ }+ }++ throw this.unexpected(keywordToken);+ };++ _proto.peekDescription = function peekDescription() {+ return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);+ }+ /**+ * Description : StringValue+ */+ ;++ _proto.parseDescription = function parseDescription() {+ if (this.peekDescription()) {+ return this.parseStringLiteral();+ }+ }+ /**+ * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }+ */+ ;++ _proto.parseSchemaDefinition = function parseSchemaDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ this.expectKeyword('schema');+ var directives = this.parseDirectives(true);+ var operationTypes = this.many(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);+ return {+ kind: Kind.SCHEMA_DEFINITION,+ description: description,+ directives: directives,+ operationTypes: operationTypes,+ loc: this.loc(start)+ };+ }+ /**+ * OperationTypeDefinition : OperationType : NamedType+ */+ ;++ _proto.parseOperationTypeDefinition = function parseOperationTypeDefinition() {+ var start = this._lexer.token;+ var operation = this.parseOperationType();+ this.expectToken(TokenKind.COLON);+ var type = this.parseNamedType();+ return {+ kind: Kind.OPERATION_TYPE_DEFINITION,+ operation: operation,+ type: type,+ loc: this.loc(start)+ };+ }+ /**+ * ScalarTypeDefinition : Description? scalar Name Directives[Const]?+ */+ ;++ _proto.parseScalarTypeDefinition = function parseScalarTypeDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ this.expectKeyword('scalar');+ var name = this.parseName();+ var directives = this.parseDirectives(true);+ return {+ kind: Kind.SCALAR_TYPE_DEFINITION,+ description: description,+ name: name,+ directives: directives,+ loc: this.loc(start)+ };+ }+ /**+ * ObjectTypeDefinition :+ * Description?+ * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?+ */+ ;++ _proto.parseObjectTypeDefinition = function parseObjectTypeDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ this.expectKeyword('type');+ var name = this.parseName();+ var interfaces = this.parseImplementsInterfaces();+ var directives = this.parseDirectives(true);+ var fields = this.parseFieldsDefinition();+ return {+ kind: Kind.OBJECT_TYPE_DEFINITION,+ description: description,+ name: name,+ interfaces: interfaces,+ directives: directives,+ fields: fields,+ loc: this.loc(start)+ };+ }+ /**+ * ImplementsInterfaces :+ * - implements `&`? NamedType+ * - ImplementsInterfaces & NamedType+ */+ ;++ _proto.parseImplementsInterfaces = function parseImplementsInterfaces() {+ var types = [];++ if (this.expectOptionalKeyword('implements')) {+ // Optional leading ampersand+ this.expectOptionalToken(TokenKind.AMP);++ do {+ var _this$_options2;++ types.push(this.parseNamedType());+ } while (this.expectOptionalToken(TokenKind.AMP) || // Legacy support for the SDL?+ ((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.allowLegacySDLImplementsInterfaces) === true && this.peek(TokenKind.NAME));+ }++ return types;+ }+ /**+ * FieldsDefinition : { FieldDefinition+ }+ */+ ;++ _proto.parseFieldsDefinition = function parseFieldsDefinition() {+ var _this$_options3;++ // Legacy support for the SDL?+ if (((_this$_options3 = this._options) === null || _this$_options3 === void 0 ? void 0 : _this$_options3.allowLegacySDLEmptyFields) === true && this.peek(TokenKind.BRACE_L) && this._lexer.lookahead().kind === TokenKind.BRACE_R) {+ this._lexer.advance();++ this._lexer.advance();++ return [];+ }++ return this.optionalMany(TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R);+ }+ /**+ * FieldDefinition :+ * - Description? Name ArgumentsDefinition? : Type Directives[Const]?+ */+ ;++ _proto.parseFieldDefinition = function parseFieldDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ var name = this.parseName();+ var args = this.parseArgumentDefs();+ this.expectToken(TokenKind.COLON);+ var type = this.parseTypeReference();+ var directives = this.parseDirectives(true);+ return {+ kind: Kind.FIELD_DEFINITION,+ description: description,+ name: name,+ arguments: args,+ type: type,+ directives: directives,+ loc: this.loc(start)+ };+ }+ /**+ * ArgumentsDefinition : ( InputValueDefinition+ )+ */+ ;++ _proto.parseArgumentDefs = function parseArgumentDefs() {+ return this.optionalMany(TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R);+ }+ /**+ * InputValueDefinition :+ * - Description? Name : Type DefaultValue? Directives[Const]?+ */+ ;++ _proto.parseInputValueDef = function parseInputValueDef() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ var name = this.parseName();+ this.expectToken(TokenKind.COLON);+ var type = this.parseTypeReference();+ var defaultValue;++ if (this.expectOptionalToken(TokenKind.EQUALS)) {+ defaultValue = this.parseValueLiteral(true);+ }++ var directives = this.parseDirectives(true);+ return {+ kind: Kind.INPUT_VALUE_DEFINITION,+ description: description,+ name: name,+ type: type,+ defaultValue: defaultValue,+ directives: directives,+ loc: this.loc(start)+ };+ }+ /**+ * InterfaceTypeDefinition :+ * - Description? interface Name Directives[Const]? FieldsDefinition?+ */+ ;++ _proto.parseInterfaceTypeDefinition = function parseInterfaceTypeDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ this.expectKeyword('interface');+ var name = this.parseName();+ var interfaces = this.parseImplementsInterfaces();+ var directives = this.parseDirectives(true);+ var fields = this.parseFieldsDefinition();+ return {+ kind: Kind.INTERFACE_TYPE_DEFINITION,+ description: description,+ name: name,+ interfaces: interfaces,+ directives: directives,+ fields: fields,+ loc: this.loc(start)+ };+ }+ /**+ * UnionTypeDefinition :+ * - Description? union Name Directives[Const]? UnionMemberTypes?+ */+ ;++ _proto.parseUnionTypeDefinition = function parseUnionTypeDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ this.expectKeyword('union');+ var name = this.parseName();+ var directives = this.parseDirectives(true);+ var types = this.parseUnionMemberTypes();+ return {+ kind: Kind.UNION_TYPE_DEFINITION,+ description: description,+ name: name,+ directives: directives,+ types: types,+ loc: this.loc(start)+ };+ }+ /**+ * UnionMemberTypes :+ * - = `|`? NamedType+ * - UnionMemberTypes | NamedType+ */+ ;++ _proto.parseUnionMemberTypes = function parseUnionMemberTypes() {+ var types = [];++ if (this.expectOptionalToken(TokenKind.EQUALS)) {+ // Optional leading pipe+ this.expectOptionalToken(TokenKind.PIPE);++ do {+ types.push(this.parseNamedType());+ } while (this.expectOptionalToken(TokenKind.PIPE));+ }++ return types;+ }+ /**+ * EnumTypeDefinition :+ * - Description? enum Name Directives[Const]? EnumValuesDefinition?+ */+ ;++ _proto.parseEnumTypeDefinition = function parseEnumTypeDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ this.expectKeyword('enum');+ var name = this.parseName();+ var directives = this.parseDirectives(true);+ var values = this.parseEnumValuesDefinition();+ return {+ kind: Kind.ENUM_TYPE_DEFINITION,+ description: description,+ name: name,+ directives: directives,+ values: values,+ loc: this.loc(start)+ };+ }+ /**+ * EnumValuesDefinition : { EnumValueDefinition+ }+ */+ ;++ _proto.parseEnumValuesDefinition = function parseEnumValuesDefinition() {+ return this.optionalMany(TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R);+ }+ /**+ * EnumValueDefinition : Description? EnumValue Directives[Const]?+ *+ * EnumValue : Name+ */+ ;++ _proto.parseEnumValueDefinition = function parseEnumValueDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ var name = this.parseName();+ var directives = this.parseDirectives(true);+ return {+ kind: Kind.ENUM_VALUE_DEFINITION,+ description: description,+ name: name,+ directives: directives,+ loc: this.loc(start)+ };+ }+ /**+ * InputObjectTypeDefinition :+ * - Description? input Name Directives[Const]? InputFieldsDefinition?+ */+ ;++ _proto.parseInputObjectTypeDefinition = function parseInputObjectTypeDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ this.expectKeyword('input');+ var name = this.parseName();+ var directives = this.parseDirectives(true);+ var fields = this.parseInputFieldsDefinition();+ return {+ kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,+ description: description,+ name: name,+ directives: directives,+ fields: fields,+ loc: this.loc(start)+ };+ }+ /**+ * InputFieldsDefinition : { InputValueDefinition+ }+ */+ ;++ _proto.parseInputFieldsDefinition = function parseInputFieldsDefinition() {+ return this.optionalMany(TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R);+ }+ /**+ * TypeSystemExtension :+ * - SchemaExtension+ * - TypeExtension+ *+ * TypeExtension :+ * - ScalarTypeExtension+ * - ObjectTypeExtension+ * - InterfaceTypeExtension+ * - UnionTypeExtension+ * - EnumTypeExtension+ * - InputObjectTypeDefinition+ */+ ;++ _proto.parseTypeSystemExtension = function parseTypeSystemExtension() {+ var keywordToken = this._lexer.lookahead();++ if (keywordToken.kind === TokenKind.NAME) {+ switch (keywordToken.value) {+ case 'schema':+ return this.parseSchemaExtension();++ case 'scalar':+ return this.parseScalarTypeExtension();++ case 'type':+ return this.parseObjectTypeExtension();++ case 'interface':+ return this.parseInterfaceTypeExtension();++ case 'union':+ return this.parseUnionTypeExtension();++ case 'enum':+ return this.parseEnumTypeExtension();++ case 'input':+ return this.parseInputObjectTypeExtension();+ }+ }++ throw this.unexpected(keywordToken);+ }+ /**+ * SchemaExtension :+ * - extend schema Directives[Const]? { OperationTypeDefinition+ }+ * - extend schema Directives[Const]+ */+ ;++ _proto.parseSchemaExtension = function parseSchemaExtension() {+ var start = this._lexer.token;+ this.expectKeyword('extend');+ this.expectKeyword('schema');+ var directives = this.parseDirectives(true);+ var operationTypes = this.optionalMany(TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R);++ if (directives.length === 0 && operationTypes.length === 0) {+ throw this.unexpected();+ }++ return {+ kind: Kind.SCHEMA_EXTENSION,+ directives: directives,+ operationTypes: operationTypes,+ loc: this.loc(start)+ };+ }+ /**+ * ScalarTypeExtension :+ * - extend scalar Name Directives[Const]+ */+ ;++ _proto.parseScalarTypeExtension = function parseScalarTypeExtension() {+ var start = this._lexer.token;+ this.expectKeyword('extend');+ this.expectKeyword('scalar');+ var name = this.parseName();+ var directives = this.parseDirectives(true);++ if (directives.length === 0) {+ throw this.unexpected();+ }++ return {+ kind: Kind.SCALAR_TYPE_EXTENSION,+ name: name,+ directives: directives,+ loc: this.loc(start)+ };+ }+ /**+ * ObjectTypeExtension :+ * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition+ * - extend type Name ImplementsInterfaces? Directives[Const]+ * - extend type Name ImplementsInterfaces+ */+ ;++ _proto.parseObjectTypeExtension = function parseObjectTypeExtension() {+ var start = this._lexer.token;+ this.expectKeyword('extend');+ this.expectKeyword('type');+ var name = this.parseName();+ var interfaces = this.parseImplementsInterfaces();+ var directives = this.parseDirectives(true);+ var fields = this.parseFieldsDefinition();++ if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {+ throw this.unexpected();+ }++ return {+ kind: Kind.OBJECT_TYPE_EXTENSION,+ name: name,+ interfaces: interfaces,+ directives: directives,+ fields: fields,+ loc: this.loc(start)+ };+ }+ /**+ * InterfaceTypeExtension :+ * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition+ * - extend interface Name ImplementsInterfaces? Directives[Const]+ * - extend interface Name ImplementsInterfaces+ */+ ;++ _proto.parseInterfaceTypeExtension = function parseInterfaceTypeExtension() {+ var start = this._lexer.token;+ this.expectKeyword('extend');+ this.expectKeyword('interface');+ var name = this.parseName();+ var interfaces = this.parseImplementsInterfaces();+ var directives = this.parseDirectives(true);+ var fields = this.parseFieldsDefinition();++ if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {+ throw this.unexpected();+ }++ return {+ kind: Kind.INTERFACE_TYPE_EXTENSION,+ name: name,+ interfaces: interfaces,+ directives: directives,+ fields: fields,+ loc: this.loc(start)+ };+ }+ /**+ * UnionTypeExtension :+ * - extend union Name Directives[Const]? UnionMemberTypes+ * - extend union Name Directives[Const]+ */+ ;++ _proto.parseUnionTypeExtension = function parseUnionTypeExtension() {+ var start = this._lexer.token;+ this.expectKeyword('extend');+ this.expectKeyword('union');+ var name = this.parseName();+ var directives = this.parseDirectives(true);+ var types = this.parseUnionMemberTypes();++ if (directives.length === 0 && types.length === 0) {+ throw this.unexpected();+ }++ return {+ kind: Kind.UNION_TYPE_EXTENSION,+ name: name,+ directives: directives,+ types: types,+ loc: this.loc(start)+ };+ }+ /**+ * EnumTypeExtension :+ * - extend enum Name Directives[Const]? EnumValuesDefinition+ * - extend enum Name Directives[Const]+ */+ ;++ _proto.parseEnumTypeExtension = function parseEnumTypeExtension() {+ var start = this._lexer.token;+ this.expectKeyword('extend');+ this.expectKeyword('enum');+ var name = this.parseName();+ var directives = this.parseDirectives(true);+ var values = this.parseEnumValuesDefinition();++ if (directives.length === 0 && values.length === 0) {+ throw this.unexpected();+ }++ return {+ kind: Kind.ENUM_TYPE_EXTENSION,+ name: name,+ directives: directives,+ values: values,+ loc: this.loc(start)+ };+ }+ /**+ * InputObjectTypeExtension :+ * - extend input Name Directives[Const]? InputFieldsDefinition+ * - extend input Name Directives[Const]+ */+ ;++ _proto.parseInputObjectTypeExtension = function parseInputObjectTypeExtension() {+ var start = this._lexer.token;+ this.expectKeyword('extend');+ this.expectKeyword('input');+ var name = this.parseName();+ var directives = this.parseDirectives(true);+ var fields = this.parseInputFieldsDefinition();++ if (directives.length === 0 && fields.length === 0) {+ throw this.unexpected();+ }++ return {+ kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,+ name: name,+ directives: directives,+ fields: fields,+ loc: this.loc(start)+ };+ }+ /**+ * DirectiveDefinition :+ * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations+ */+ ;++ _proto.parseDirectiveDefinition = function parseDirectiveDefinition() {+ var start = this._lexer.token;+ var description = this.parseDescription();+ this.expectKeyword('directive');+ this.expectToken(TokenKind.AT);+ var name = this.parseName();+ var args = this.parseArgumentDefs();+ var repeatable = this.expectOptionalKeyword('repeatable');+ this.expectKeyword('on');+ var locations = this.parseDirectiveLocations();+ return {+ kind: Kind.DIRECTIVE_DEFINITION,+ description: description,+ name: name,+ arguments: args,+ repeatable: repeatable,+ locations: locations,+ loc: this.loc(start)+ };+ }+ /**+ * DirectiveLocations :+ * - `|`? DirectiveLocation+ * - DirectiveLocations | DirectiveLocation+ */+ ;++ _proto.parseDirectiveLocations = function parseDirectiveLocations() {+ // Optional leading pipe+ this.expectOptionalToken(TokenKind.PIPE);+ var locations = [];++ do {+ locations.push(this.parseDirectiveLocation());+ } while (this.expectOptionalToken(TokenKind.PIPE));++ return locations;+ }+ /*+ * DirectiveLocation :+ * - ExecutableDirectiveLocation+ * - TypeSystemDirectiveLocation+ *+ * ExecutableDirectiveLocation : one of+ * `QUERY`+ * `MUTATION`+ * `SUBSCRIPTION`+ * `FIELD`+ * `FRAGMENT_DEFINITION`+ * `FRAGMENT_SPREAD`+ * `INLINE_FRAGMENT`+ *+ * TypeSystemDirectiveLocation : one of+ * `SCHEMA`+ * `SCALAR`+ * `OBJECT`+ * `FIELD_DEFINITION`+ * `ARGUMENT_DEFINITION`+ * `INTERFACE`+ * `UNION`+ * `ENUM`+ * `ENUM_VALUE`+ * `INPUT_OBJECT`+ * `INPUT_FIELD_DEFINITION`+ */+ ;++ _proto.parseDirectiveLocation = function parseDirectiveLocation() {+ var start = this._lexer.token;+ var name = this.parseName();++ if (DirectiveLocation[name.value] !== undefined) {+ return name;+ }++ throw this.unexpected(start);+ } // Core parsing utility functions++ /**+ * Returns a location object, used to identify the place in+ * the source that created a given parsed object.+ */+ ;++ _proto.loc = function loc(startToken) {+ var _this$_options4;++ if (((_this$_options4 = this._options) === null || _this$_options4 === void 0 ? void 0 : _this$_options4.noLocation) !== true) {+ return new Location(startToken, this._lexer.lastToken, this._lexer.source);+ }+ }+ /**+ * Determines if the next token is of a given kind+ */+ ;++ _proto.peek = function peek(kind) {+ return this._lexer.token.kind === kind;+ }+ /**+ * If the next token is of the given kind, return that token after advancing+ * the lexer. Otherwise, do not change the parser state and throw an error.+ */+ ;++ _proto.expectToken = function expectToken(kind) {+ var token = this._lexer.token;++ if (token.kind === kind) {+ this._lexer.advance();++ return token;+ }++ throw syntaxError(this._lexer.source, token.start, "Expected ".concat(getTokenKindDesc(kind), ", found ").concat(getTokenDesc(token), "."));+ }+ /**+ * If the next token is of the given kind, return that token after advancing+ * the lexer. Otherwise, do not change the parser state and return undefined.+ */+ ;++ _proto.expectOptionalToken = function expectOptionalToken(kind) {+ var token = this._lexer.token;++ if (token.kind === kind) {+ this._lexer.advance();++ return token;+ }++ return undefined;+ }+ /**+ * If the next token is a given keyword, advance the lexer.+ * Otherwise, do not change the parser state and throw an error.+ */+ ;++ _proto.expectKeyword = function expectKeyword(value) {+ var token = this._lexer.token;++ if (token.kind === TokenKind.NAME && token.value === value) {+ this._lexer.advance();+ } else {+ throw syntaxError(this._lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token), "."));+ }+ }+ /**+ * If the next token is a given keyword, return "true" after advancing+ * the lexer. Otherwise, do not change the parser state and return "false".+ */+ ;++ _proto.expectOptionalKeyword = function expectOptionalKeyword(value) {+ var token = this._lexer.token;++ if (token.kind === TokenKind.NAME && token.value === value) {+ this._lexer.advance();++ return true;+ }++ return false;+ }+ /**+ * Helper function for creating an error when an unexpected lexed token+ * is encountered.+ */+ ;++ _proto.unexpected = function unexpected(atToken) {+ var token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;+ return syntaxError(this._lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token), "."));+ }+ /**+ * Returns a possibly empty list of parse nodes, determined by+ * the parseFn. This list begins with a lex token of openKind+ * and ends with a lex token of closeKind. Advances the parser+ * to the next lex token after the closing token.+ */+ ;++ _proto.any = function any(openKind, parseFn, closeKind) {+ this.expectToken(openKind);+ var nodes = [];++ while (!this.expectOptionalToken(closeKind)) {+ nodes.push(parseFn.call(this));+ }++ return nodes;+ }+ /**+ * Returns a list of parse nodes, determined by the parseFn.+ * It can be empty only if open token is missing otherwise it will always+ * return non-empty list that begins with a lex token of openKind and ends+ * with a lex token of closeKind. Advances the parser to the next lex token+ * after the closing token.+ */+ ;++ _proto.optionalMany = function optionalMany(openKind, parseFn, closeKind) {+ if (this.expectOptionalToken(openKind)) {+ var nodes = [];++ do {+ nodes.push(parseFn.call(this));+ } while (!this.expectOptionalToken(closeKind));++ return nodes;+ }++ return [];+ }+ /**+ * Returns a non-empty list of parse nodes, determined by+ * the parseFn. This list begins with a lex token of openKind+ * and ends with a lex token of closeKind. Advances the parser+ * to the next lex token after the closing token.+ */+ ;++ _proto.many = function many(openKind, parseFn, closeKind) {+ this.expectToken(openKind);+ var nodes = [];++ do {+ nodes.push(parseFn.call(this));+ } while (!this.expectOptionalToken(closeKind));++ return nodes;+ };++ return Parser;+}();+/**+ * A helper function to describe a token as a string for debugging+ */+++function getTokenDesc(token) {+ var value = token.value;+ return getTokenKindDesc(token.kind) + (value != null ? " \"".concat(value, "\"") : '');+}+/**+ * A helper function to describe a token kind as a string for debugging+ */+++function getTokenKindDesc(kind) {+ return isPunctuatorTokenKind(kind) ? "\"".concat(kind, "\"") : kind;+}++/**+ * A visitor is provided to visit, it contains the collection of+ * relevant functions to be called during the visitor's traversal.+ */++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: ['description', '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', 'interfaces', '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', 'interfaces', 'directives', 'fields'],+ UnionTypeExtension: ['name', 'directives', 'types'],+ EnumTypeExtension: ['name', 'directives', 'values'],+ InputObjectTypeExtension: ['name', 'directives', 'fields']+};+var BREAK = Object.freeze({});+/**+ * 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 the+ * visitor API:+ *+ * 1) Named visitors triggered when entering a node of 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 _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) {+ var k = _Object$keys2[_i2];+ 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: ".concat(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 {+ var _visitorKeys$node$kin;++ stack = {+ inArray: inArray,+ index: index,+ keys: keys,+ edits: edits,+ prev: stack+ };+ inArray = Array.isArray(node);+ keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : [];+ 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;+}+/**+ * Creates a new visitor instance which delegates to many visitors to run in+ * parallel. Each visitor will be visited for each node before moving on.+ *+ * If a prior visitor edits a node, no following visitors will see that node.+ */++function visitInParallel(visitors) {+ var skipping = new Array(visitors.length);+ return {+ enter: function enter(node) {+ for (var i = 0; i < visitors.length; i++) {+ if (skipping[i] == null) {+ var fn = getVisitFn(visitors[i], node.kind,+ /* isLeaving */+ false);++ if (fn) {+ var result = fn.apply(visitors[i], arguments);++ if (result === false) {+ skipping[i] = node;+ } else if (result === BREAK) {+ skipping[i] = BREAK;+ } else if (result !== undefined) {+ return result;+ }+ }+ }+ }+ },+ leave: function leave(node) {+ for (var i = 0; i < visitors.length; i++) {+ if (skipping[i] == null) {+ var fn = getVisitFn(visitors[i], node.kind,+ /* isLeaving */+ true);++ if (fn) {+ var result = fn.apply(visitors[i], arguments);++ if (result === BREAK) {+ skipping[i] = BREAK;+ } else if (result !== undefined && result !== false) {+ return result;+ }+ }+ } else if (skipping[i] === node) {+ skipping[i] = null;+ }+ }+ }+ };+}+/**+ * 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;+ }+ }+ }+}++/* eslint-disable no-redeclare */+// $FlowFixMe+var find = Array.prototype.find ? function (list, predicate) {+ return Array.prototype.find.call(list, predicate);+} : function (list, predicate) {+ for (var _i2 = 0; _i2 < list.length; _i2++) {+ var value = list[_i2];++ if (predicate(value)) {+ return value;+ }+ }+};++var flatMapMethod = Array.prototype.flatMap;+/* eslint-disable no-redeclare */+// $FlowFixMe++var flatMap = flatMapMethod ? function (list, fn) {+ return flatMapMethod.call(list, fn);+} : function (list, fn) {+ var result = [];++ for (var _i2 = 0; _i2 < list.length; _i2++) {+ var _item = list[_i2];+ var value = fn(_item);++ if (Array.isArray(value)) {+ result = result.concat(value);+ } else {+ result.push(value);+ }+ }++ return result;+};++/* eslint-disable no-redeclare */+// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221+var objectValues = Object.values || function (obj) {+ return Object.keys(obj).map(function (key) {+ return obj[key];+ });+};++/**+ * Given an arbitrary Error, presumably thrown while attempting to execute a+ * GraphQL operation, produce a new GraphQLError aware of the location in the+ * document responsible for the original Error.+ */++function locatedError(originalError, nodes, path) {+ var _nodes;++ // Note: this uses a brand-check to support GraphQL errors originating from+ // other contexts.+ if (Array.isArray(originalError.path)) {+ return originalError;+ }++ return new GraphQLError(originalError.message, (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes, originalError.source, originalError.positions, path, originalError);+}++var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;+/**+ * Upholds the spec rules about naming.+ */++function assertValidName(name) {+ var error = isValidNameError(name);++ if (error) {+ throw error;+ }++ return name;+}+/**+ * Returns an Error if a name is invalid.+ */++function isValidNameError(name) {+ typeof name === 'string' || devAssert(0, 'Expected name to be a string.');++ if (name.length > 1 && name[0] === '_' && name[1] === '_') {+ return new GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by GraphQL introspection."));+ }++ if (!NAME_RX.test(name)) {+ return new GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."));+ }+}++/* eslint-disable no-redeclare */+// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/5838+var objectEntries = Object.entries || function (obj) {+ return Object.keys(obj).map(function (key) {+ return [key, obj[key]];+ });+};++/**+ * Creates a keyed JS object from an array, given a function to produce the keys+ * for each value in the array.+ *+ * This provides a convenient lookup for the array items if the key function+ * produces unique results.+ *+ * const phoneBook = [+ * { name: 'Jon', num: '555-1234' },+ * { name: 'Jenny', num: '867-5309' }+ * ]+ *+ * // { Jon: { name: 'Jon', num: '555-1234' },+ * // Jenny: { name: 'Jenny', num: '867-5309' } }+ * const entriesByName = keyMap(+ * phoneBook,+ * entry => entry.name+ * )+ *+ * // { name: 'Jenny', num: '857-6309' }+ * const jennyEntry = entriesByName['Jenny']+ *+ */+function keyMap(list, keyFn) {+ return list.reduce(function (map, item) {+ map[keyFn(item)] = item;+ return map;+ }, Object.create(null));+}++/**+ * Creates an object map with the same keys as `map` and values generated by+ * running each value of `map` thru `fn`.+ */+function mapValue(map, fn) {+ var result = Object.create(null);++ for (var _i2 = 0, _objectEntries2 = objectEntries(map); _i2 < _objectEntries2.length; _i2++) {+ var _ref2 = _objectEntries2[_i2];+ var _key = _ref2[0];+ var _value = _ref2[1];+ result[_key] = fn(_value, _key);+ }++ return result;+}++function toObjMap(obj) {+ /* eslint-enable no-redeclare */+ if (Object.getPrototypeOf(obj) === null) {+ return obj;+ }++ var map = Object.create(null);++ for (var _i2 = 0, _objectEntries2 = objectEntries(obj); _i2 < _objectEntries2.length; _i2++) {+ var _ref2 = _objectEntries2[_i2];+ var key = _ref2[0];+ var value = _ref2[1];+ map[key] = value;+ }++ return map;+}++/**+ * Creates a keyed JS object from an array, given a function to produce the keys+ * and a function to produce the values from each item in the array.+ *+ * const phoneBook = [+ * { name: 'Jon', num: '555-1234' },+ * { name: 'Jenny', num: '867-5309' }+ * ]+ *+ * // { Jon: '555-1234', Jenny: '867-5309' }+ * const phonesByName = keyValMap(+ * phoneBook,+ * entry => entry.name,+ * entry => entry.num+ * )+ *+ */+function keyValMap(list, keyFn, valFn) {+ return list.reduce(function (map, item) {+ map[keyFn(item)] = valFn(item);+ return map;+ }, Object.create(null));+}++/**+ * A replacement for instanceof which includes an error warning when multi-realm+ * constructors are detected.+ */+// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production+// See: https://webpack.js.org/guides/production/+var instanceOf = process.env.NODE_ENV === 'production' ? // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2317')+// eslint-disable-next-line no-shadow+function instanceOf(value, constructor) {+ return value instanceof constructor;+} : // eslint-disable-next-line no-shadow+function instanceOf(value, constructor) {+ if (value instanceof constructor) {+ return true;+ }++ if (value) {+ var valueClass = value.constructor;+ var className = constructor.name;++ if (className && valueClass && valueClass.name === className) {+ 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."));+ }+ }++ return false;+};++var MAX_SUGGESTIONS = 5;+/**+ * Given [ A, B, C ] return ' Did you mean A, B, or C?'.+ */++// eslint-disable-next-line no-redeclare+function didYouMean(firstArg, secondArg) {+ var _ref = typeof firstArg === 'string' ? [firstArg, secondArg] : [undefined, firstArg],+ subMessage = _ref[0],+ suggestionsArg = _ref[1];++ var message = ' Did you mean ';++ if (subMessage) {+ message += subMessage + ' ';+ }++ var suggestions = suggestionsArg.map(function (x) {+ return "\"".concat(x, "\"");+ });++ switch (suggestions.length) {+ case 0:+ return '';++ case 1:+ return message + suggestions[0] + '?';++ case 2:+ return message + suggestions[0] + ' or ' + suggestions[1] + '?';+ }++ var selected = suggestions.slice(0, MAX_SUGGESTIONS);+ var lastItem = selected.pop();+ return message + selected.join(', ') + ', or ' + lastItem + '?';+}++/**+ * Returns the first argument it receives.+ */+function identityFunc(x) {+ return x;+}++/**+ * Given an invalid input string and a list of valid options, returns a filtered+ * list of valid options sorted based on their similarity with the input.+ */+function suggestionList(input, options) {+ var optionsByDistance = Object.create(null);+ var lexicalDistance = new LexicalDistance(input);+ var threshold = Math.floor(input.length * 0.4) + 1;++ for (var _i2 = 0; _i2 < options.length; _i2++) {+ var option = options[_i2];+ var distance = lexicalDistance.measure(option, threshold);++ if (distance !== undefined) {+ optionsByDistance[option] = distance;+ }+ }++ return Object.keys(optionsByDistance).sort(function (a, b) {+ var distanceDiff = optionsByDistance[a] - optionsByDistance[b];+ return distanceDiff !== 0 ? distanceDiff : a.localeCompare(b);+ });+}+/**+ * Computes the lexical distance between strings A and B.+ *+ * The "distance" between two strings is given by counting the minimum number+ * of edits needed to transform string A into string B. An edit can be an+ * insertion, deletion, or substitution of a single character, or a swap of two+ * adjacent characters.+ *+ * Includes a custom alteration from Damerau-Levenshtein to treat case changes+ * as a single edit which helps identify mis-cased values with an edit distance+ * of 1.+ *+ * This distance can be useful for detecting typos in input or sorting+ */++var LexicalDistance = /*#__PURE__*/function () {+ function LexicalDistance(input) {+ this._input = input;+ this._inputLowerCase = input.toLowerCase();+ this._inputArray = stringToArray(this._inputLowerCase);+ this._rows = [new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0), new Array(input.length + 1).fill(0)];+ }++ var _proto = LexicalDistance.prototype;++ _proto.measure = function measure(option, threshold) {+ if (this._input === option) {+ return 0;+ }++ var optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit++ if (this._inputLowerCase === optionLowerCase) {+ return 1;+ }++ var a = stringToArray(optionLowerCase);+ var b = this._inputArray;++ if (a.length < b.length) {+ var tmp = a;+ a = b;+ b = tmp;+ }++ var aLength = a.length;+ var bLength = b.length;++ if (aLength - bLength > threshold) {+ return undefined;+ }++ var rows = this._rows;++ for (var j = 0; j <= bLength; j++) {+ rows[0][j] = j;+ }++ for (var i = 1; i <= aLength; i++) {+ var upRow = rows[(i - 1) % 3];+ var currentRow = rows[i % 3];+ var smallestCell = currentRow[0] = i;++ for (var _j = 1; _j <= bLength; _j++) {+ var cost = a[i - 1] === b[_j - 1] ? 0 : 1;+ var currentCell = Math.min(upRow[_j] + 1, // delete+ currentRow[_j - 1] + 1, // insert+ upRow[_j - 1] + cost // substitute+ );++ if (i > 1 && _j > 1 && a[i - 1] === b[_j - 2] && a[i - 2] === b[_j - 1]) {+ // transposition+ var doubleDiagonalCell = rows[(i - 2) % 3][_j - 2];+ currentCell = Math.min(currentCell, doubleDiagonalCell + 1);+ }++ if (currentCell < smallestCell) {+ smallestCell = currentCell;+ }++ currentRow[_j] = currentCell;+ } // Early exit, since distance can't go smaller than smallest element of the previous row.+++ if (smallestCell > threshold) {+ return undefined;+ }+ }++ var distance = rows[aLength % 3][bLength];+ return distance <= threshold ? distance : undefined;+ };++ return LexicalDistance;+}();++function stringToArray(str) {+ var strLength = str.length;+ var array = new Array(strLength);++ for (var i = 0; i < strLength; ++i) {+ array[i] = str.charCodeAt(i);+ }++ return array;+}++/**+ * Converts an AST into a string, using one set of reasonable+ * formatting rules.+ */++function print(ast) {+ return visit(ast, {+ leave: printDocASTReducer+ });+} // TODO: provide better type coverage in future++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: addDescription(function (_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 + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + ': ' + 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,+ interfaces = _ref26.interfaces,+ directives = _ref26.directives,+ fields = _ref26.fields;+ return join(['interface', name, wrap('implements ', join(interfaces, ' & ')), 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,+ repeatable = _ref31.repeatable,+ locations = _ref31.locations;+ return 'directive @' + name + (hasMultilineItems(args) ? wrap('(\n', indent(join(args, '\n')), '\n)') : wrap('(', join(args, ', '), ')')) + (repeatable ? ' repeatable' : '') + ' 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,+ interfaces = _ref35.interfaces,+ directives = _ref35.directives,+ fields = _ref35.fields;+ return join(['extend interface', name, wrap('implements ', join(interfaces, ' & ')), 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) {+ var _maybeArray$filter$jo;++ var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';+ return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter(function (x) {+ return x;+ }).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : '';+}+/**+ * 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) {+ var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';+ return maybeString ? start + maybeString + end : '';+}++function indent(maybeString) {+ return maybeString && ' ' + maybeString.replace(/\n/g, '\n ');+}++function isMultiline(string) {+ return string.indexOf('\n') !== -1;+}++function hasMultilineItems(maybeArray) {+ return maybeArray && maybeArray.some(isMultiline);+}++var printer = /*#__PURE__*/Object.freeze({+ __proto__: null,+ print: print+});++/**+ * Produces a JavaScript value given a GraphQL Value AST.+ *+ * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value+ * will reflect the provided GraphQL value AST.+ *+ * | GraphQL Value | JavaScript Value |+ * | -------------------- | ---------------- |+ * | Input Object | Object |+ * | List | Array |+ * | Boolean | Boolean |+ * | String / Enum | String |+ * | Int / Float | Number |+ * | Null | null |+ *+ */+function valueFromASTUntyped(valueNode, variables) {+ switch (valueNode.kind) {+ case Kind.NULL:+ return null;++ case Kind.INT:+ return parseInt(valueNode.value, 10);++ case Kind.FLOAT:+ return parseFloat(valueNode.value);++ case Kind.STRING:+ case Kind.ENUM:+ case Kind.BOOLEAN:+ return valueNode.value;++ case Kind.LIST:+ return valueNode.values.map(function (node) {+ return valueFromASTUntyped(node, variables);+ });++ case Kind.OBJECT:+ return keyValMap(valueNode.fields, function (field) {+ return field.name.value;+ }, function (field) {+ return valueFromASTUntyped(field.value, variables);+ });++ case Kind.VARIABLE:+ return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value];+ } // istanbul ignore next (Not reachable. All possible value nodes have been considered)+++ invariant(0, 'Unexpected value node: ' + inspect(valueNode));+}++function _defineProperties$2(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); } }++function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$2(Constructor.prototype, protoProps); if (staticProps) _defineProperties$2(Constructor, staticProps); return Constructor; }+function isType(type) {+ return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type);+}+function assertType(type) {+ if (!isType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL type."));+ }++ return type;+}+/**+ * There are predicates for each kind of GraphQL type.+ */++// eslint-disable-next-line no-redeclare+function isScalarType(type) {+ return instanceOf(type, GraphQLScalarType);+}+function assertScalarType(type) {+ if (!isScalarType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Scalar type."));+ }++ return type;+}+// eslint-disable-next-line no-redeclare+function isObjectType(type) {+ return instanceOf(type, GraphQLObjectType);+}+function assertObjectType(type) {+ if (!isObjectType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Object type."));+ }++ return type;+}+// eslint-disable-next-line no-redeclare+function isInterfaceType(type) {+ return instanceOf(type, GraphQLInterfaceType);+}+function assertInterfaceType(type) {+ if (!isInterfaceType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Interface type."));+ }++ return type;+}+// eslint-disable-next-line no-redeclare+function isUnionType(type) {+ return instanceOf(type, GraphQLUnionType);+}+function assertUnionType(type) {+ if (!isUnionType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Union type."));+ }++ return type;+}+// eslint-disable-next-line no-redeclare+function isEnumType(type) {+ return instanceOf(type, GraphQLEnumType);+}+function assertEnumType(type) {+ if (!isEnumType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Enum type."));+ }++ return type;+}+// eslint-disable-next-line no-redeclare+function isInputObjectType(type) {+ return instanceOf(type, GraphQLInputObjectType);+}+function assertInputObjectType(type) {+ if (!isInputObjectType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Input Object type."));+ }++ return type;+}+// eslint-disable-next-line no-redeclare+function isListType(type) {+ return instanceOf(type, GraphQLList);+}+function assertListType(type) {+ if (!isListType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL List type."));+ }++ return type;+}+// eslint-disable-next-line no-redeclare+function isNonNullType(type) {+ return instanceOf(type, GraphQLNonNull);+}+function assertNonNullType(type) {+ if (!isNonNullType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL Non-Null type."));+ }++ return type;+}+/**+ * These types may be used as input types for arguments and directives.+ */++function isInputType(type) {+ return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType);+}+function assertInputType(type) {+ if (!isInputType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL input type."));+ }++ return type;+}+/**+ * These types may be used as output types as the result of fields.+ */++function isOutputType(type) {+ return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType);+}+function assertOutputType(type) {+ if (!isOutputType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL output type."));+ }++ return type;+}+/**+ * These types may describe types which may be leaf values.+ */++function isLeafType(type) {+ return isScalarType(type) || isEnumType(type);+}+function assertLeafType(type) {+ if (!isLeafType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL leaf type."));+ }++ return type;+}+/**+ * These types may describe the parent context of a selection set.+ */++function isCompositeType(type) {+ return isObjectType(type) || isInterfaceType(type) || isUnionType(type);+}+function assertCompositeType(type) {+ if (!isCompositeType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL composite type."));+ }++ return type;+}+/**+ * These types may describe the parent context of a selection set.+ */++function isAbstractType(type) {+ return isInterfaceType(type) || isUnionType(type);+}+function assertAbstractType(type) {+ if (!isAbstractType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL abstract type."));+ }++ return type;+}+/**+ * List Type Wrapper+ *+ * A list is a wrapping type which points to another type.+ * Lists are often created within the context of defining the fields of+ * an object type.+ *+ * Example:+ *+ * const PersonType = new GraphQLObjectType({+ * name: 'Person',+ * fields: () => ({+ * parents: { type: GraphQLList(PersonType) },+ * children: { type: GraphQLList(PersonType) },+ * })+ * })+ *+ */+// FIXME: workaround to fix issue with Babel parser++/* ::+declare class GraphQLList<+T: GraphQLType> {+ +ofType: T;+ static <T>(ofType: T): GraphQLList<T>;+ // Note: constructors cannot be used for covariant types. Drop the "new".+ constructor(ofType: GraphQLType): void;+}+*/++function GraphQLList(ofType) {+ if (this instanceof GraphQLList) {+ this.ofType = assertType(ofType);+ } else {+ return new GraphQLList(ofType);+ }+} // Need to cast through any to alter the prototype.++GraphQLList.prototype.toString = function toString() {+ return '[' + String(this.ofType) + ']';+};++GraphQLList.prototype.toJSON = function toJSON() {+ return this.toString();+};++Object.defineProperty(GraphQLList.prototype, SYMBOL_TO_STRING_TAG, {+ get: function get() {+ return 'GraphQLList';+ }+}); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLList);+/**+ * Non-Null Type Wrapper+ *+ * A non-null is a wrapping type which points to another type.+ * Non-null types enforce that their values are never null and can ensure+ * an error is raised if this ever occurs during a request. It is useful for+ * fields which you can make a strong guarantee on non-nullability, for example+ * usually the id field of a database row will never be null.+ *+ * Example:+ *+ * const RowType = new GraphQLObjectType({+ * name: 'Row',+ * fields: () => ({+ * id: { type: GraphQLNonNull(GraphQLString) },+ * })+ * })+ *+ * Note: the enforcement of non-nullability occurs within the executor.+ */+// FIXME: workaround to fix issue with Babel parser++/* ::+declare class GraphQLNonNull<+T: GraphQLNullableType> {+ +ofType: T;+ static <T>(ofType: T): GraphQLNonNull<T>;+ // Note: constructors cannot be used for covariant types. Drop the "new".+ constructor(ofType: GraphQLType): void;+}+*/++function GraphQLNonNull(ofType) {+ if (this instanceof GraphQLNonNull) {+ this.ofType = assertNullableType(ofType);+ } else {+ return new GraphQLNonNull(ofType);+ }+} // Need to cast through any to alter the prototype.++GraphQLNonNull.prototype.toString = function toString() {+ return String(this.ofType) + '!';+};++GraphQLNonNull.prototype.toJSON = function toJSON() {+ return this.toString();+};++Object.defineProperty(GraphQLNonNull.prototype, SYMBOL_TO_STRING_TAG, {+ get: function get() {+ return 'GraphQLNonNull';+ }+}); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLNonNull);+/**+ * These types wrap and modify other types+ */++function isWrappingType(type) {+ return isListType(type) || isNonNullType(type);+}+function assertWrappingType(type) {+ if (!isWrappingType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL wrapping type."));+ }++ return type;+}+/**+ * These types can all accept null as a value.+ */++function isNullableType(type) {+ return isType(type) && !isNonNullType(type);+}+function assertNullableType(type) {+ if (!isNullableType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL nullable type."));+ }++ return type;+}+/* eslint-disable no-redeclare */++function getNullableType(type) {+ /* eslint-enable no-redeclare */+ if (type) {+ return isNonNullType(type) ? type.ofType : type;+ }+}+/**+ * These named types do not include modifiers like List or NonNull.+ */++function isNamedType(type) {+ return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type);+}+function assertNamedType(type) {+ if (!isNamedType(type)) {+ throw new Error("Expected ".concat(inspect(type), " to be a GraphQL named type."));+ }++ return type;+}+/* eslint-disable no-redeclare */++function getNamedType(type) {+ /* eslint-enable no-redeclare */+ if (type) {+ var unwrappedType = type;++ while (isWrappingType(unwrappedType)) {+ unwrappedType = unwrappedType.ofType;+ }++ return unwrappedType;+ }+}+/**+ * Used while defining GraphQL types to allow for circular references in+ * otherwise immutable type definitions.+ */++function resolveThunk(thunk) {+ // $FlowFixMe(>=0.90.0)+ return typeof thunk === 'function' ? thunk() : thunk;+}++function undefineIfEmpty(arr) {+ return arr && arr.length > 0 ? arr : undefined;+}+/**+ * Scalar Type Definition+ *+ * The leaf values of any request and input values to arguments are+ * Scalars (or Enums) and are defined with a name and a series of functions+ * used to parse input from ast or variables and to ensure validity.+ *+ * If a type's serialize function does not return a value (i.e. it returns+ * `undefined`) then an error will be raised and a `null` value will be returned+ * in the response. If the serialize function returns `null`, then no error will+ * be included in the response.+ *+ * Example:+ *+ * const OddType = new GraphQLScalarType({+ * name: 'Odd',+ * serialize(value) {+ * if (value % 2 === 1) {+ * return value;+ * }+ * }+ * });+ *+ */+++var GraphQLScalarType = /*#__PURE__*/function () {+ function GraphQLScalarType(config) {+ var _config$parseValue, _config$serialize, _config$parseLiteral;++ var parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : identityFunc;+ this.name = config.name;+ this.description = config.description;+ this.specifiedByUrl = config.specifiedByUrl;+ this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : identityFunc;+ this.parseValue = parseValue;+ this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : function (node) {+ return parseValue(valueFromASTUntyped(node));+ };+ this.extensions = config.extensions && toObjMap(config.extensions);+ this.astNode = config.astNode;+ this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);+ typeof config.name === 'string' || devAssert(0, 'Must provide name.');+ config.specifiedByUrl == null || typeof config.specifiedByUrl === 'string' || devAssert(0, "".concat(this.name, " must provide \"specifiedByUrl\" as a string, ") + "but got: ".concat(inspect(config.specifiedByUrl), "."));+ 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."));++ if (config.parseLiteral) {+ typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function' || devAssert(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" functions."));+ }+ }++ var _proto = GraphQLScalarType.prototype;++ _proto.toConfig = function toConfig() {+ var _this$extensionASTNod;++ return {+ name: this.name,+ description: this.description,+ specifiedByUrl: this.specifiedByUrl,+ serialize: this.serialize,+ parseValue: this.parseValue,+ parseLiteral: this.parseLiteral,+ extensions: this.extensions,+ astNode: this.astNode,+ extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : []+ };+ };++ _proto.toString = function toString() {+ return this.name;+ };++ _proto.toJSON = function toJSON() {+ return this.toString();+ } // $FlowFixMe Flow doesn't support computed properties yet+ ;++ _createClass$2(GraphQLScalarType, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'GraphQLScalarType';+ }+ }]);++ return GraphQLScalarType;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLScalarType);++/**+ * Object Type Definition+ *+ * Almost all of the GraphQL types you define will be object types. Object types+ * have a name, but most importantly describe their fields.+ *+ * Example:+ *+ * const AddressType = new GraphQLObjectType({+ * name: 'Address',+ * fields: {+ * street: { type: GraphQLString },+ * number: { type: GraphQLInt },+ * formatted: {+ * type: GraphQLString,+ * resolve(obj) {+ * return obj.number + ' ' + obj.street+ * }+ * }+ * }+ * });+ *+ * When two types need to refer to each other, or a type needs to refer to+ * itself in a field, you can use a function expression (aka a closure or a+ * thunk) to supply the fields lazily.+ *+ * Example:+ *+ * const PersonType = new GraphQLObjectType({+ * name: 'Person',+ * fields: () => ({+ * name: { type: GraphQLString },+ * bestFriend: { type: PersonType },+ * })+ * });+ *+ */+var GraphQLObjectType = /*#__PURE__*/function () {+ function GraphQLObjectType(config) {+ this.name = config.name;+ this.description = config.description;+ this.isTypeOf = config.isTypeOf;+ this.extensions = config.extensions && toObjMap(config.extensions);+ this.astNode = config.astNode;+ this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);+ this._fields = defineFieldMap.bind(undefined, config);+ this._interfaces = defineInterfaces.bind(undefined, config);+ typeof config.name === 'string' || devAssert(0, 'Must provide name.');+ config.isTypeOf == null || typeof config.isTypeOf === 'function' || devAssert(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat(inspect(config.isTypeOf), "."));+ }++ var _proto2 = GraphQLObjectType.prototype;++ _proto2.getFields = function getFields() {+ if (typeof this._fields === 'function') {+ this._fields = this._fields();+ }++ return this._fields;+ };++ _proto2.getInterfaces = function getInterfaces() {+ if (typeof this._interfaces === 'function') {+ this._interfaces = this._interfaces();+ }++ return this._interfaces;+ };++ _proto2.toConfig = function toConfig() {+ return {+ name: this.name,+ description: this.description,+ interfaces: this.getInterfaces(),+ fields: fieldsToFieldsConfig(this.getFields()),+ isTypeOf: this.isTypeOf,+ extensions: this.extensions,+ astNode: this.astNode,+ extensionASTNodes: this.extensionASTNodes || []+ };+ };++ _proto2.toString = function toString() {+ return this.name;+ };++ _proto2.toJSON = function toJSON() {+ return this.toString();+ } // $FlowFixMe Flow doesn't support computed properties yet+ ;++ _createClass$2(GraphQLObjectType, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'GraphQLObjectType';+ }+ }]);++ return GraphQLObjectType;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLObjectType);++function defineInterfaces(config) {+ var _resolveThunk;++ var interfaces = (_resolveThunk = resolveThunk(config.interfaces)) !== null && _resolveThunk !== void 0 ? _resolveThunk : [];+ Array.isArray(interfaces) || devAssert(0, "".concat(config.name, " interfaces must be an Array or a function which returns an Array."));+ return interfaces;+}++function defineFieldMap(config) {+ var fieldMap = resolveThunk(config.fields);+ 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."));+ return mapValue(fieldMap, function (fieldConfig, fieldName) {+ var _fieldConfig$args;++ isPlainObj(fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object."));+ !('isDeprecated' in fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" instead of \"isDeprecated\"."));+ 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), "."));+ var argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {};+ isPlainObj(argsConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument names as keys."));+ var args = objectEntries(argsConfig).map(function (_ref) {+ var argName = _ref[0],+ argConfig = _ref[1];+ return {+ name: argName,+ description: argConfig.description,+ type: argConfig.type,+ defaultValue: argConfig.defaultValue,+ extensions: argConfig.extensions && toObjMap(argConfig.extensions),+ astNode: argConfig.astNode+ };+ });+ return {+ name: fieldName,+ description: fieldConfig.description,+ type: fieldConfig.type,+ args: args,+ resolve: fieldConfig.resolve,+ subscribe: fieldConfig.subscribe,+ isDeprecated: fieldConfig.deprecationReason != null,+ deprecationReason: fieldConfig.deprecationReason,+ extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions),+ astNode: fieldConfig.astNode+ };+ });+}++function isPlainObj(obj) {+ return isObjectLike(obj) && !Array.isArray(obj);+}++function fieldsToFieldsConfig(fields) {+ return mapValue(fields, function (field) {+ return {+ description: field.description,+ type: field.type,+ args: argsToArgsConfig(field.args),+ resolve: field.resolve,+ subscribe: field.subscribe,+ deprecationReason: field.deprecationReason,+ extensions: field.extensions,+ astNode: field.astNode+ };+ });+}+/**+ * @internal+ */+++function argsToArgsConfig(args) {+ return keyValMap(args, function (arg) {+ return arg.name;+ }, function (arg) {+ return {+ description: arg.description,+ type: arg.type,+ defaultValue: arg.defaultValue,+ extensions: arg.extensions,+ astNode: arg.astNode+ };+ });+}+function isRequiredArgument(arg) {+ return isNonNullType(arg.type) && arg.defaultValue === undefined;+}++/**+ * Interface Type Definition+ *+ * When a field can return one of a heterogeneous set of types, a Interface type+ * is used to describe what types are possible, what fields are in common across+ * all types, as well as a function to determine which type is actually used+ * when the field is resolved.+ *+ * Example:+ *+ * const EntityType = new GraphQLInterfaceType({+ * name: 'Entity',+ * fields: {+ * name: { type: GraphQLString }+ * }+ * });+ *+ */+var GraphQLInterfaceType = /*#__PURE__*/function () {+ function GraphQLInterfaceType(config) {+ this.name = config.name;+ this.description = config.description;+ this.resolveType = config.resolveType;+ this.extensions = config.extensions && toObjMap(config.extensions);+ this.astNode = config.astNode;+ this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);+ this._fields = defineFieldMap.bind(undefined, config);+ this._interfaces = defineInterfaces.bind(undefined, config);+ typeof config.name === 'string' || devAssert(0, 'Must provide name.');+ config.resolveType == null || typeof config.resolveType === 'function' || devAssert(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), "."));+ }++ var _proto3 = GraphQLInterfaceType.prototype;++ _proto3.getFields = function getFields() {+ if (typeof this._fields === 'function') {+ this._fields = this._fields();+ }++ return this._fields;+ };++ _proto3.getInterfaces = function getInterfaces() {+ if (typeof this._interfaces === 'function') {+ this._interfaces = this._interfaces();+ }++ return this._interfaces;+ };++ _proto3.toConfig = function toConfig() {+ var _this$extensionASTNod2;++ return {+ name: this.name,+ description: this.description,+ interfaces: this.getInterfaces(),+ fields: fieldsToFieldsConfig(this.getFields()),+ resolveType: this.resolveType,+ extensions: this.extensions,+ astNode: this.astNode,+ extensionASTNodes: (_this$extensionASTNod2 = this.extensionASTNodes) !== null && _this$extensionASTNod2 !== void 0 ? _this$extensionASTNod2 : []+ };+ };++ _proto3.toString = function toString() {+ return this.name;+ };++ _proto3.toJSON = function toJSON() {+ return this.toString();+ } // $FlowFixMe Flow doesn't support computed properties yet+ ;++ _createClass$2(GraphQLInterfaceType, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'GraphQLInterfaceType';+ }+ }]);++ return GraphQLInterfaceType;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLInterfaceType);++/**+ * Union Type Definition+ *+ * When a field can return one of a heterogeneous set of types, a Union type+ * is used to describe what types are possible as well as providing a function+ * to determine which type is actually used when the field is resolved.+ *+ * Example:+ *+ * const PetType = new GraphQLUnionType({+ * name: 'Pet',+ * types: [ DogType, CatType ],+ * resolveType(value) {+ * if (value instanceof Dog) {+ * return DogType;+ * }+ * if (value instanceof Cat) {+ * return CatType;+ * }+ * }+ * });+ *+ */+var GraphQLUnionType = /*#__PURE__*/function () {+ function GraphQLUnionType(config) {+ this.name = config.name;+ this.description = config.description;+ this.resolveType = config.resolveType;+ this.extensions = config.extensions && toObjMap(config.extensions);+ this.astNode = config.astNode;+ this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);+ this._types = defineTypes.bind(undefined, config);+ typeof config.name === 'string' || devAssert(0, 'Must provide name.');+ config.resolveType == null || typeof config.resolveType === 'function' || devAssert(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), "."));+ }++ var _proto4 = GraphQLUnionType.prototype;++ _proto4.getTypes = function getTypes() {+ if (typeof this._types === 'function') {+ this._types = this._types();+ }++ return this._types;+ };++ _proto4.toConfig = function toConfig() {+ var _this$extensionASTNod3;++ return {+ name: this.name,+ description: this.description,+ types: this.getTypes(),+ resolveType: this.resolveType,+ extensions: this.extensions,+ astNode: this.astNode,+ extensionASTNodes: (_this$extensionASTNod3 = this.extensionASTNodes) !== null && _this$extensionASTNod3 !== void 0 ? _this$extensionASTNod3 : []+ };+ };++ _proto4.toString = function toString() {+ return this.name;+ };++ _proto4.toJSON = function toJSON() {+ return this.toString();+ } // $FlowFixMe Flow doesn't support computed properties yet+ ;++ _createClass$2(GraphQLUnionType, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'GraphQLUnionType';+ }+ }]);++ return GraphQLUnionType;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLUnionType);++function defineTypes(config) {+ var types = resolveThunk(config.types);+ Array.isArray(types) || devAssert(0, "Must provide Array of types or a function which returns such an array for Union ".concat(config.name, "."));+ return types;+}++/**+ * Enum Type Definition+ *+ * Some leaf values of requests and input values are Enums. GraphQL serializes+ * Enum values as strings, however internally Enums can be represented by any+ * kind of type, often integers.+ *+ * Example:+ *+ * const RGBType = new GraphQLEnumType({+ * name: 'RGB',+ * values: {+ * RED: { value: 0 },+ * GREEN: { value: 1 },+ * BLUE: { value: 2 }+ * }+ * });+ *+ * Note: If a value is not provided in a definition, the name of the enum value+ * will be used as its internal value.+ */+var GraphQLEnumType+/* <T> */+= /*#__PURE__*/function () {+ function GraphQLEnumType(config) {+ this.name = config.name;+ this.description = config.description;+ this.extensions = config.extensions && toObjMap(config.extensions);+ this.astNode = config.astNode;+ this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);+ this._values = defineEnumValues(this.name, config.values);+ this._valueLookup = new Map(this._values.map(function (enumValue) {+ return [enumValue.value, enumValue];+ }));+ this._nameLookup = keyMap(this._values, function (value) {+ return value.name;+ });+ typeof config.name === 'string' || devAssert(0, 'Must provide name.');+ }++ var _proto5 = GraphQLEnumType.prototype;++ _proto5.getValues = function getValues() {+ return this._values;+ };++ _proto5.getValue = function getValue(name) {+ return this._nameLookup[name];+ };++ _proto5.serialize = function serialize(outputValue) {+ var enumValue = this._valueLookup.get(outputValue);++ if (enumValue === undefined) {+ throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent value: ").concat(inspect(outputValue)));+ }++ return enumValue.name;+ };++ _proto5.parseValue = function parseValue(inputValue)+ /* T */+ {+ if (typeof inputValue !== 'string') {+ var valueStr = inspect(inputValue);+ throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-string value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr));+ }++ var enumValue = this.getValue(inputValue);++ if (enumValue == null) {+ throw new GraphQLError("Value \"".concat(inputValue, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, inputValue));+ }++ return enumValue.value;+ };++ _proto5.parseLiteral = function parseLiteral(valueNode, _variables)+ /* T */+ {+ // Note: variables will be resolved to a value before calling this function.+ if (valueNode.kind !== Kind.ENUM) {+ var valueStr = print(valueNode);+ throw new GraphQLError("Enum \"".concat(this.name, "\" cannot represent non-enum value: ").concat(valueStr, ".") + didYouMeanEnumValue(this, valueStr), valueNode);+ }++ var enumValue = this.getValue(valueNode.value);++ if (enumValue == null) {+ var _valueStr = print(valueNode);++ throw new GraphQLError("Value \"".concat(_valueStr, "\" does not exist in \"").concat(this.name, "\" enum.") + didYouMeanEnumValue(this, _valueStr), valueNode);+ }++ return enumValue.value;+ };++ _proto5.toConfig = function toConfig() {+ var _this$extensionASTNod4;++ var values = keyValMap(this.getValues(), function (value) {+ return value.name;+ }, function (value) {+ return {+ description: value.description,+ value: value.value,+ deprecationReason: value.deprecationReason,+ extensions: value.extensions,+ astNode: value.astNode+ };+ });+ return {+ name: this.name,+ description: this.description,+ values: values,+ extensions: this.extensions,+ astNode: this.astNode,+ extensionASTNodes: (_this$extensionASTNod4 = this.extensionASTNodes) !== null && _this$extensionASTNod4 !== void 0 ? _this$extensionASTNod4 : []+ };+ };++ _proto5.toString = function toString() {+ return this.name;+ };++ _proto5.toJSON = function toJSON() {+ return this.toString();+ } // $FlowFixMe Flow doesn't support computed properties yet+ ;++ _createClass$2(GraphQLEnumType, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'GraphQLEnumType';+ }+ }]);++ return GraphQLEnumType;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLEnumType);++function didYouMeanEnumValue(enumType, unknownValueStr) {+ var allNames = enumType.getValues().map(function (value) {+ return value.name;+ });+ var suggestedValues = suggestionList(unknownValueStr, allNames);+ return didYouMean('the enum value', suggestedValues);+}++function defineEnumValues(typeName, valueMap) {+ isPlainObj(valueMap) || devAssert(0, "".concat(typeName, " values must be an object with value names as keys."));+ return objectEntries(valueMap).map(function (_ref2) {+ var valueName = _ref2[0],+ valueConfig = _ref2[1];+ 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), "."));+ !('isDeprecated' in valueConfig) || devAssert(0, "".concat(typeName, ".").concat(valueName, " should provide \"deprecationReason\" instead of \"isDeprecated\"."));+ return {+ name: valueName,+ description: valueConfig.description,+ value: valueConfig.value !== undefined ? valueConfig.value : valueName,+ isDeprecated: valueConfig.deprecationReason != null,+ deprecationReason: valueConfig.deprecationReason,+ extensions: valueConfig.extensions && toObjMap(valueConfig.extensions),+ astNode: valueConfig.astNode+ };+ });+}++/**+ * Input Object Type Definition+ *+ * An input object defines a structured collection of fields which may be+ * supplied to a field argument.+ *+ * Using `NonNull` will ensure that a value must be provided by the query+ *+ * Example:+ *+ * const GeoPoint = new GraphQLInputObjectType({+ * name: 'GeoPoint',+ * fields: {+ * lat: { type: GraphQLNonNull(GraphQLFloat) },+ * lon: { type: GraphQLNonNull(GraphQLFloat) },+ * alt: { type: GraphQLFloat, defaultValue: 0 },+ * }+ * });+ *+ */+var GraphQLInputObjectType = /*#__PURE__*/function () {+ function GraphQLInputObjectType(config) {+ this.name = config.name;+ this.description = config.description;+ this.extensions = config.extensions && toObjMap(config.extensions);+ this.astNode = config.astNode;+ this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);+ this._fields = defineInputFieldMap.bind(undefined, config);+ typeof config.name === 'string' || devAssert(0, 'Must provide name.');+ }++ var _proto6 = GraphQLInputObjectType.prototype;++ _proto6.getFields = function getFields() {+ if (typeof this._fields === 'function') {+ this._fields = this._fields();+ }++ return this._fields;+ };++ _proto6.toConfig = function toConfig() {+ var _this$extensionASTNod5;++ var fields = mapValue(this.getFields(), function (field) {+ return {+ description: field.description,+ type: field.type,+ defaultValue: field.defaultValue,+ extensions: field.extensions,+ astNode: field.astNode+ };+ });+ return {+ name: this.name,+ description: this.description,+ fields: fields,+ extensions: this.extensions,+ astNode: this.astNode,+ extensionASTNodes: (_this$extensionASTNod5 = this.extensionASTNodes) !== null && _this$extensionASTNod5 !== void 0 ? _this$extensionASTNod5 : []+ };+ };++ _proto6.toString = function toString() {+ return this.name;+ };++ _proto6.toJSON = function toJSON() {+ return this.toString();+ } // $FlowFixMe Flow doesn't support computed properties yet+ ;++ _createClass$2(GraphQLInputObjectType, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'GraphQLInputObjectType';+ }+ }]);++ return GraphQLInputObjectType;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLInputObjectType);++function defineInputFieldMap(config) {+ var fieldMap = resolveThunk(config.fields);+ 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."));+ return mapValue(fieldMap, function (fieldConfig, fieldName) {+ !('resolve' in fieldConfig) || devAssert(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but Input Types cannot define resolvers."));+ return {+ name: fieldName,+ description: fieldConfig.description,+ type: fieldConfig.type,+ defaultValue: fieldConfig.defaultValue,+ extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions),+ astNode: fieldConfig.astNode+ };+ });+}++function isRequiredInputField(field) {+ return isNonNullType(field.type) && field.defaultValue === undefined;+}++/**+ * Provided two types, return true if the types are equal (invariant).+ */++function isEqualType(typeA, typeB) {+ // Equivalent types are equal.+ if (typeA === typeB) {+ return true;+ } // If either type is non-null, the other must also be non-null.+++ if (isNonNullType(typeA) && isNonNullType(typeB)) {+ return isEqualType(typeA.ofType, typeB.ofType);+ } // If either type is a list, the other must also be a list.+++ if (isListType(typeA) && isListType(typeB)) {+ return isEqualType(typeA.ofType, typeB.ofType);+ } // Otherwise the types are not equal.+++ return false;+}+/**+ * Provided a type and a super type, return true if the first type is either+ * equal or a subset of the second super type (covariant).+ */++function isTypeSubTypeOf(schema, maybeSubType, superType) {+ // Equivalent type is a valid subtype+ if (maybeSubType === superType) {+ return true;+ } // If superType is non-null, maybeSubType must also be non-null.+++ if (isNonNullType(superType)) {+ if (isNonNullType(maybeSubType)) {+ return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);+ }++ return false;+ }++ if (isNonNullType(maybeSubType)) {+ // If superType is nullable, maybeSubType may be non-null or nullable.+ return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);+ } // If superType type is a list, maybeSubType type must also be a list.+++ if (isListType(superType)) {+ if (isListType(maybeSubType)) {+ return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);+ }++ return false;+ }++ if (isListType(maybeSubType)) {+ // If superType is not a list, maybeSubType must also be not a list.+ return false;+ } // If superType type is an abstract type, check if it is super type of maybeSubType.+ // Otherwise, the child type is not a valid subtype of the parent type.+++ return isAbstractType(superType) && (isInterfaceType(maybeSubType) || isObjectType(maybeSubType)) && schema.isSubType(superType, maybeSubType);+}+/**+ * Provided two composite types, determine if they "overlap". Two composite+ * types overlap when the Sets of possible concrete types for each intersect.+ *+ * This is often used to determine if a fragment of a given type could possibly+ * be visited in a context of another type.+ *+ * This function is commutative.+ */++function doTypesOverlap(schema, typeA, typeB) {+ // Equivalent types overlap+ if (typeA === typeB) {+ return true;+ }++ if (isAbstractType(typeA)) {+ if (isAbstractType(typeB)) {+ // If both types are abstract, then determine if there is any intersection+ // between possible concrete types of each.+ return schema.getPossibleTypes(typeA).some(function (type) {+ return schema.isSubType(typeB, type);+ });+ } // Determine if the latter type is a possible concrete type of the former.+++ return schema.isSubType(typeA, typeB);+ }++ if (isAbstractType(typeB)) {+ // Determine if the former type is a possible concrete type of the latter.+ return schema.isSubType(typeB, typeA);+ } // Otherwise the types do not overlap.+++ return false;+}++/* eslint-disable no-redeclare */+// $FlowFixMe+var arrayFrom = Array.from || function (obj, mapFn, thisArg) {+ if (obj == null) {+ throw new TypeError('Array.from requires an array-like object - not null or undefined');+ } // Is Iterable?+++ var iteratorMethod = obj[SYMBOL_ITERATOR];++ if (typeof iteratorMethod === 'function') {+ var iterator = iteratorMethod.call(obj);+ var result = [];+ var step;++ for (var i = 0; !(step = iterator.next()).done; ++i) {+ result.push(mapFn.call(thisArg, step.value, i)); // Infinite Iterators could cause forEach to run forever.+ // After a very large number of iterations, produce an error.+ // istanbul ignore if (Too big to actually test)++ if (i > 9999999) {+ throw new TypeError('Near-infinite iteration.');+ }+ }++ return result;+ } // Is Array like?+++ var length = obj.length;++ if (typeof length === 'number' && length >= 0 && length % 1 === 0) {+ var _result = [];++ for (var _i = 0; _i < length; ++_i) {+ if (Object.prototype.hasOwnProperty.call(obj, _i)) {+ _result.push(mapFn.call(thisArg, obj[_i], _i));+ }+ }++ return _result;+ }++ return [];+};++/* eslint-disable no-redeclare */+// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441+var isFinitePolyfill = Number.isFinite || function (value) {+ return typeof value === 'number' && isFinite(value);+};++function _typeof$3(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$3 = function _typeof(obj) { return typeof obj; }; } else { _typeof$3 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$3(obj); }+/**+ * Returns true if the provided object is an Object (i.e. not a string literal)+ * and is either Iterable or Array-like.+ *+ * This may be used in place of [Array.isArray()][isArray] to determine if an+ * object should be iterated-over. It always excludes string literals and+ * includes Arrays (regardless of if it is Iterable). It also includes other+ * Array-like objects such as NodeList, TypedArray, and Buffer.+ *+ * @example+ *+ * isCollection([ 1, 2, 3 ]) // true+ * isCollection('ABC') // false+ * isCollection({ length: 1, 0: 'Alpha' }) // true+ * isCollection({ key: 'value' }) // false+ * isCollection(new Map()) // true+ *+ * @param obj+ * An Object value which might implement the Iterable or Array-like protocols.+ * @return {boolean} true if Iterable or Array-like Object.+ */++function isCollection(obj) {+ if (obj == null || _typeof$3(obj) !== 'object') {+ return false;+ } // Is Array like?+++ var length = obj.length;++ if (typeof length === 'number' && length >= 0 && length % 1 === 0) {+ return true;+ } // Is Iterable?+++ return typeof obj[SYMBOL_ITERATOR] === 'function';+}++/* eslint-disable no-redeclare */+// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441+var isInteger = Number.isInteger || function (value) {+ return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;+};++// 32-bit signed integer, providing the broadest support across platforms.+//+// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because+// they are internally represented as IEEE 754 doubles.++var MAX_INT = 2147483647;+var MIN_INT = -2147483648;++function serializeInt(outputValue) {+ var coercedValue = serializeObject(outputValue);++ if (typeof coercedValue === 'boolean') {+ return coercedValue ? 1 : 0;+ }++ var num = coercedValue;++ if (typeof coercedValue === 'string' && coercedValue !== '') {+ num = Number(coercedValue);+ }++ if (!isInteger(num)) {+ throw new GraphQLError("Int cannot represent non-integer value: ".concat(inspect(coercedValue)));+ }++ if (num > MAX_INT || num < MIN_INT) {+ throw new GraphQLError('Int cannot represent non 32-bit signed integer value: ' + inspect(coercedValue));+ }++ return num;+}++function coerceInt(inputValue) {+ if (!isInteger(inputValue)) {+ throw new GraphQLError("Int cannot represent non-integer value: ".concat(inspect(inputValue)));+ }++ if (inputValue > MAX_INT || inputValue < MIN_INT) {+ throw new GraphQLError("Int cannot represent non 32-bit signed integer value: ".concat(inputValue));+ }++ return inputValue;+}++var GraphQLInt = new GraphQLScalarType({+ name: 'Int',+ description: 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.',+ serialize: serializeInt,+ parseValue: coerceInt,+ parseLiteral: function parseLiteral(valueNode) {+ if (valueNode.kind !== Kind.INT) {+ throw new GraphQLError("Int cannot represent non-integer value: ".concat(print(valueNode)), valueNode);+ }++ var num = parseInt(valueNode.value, 10);++ if (num > MAX_INT || num < MIN_INT) {+ throw new GraphQLError("Int cannot represent non 32-bit signed integer value: ".concat(valueNode.value), valueNode);+ }++ return num;+ }+});++function serializeFloat(outputValue) {+ var coercedValue = serializeObject(outputValue);++ if (typeof coercedValue === 'boolean') {+ return coercedValue ? 1 : 0;+ }++ var num = coercedValue;++ if (typeof coercedValue === 'string' && coercedValue !== '') {+ num = Number(coercedValue);+ }++ if (!isFinitePolyfill(num)) {+ throw new GraphQLError("Float cannot represent non numeric value: ".concat(inspect(coercedValue)));+ }++ return num;+}++function coerceFloat(inputValue) {+ if (!isFinitePolyfill(inputValue)) {+ throw new GraphQLError("Float cannot represent non numeric value: ".concat(inspect(inputValue)));+ }++ return inputValue;+}++var GraphQLFloat = new GraphQLScalarType({+ name: 'Float',+ description: 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).',+ serialize: serializeFloat,+ parseValue: coerceFloat,+ parseLiteral: function parseLiteral(valueNode) {+ if (valueNode.kind !== Kind.FLOAT && valueNode.kind !== Kind.INT) {+ throw new GraphQLError("Float cannot represent non numeric value: ".concat(print(valueNode)), valueNode);+ }++ return parseFloat(valueNode.value);+ }+}); // Support serializing objects with custom valueOf() or toJSON() functions -+// a common way to represent a complex value which can be represented as+// a string (ex: MongoDB id objects).++function serializeObject(outputValue) {+ if (isObjectLike(outputValue)) {+ if (typeof outputValue.valueOf === 'function') {+ var valueOfResult = outputValue.valueOf();++ if (!isObjectLike(valueOfResult)) {+ return valueOfResult;+ }+ }++ if (typeof outputValue.toJSON === 'function') {+ // $FlowFixMe(>=0.90.0)+ return outputValue.toJSON();+ }+ }++ return outputValue;+}++function serializeString(outputValue) {+ var coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not+ // attempt to coerce object, function, symbol, or other types as strings.++ if (typeof coercedValue === 'string') {+ return coercedValue;+ }++ if (typeof coercedValue === 'boolean') {+ return coercedValue ? 'true' : 'false';+ }++ if (isFinitePolyfill(coercedValue)) {+ return coercedValue.toString();+ }++ throw new GraphQLError("String cannot represent value: ".concat(inspect(outputValue)));+}++function coerceString(inputValue) {+ if (typeof inputValue !== 'string') {+ throw new GraphQLError("String cannot represent a non string value: ".concat(inspect(inputValue)));+ }++ return inputValue;+}++var GraphQLString = new GraphQLScalarType({+ name: 'String',+ description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.',+ serialize: serializeString,+ parseValue: coerceString,+ parseLiteral: function parseLiteral(valueNode) {+ if (valueNode.kind !== Kind.STRING) {+ throw new GraphQLError("String cannot represent a non string value: ".concat(print(valueNode)), valueNode);+ }++ return valueNode.value;+ }+});++function serializeBoolean(outputValue) {+ var coercedValue = serializeObject(outputValue);++ if (typeof coercedValue === 'boolean') {+ return coercedValue;+ }++ if (isFinitePolyfill(coercedValue)) {+ return coercedValue !== 0;+ }++ throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(inspect(coercedValue)));+}++function coerceBoolean(inputValue) {+ if (typeof inputValue !== 'boolean') {+ throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(inspect(inputValue)));+ }++ return inputValue;+}++var GraphQLBoolean = new GraphQLScalarType({+ name: 'Boolean',+ description: 'The `Boolean` scalar type represents `true` or `false`.',+ serialize: serializeBoolean,+ parseValue: coerceBoolean,+ parseLiteral: function parseLiteral(valueNode) {+ if (valueNode.kind !== Kind.BOOLEAN) {+ throw new GraphQLError("Boolean cannot represent a non boolean value: ".concat(print(valueNode)), valueNode);+ }++ return valueNode.value;+ }+});++function serializeID(outputValue) {+ var coercedValue = serializeObject(outputValue);++ if (typeof coercedValue === 'string') {+ return coercedValue;+ }++ if (isInteger(coercedValue)) {+ return String(coercedValue);+ }++ throw new GraphQLError("ID cannot represent value: ".concat(inspect(outputValue)));+}++function coerceID(inputValue) {+ if (typeof inputValue === 'string') {+ return inputValue;+ }++ if (isInteger(inputValue)) {+ return inputValue.toString();+ }++ throw new GraphQLError("ID cannot represent value: ".concat(inspect(inputValue)));+}++var GraphQLID = new GraphQLScalarType({+ name: 'ID',+ description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.',+ serialize: serializeID,+ parseValue: coerceID,+ parseLiteral: function parseLiteral(valueNode) {+ if (valueNode.kind !== Kind.STRING && valueNode.kind !== Kind.INT) {+ throw new GraphQLError('ID cannot represent a non-string and non-integer value: ' + print(valueNode), valueNode);+ }++ return valueNode.value;+ }+});+var specifiedScalarTypes = Object.freeze([GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]);+function isSpecifiedScalarType(type) {+ return specifiedScalarTypes.some(function (_ref) {+ var name = _ref.name;+ return type.name === name;+ });+}++/**+ * Produces a GraphQL Value AST given a JavaScript object.+ * Function will match JavaScript/JSON values to GraphQL AST schema format+ * by using suggested GraphQLInputType. For example:+ *+ * astFromValue("value", GraphQLString)+ *+ * A GraphQL type must be provided, which will be used to interpret different+ * JavaScript values.+ *+ * | JSON Value | GraphQL Value |+ * | ------------- | -------------------- |+ * | Object | Input Object |+ * | Array | List |+ * | Boolean | Boolean |+ * | String | String / Enum Value |+ * | Number | Int / Float |+ * | Mixed | Enum Value |+ * | null | NullValue |+ *+ */++function astFromValue(value, type) {+ if (isNonNullType(type)) {+ var astValue = astFromValue(value, type.ofType);++ if ((astValue === null || astValue === void 0 ? void 0 : astValue.kind) === Kind.NULL) {+ return null;+ }++ return astValue;+ } // only explicit null, not undefined, NaN+++ if (value === null) {+ return {+ kind: Kind.NULL+ };+ } // undefined+++ if (value === undefined) {+ return null;+ } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but+ // the value is not an array, convert the value using the list's item type.+++ if (isListType(type)) {+ var itemType = type.ofType;++ if (isCollection(value)) {+ var valuesNodes = []; // Since we transpile for-of in loose mode it doesn't support iterators+ // and it's required to first convert iteratable into array++ for (var _i2 = 0, _arrayFrom2 = arrayFrom(value); _i2 < _arrayFrom2.length; _i2++) {+ var item = _arrayFrom2[_i2];+ var itemNode = astFromValue(item, itemType);++ if (itemNode != null) {+ valuesNodes.push(itemNode);+ }+ }++ return {+ kind: Kind.LIST,+ values: valuesNodes+ };+ }++ return astFromValue(value, itemType);+ } // Populate the fields of the input object by creating ASTs from each value+ // in the JavaScript object according to the fields in the input type.+++ if (isInputObjectType(type)) {+ if (!isObjectLike(value)) {+ return null;+ }++ var fieldNodes = [];++ for (var _i4 = 0, _objectValues2 = objectValues(type.getFields()); _i4 < _objectValues2.length; _i4++) {+ var field = _objectValues2[_i4];+ var fieldValue = astFromValue(value[field.name], field.type);++ if (fieldValue) {+ fieldNodes.push({+ kind: Kind.OBJECT_FIELD,+ name: {+ kind: Kind.NAME,+ value: field.name+ },+ value: fieldValue+ });+ }+ }++ return {+ kind: Kind.OBJECT,+ fields: fieldNodes+ };+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isLeafType(type)) {+ // Since value is an internally represented value, it must be serialized+ // to an externally represented value before converting into an AST.+ var serialized = type.serialize(value);++ if (serialized == null) {+ return null;+ } // Others serialize based on their corresponding JavaScript scalar types.+++ if (typeof serialized === 'boolean') {+ return {+ kind: Kind.BOOLEAN,+ value: serialized+ };+ } // JavaScript numbers can be Int or Float values.+++ if (typeof serialized === 'number' && isFinitePolyfill(serialized)) {+ var stringNum = String(serialized);+ return integerStringRegExp.test(stringNum) ? {+ kind: Kind.INT,+ value: stringNum+ } : {+ kind: Kind.FLOAT,+ value: stringNum+ };+ }++ if (typeof serialized === 'string') {+ // Enum types use Enum literals.+ if (isEnumType(type)) {+ return {+ kind: Kind.ENUM,+ value: serialized+ };+ } // ID types can use Int literals.+++ if (type === GraphQLID && integerStringRegExp.test(serialized)) {+ return {+ kind: Kind.INT,+ value: serialized+ };+ }++ return {+ kind: Kind.STRING,+ value: serialized+ };+ }++ throw new TypeError("Cannot convert value to AST: ".concat(inspect(serialized), "."));+ } // istanbul ignore next (Not reachable. All possible input types have been considered)+++ invariant(0, 'Unexpected input type: ' + inspect(type));+}+/**+ * IntValue:+ * - NegativeSign? 0+ * - NegativeSign? NonZeroDigit ( Digit+ )?+ */++var integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;++var __Schema = new GraphQLObjectType({+ name: '__Schema',+ description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.',+ fields: function fields() {+ return {+ description: {+ type: GraphQLString,+ resolve: function resolve(schema) {+ return schema.description;+ }+ },+ types: {+ description: 'A list of all types supported by this server.',+ type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))),+ resolve: function resolve(schema) {+ return objectValues(schema.getTypeMap());+ }+ },+ queryType: {+ description: 'The type that query operations will be rooted at.',+ type: GraphQLNonNull(__Type),+ resolve: function resolve(schema) {+ return schema.getQueryType();+ }+ },+ mutationType: {+ description: 'If this server supports mutation, the type that mutation operations will be rooted at.',+ type: __Type,+ resolve: function resolve(schema) {+ return schema.getMutationType();+ }+ },+ subscriptionType: {+ description: 'If this server support subscription, the type that subscription operations will be rooted at.',+ type: __Type,+ resolve: function resolve(schema) {+ return schema.getSubscriptionType();+ }+ },+ directives: {+ description: 'A list of all directives supported by this server.',+ type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))),+ resolve: function resolve(schema) {+ return schema.getDirectives();+ }+ }+ };+ }+});+var __Directive = new GraphQLObjectType({+ name: '__Directive',+ description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.",+ fields: function fields() {+ return {+ name: {+ type: GraphQLNonNull(GraphQLString),+ resolve: function resolve(directive) {+ return directive.name;+ }+ },+ description: {+ type: GraphQLString,+ resolve: function resolve(directive) {+ return directive.description;+ }+ },+ isRepeatable: {+ type: GraphQLNonNull(GraphQLBoolean),+ resolve: function resolve(directive) {+ return directive.isRepeatable;+ }+ },+ locations: {+ type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))),+ resolve: function resolve(directive) {+ return directive.locations;+ }+ },+ args: {+ type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),+ resolve: function resolve(directive) {+ return directive.args;+ }+ }+ };+ }+});+var __DirectiveLocation = new GraphQLEnumType({+ name: '__DirectiveLocation',+ description: 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.',+ values: {+ QUERY: {+ value: DirectiveLocation.QUERY,+ description: 'Location adjacent to a query operation.'+ },+ MUTATION: {+ value: DirectiveLocation.MUTATION,+ description: 'Location adjacent to a mutation operation.'+ },+ SUBSCRIPTION: {+ value: DirectiveLocation.SUBSCRIPTION,+ description: 'Location adjacent to a subscription operation.'+ },+ FIELD: {+ value: DirectiveLocation.FIELD,+ description: 'Location adjacent to a field.'+ },+ FRAGMENT_DEFINITION: {+ value: DirectiveLocation.FRAGMENT_DEFINITION,+ description: 'Location adjacent to a fragment definition.'+ },+ FRAGMENT_SPREAD: {+ value: DirectiveLocation.FRAGMENT_SPREAD,+ description: 'Location adjacent to a fragment spread.'+ },+ INLINE_FRAGMENT: {+ value: DirectiveLocation.INLINE_FRAGMENT,+ description: 'Location adjacent to an inline fragment.'+ },+ VARIABLE_DEFINITION: {+ value: DirectiveLocation.VARIABLE_DEFINITION,+ description: 'Location adjacent to a variable definition.'+ },+ SCHEMA: {+ value: DirectiveLocation.SCHEMA,+ description: 'Location adjacent to a schema definition.'+ },+ SCALAR: {+ value: DirectiveLocation.SCALAR,+ description: 'Location adjacent to a scalar definition.'+ },+ OBJECT: {+ value: DirectiveLocation.OBJECT,+ description: 'Location adjacent to an object type definition.'+ },+ FIELD_DEFINITION: {+ value: DirectiveLocation.FIELD_DEFINITION,+ description: 'Location adjacent to a field definition.'+ },+ ARGUMENT_DEFINITION: {+ value: DirectiveLocation.ARGUMENT_DEFINITION,+ description: 'Location adjacent to an argument definition.'+ },+ INTERFACE: {+ value: DirectiveLocation.INTERFACE,+ description: 'Location adjacent to an interface definition.'+ },+ UNION: {+ value: DirectiveLocation.UNION,+ description: 'Location adjacent to a union definition.'+ },+ ENUM: {+ value: DirectiveLocation.ENUM,+ description: 'Location adjacent to an enum definition.'+ },+ ENUM_VALUE: {+ value: DirectiveLocation.ENUM_VALUE,+ description: 'Location adjacent to an enum value definition.'+ },+ INPUT_OBJECT: {+ value: DirectiveLocation.INPUT_OBJECT,+ description: 'Location adjacent to an input object type definition.'+ },+ INPUT_FIELD_DEFINITION: {+ value: DirectiveLocation.INPUT_FIELD_DEFINITION,+ description: 'Location adjacent to an input object field definition.'+ }+ }+});+var __Type = new GraphQLObjectType({+ name: '__Type',+ description: 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByUrl`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.',+ fields: function fields() {+ return {+ kind: {+ type: GraphQLNonNull(__TypeKind),+ resolve: function resolve(type) {+ if (isScalarType(type)) {+ return TypeKind.SCALAR;+ }++ if (isObjectType(type)) {+ return TypeKind.OBJECT;+ }++ if (isInterfaceType(type)) {+ return TypeKind.INTERFACE;+ }++ if (isUnionType(type)) {+ return TypeKind.UNION;+ }++ if (isEnumType(type)) {+ return TypeKind.ENUM;+ }++ if (isInputObjectType(type)) {+ return TypeKind.INPUT_OBJECT;+ }++ if (isListType(type)) {+ return TypeKind.LIST;+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isNonNullType(type)) {+ return TypeKind.NON_NULL;+ } // istanbul ignore next (Not reachable. All possible types have been considered)+++ invariant(0, "Unexpected type: \"".concat(inspect(type), "\"."));+ }+ },+ name: {+ type: GraphQLString,+ resolve: function resolve(type) {+ return type.name !== undefined ? type.name : undefined;+ }+ },+ description: {+ type: GraphQLString,+ resolve: function resolve(type) {+ return type.description !== undefined ? type.description : undefined;+ }+ },+ specifiedByUrl: {+ type: GraphQLString,+ resolve: function resolve(obj) {+ return obj.specifiedByUrl !== undefined ? obj.specifiedByUrl : undefined;+ }+ },+ fields: {+ type: GraphQLList(GraphQLNonNull(__Field)),+ args: {+ includeDeprecated: {+ type: GraphQLBoolean,+ defaultValue: false+ }+ },+ resolve: function resolve(type, _ref) {+ var includeDeprecated = _ref.includeDeprecated;++ if (isObjectType(type) || isInterfaceType(type)) {+ var fields = objectValues(type.getFields());++ if (!includeDeprecated) {+ fields = fields.filter(function (field) {+ return !field.isDeprecated;+ });+ }++ return fields;+ }++ return null;+ }+ },+ interfaces: {+ type: GraphQLList(GraphQLNonNull(__Type)),+ resolve: function resolve(type) {+ if (isObjectType(type) || isInterfaceType(type)) {+ return type.getInterfaces();+ }+ }+ },+ possibleTypes: {+ type: GraphQLList(GraphQLNonNull(__Type)),+ resolve: function resolve(type, _args, _context, _ref2) {+ var schema = _ref2.schema;++ if (isAbstractType(type)) {+ return schema.getPossibleTypes(type);+ }+ }+ },+ enumValues: {+ type: GraphQLList(GraphQLNonNull(__EnumValue)),+ args: {+ includeDeprecated: {+ type: GraphQLBoolean,+ defaultValue: false+ }+ },+ resolve: function resolve(type, _ref3) {+ var includeDeprecated = _ref3.includeDeprecated;++ if (isEnumType(type)) {+ var values = type.getValues();++ if (!includeDeprecated) {+ values = values.filter(function (value) {+ return !value.isDeprecated;+ });+ }++ return values;+ }+ }+ },+ inputFields: {+ type: GraphQLList(GraphQLNonNull(__InputValue)),+ resolve: function resolve(type) {+ if (isInputObjectType(type)) {+ return objectValues(type.getFields());+ }+ }+ },+ ofType: {+ type: __Type,+ resolve: function resolve(type) {+ return type.ofType !== undefined ? type.ofType : undefined;+ }+ }+ };+ }+});+var __Field = new GraphQLObjectType({+ name: '__Field',+ description: 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.',+ fields: function fields() {+ return {+ name: {+ type: GraphQLNonNull(GraphQLString),+ resolve: function resolve(field) {+ return field.name;+ }+ },+ description: {+ type: GraphQLString,+ resolve: function resolve(field) {+ return field.description;+ }+ },+ args: {+ type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),+ resolve: function resolve(field) {+ return field.args;+ }+ },+ type: {+ type: GraphQLNonNull(__Type),+ resolve: function resolve(field) {+ return field.type;+ }+ },+ isDeprecated: {+ type: GraphQLNonNull(GraphQLBoolean),+ resolve: function resolve(field) {+ return field.isDeprecated;+ }+ },+ deprecationReason: {+ type: GraphQLString,+ resolve: function resolve(field) {+ return field.deprecationReason;+ }+ }+ };+ }+});+var __InputValue = new GraphQLObjectType({+ name: '__InputValue',+ description: 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.',+ fields: function fields() {+ return {+ name: {+ type: GraphQLNonNull(GraphQLString),+ resolve: function resolve(inputValue) {+ return inputValue.name;+ }+ },+ description: {+ type: GraphQLString,+ resolve: function resolve(inputValue) {+ return inputValue.description;+ }+ },+ type: {+ type: GraphQLNonNull(__Type),+ resolve: function resolve(inputValue) {+ return inputValue.type;+ }+ },+ defaultValue: {+ type: GraphQLString,+ description: 'A GraphQL-formatted string representing the default value for this input value.',+ resolve: function resolve(inputValue) {+ var type = inputValue.type,+ defaultValue = inputValue.defaultValue;+ var valueAST = astFromValue(defaultValue, type);+ return valueAST ? print(valueAST) : null;+ }+ }+ };+ }+});+var __EnumValue = new GraphQLObjectType({+ name: '__EnumValue',+ description: 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.',+ fields: function fields() {+ return {+ name: {+ type: GraphQLNonNull(GraphQLString),+ resolve: function resolve(enumValue) {+ return enumValue.name;+ }+ },+ description: {+ type: GraphQLString,+ resolve: function resolve(enumValue) {+ return enumValue.description;+ }+ },+ isDeprecated: {+ type: GraphQLNonNull(GraphQLBoolean),+ resolve: function resolve(enumValue) {+ return enumValue.isDeprecated;+ }+ },+ deprecationReason: {+ type: GraphQLString,+ resolve: function resolve(enumValue) {+ return enumValue.deprecationReason;+ }+ }+ };+ }+});+var TypeKind = Object.freeze({+ SCALAR: 'SCALAR',+ OBJECT: 'OBJECT',+ INTERFACE: 'INTERFACE',+ UNION: 'UNION',+ ENUM: 'ENUM',+ INPUT_OBJECT: 'INPUT_OBJECT',+ LIST: 'LIST',+ NON_NULL: 'NON_NULL'+});+var __TypeKind = new GraphQLEnumType({+ name: '__TypeKind',+ description: 'An enum describing what kind of type a given `__Type` is.',+ values: {+ SCALAR: {+ value: TypeKind.SCALAR,+ description: 'Indicates this type is a scalar.'+ },+ OBJECT: {+ value: TypeKind.OBJECT,+ description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.'+ },+ INTERFACE: {+ value: TypeKind.INTERFACE,+ description: 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.'+ },+ UNION: {+ value: TypeKind.UNION,+ description: 'Indicates this type is a union. `possibleTypes` is a valid field.'+ },+ ENUM: {+ value: TypeKind.ENUM,+ description: 'Indicates this type is an enum. `enumValues` is a valid field.'+ },+ INPUT_OBJECT: {+ value: TypeKind.INPUT_OBJECT,+ description: 'Indicates this type is an input object. `inputFields` is a valid field.'+ },+ LIST: {+ value: TypeKind.LIST,+ description: 'Indicates this type is a list. `ofType` is a valid field.'+ },+ NON_NULL: {+ value: TypeKind.NON_NULL,+ description: 'Indicates this type is a non-null. `ofType` is a valid field.'+ }+ }+});+/**+ * Note that these are GraphQLField and not GraphQLFieldConfig,+ * so the format for args is different.+ */++var SchemaMetaFieldDef = {+ name: '__schema',+ type: GraphQLNonNull(__Schema),+ description: 'Access the current type schema of this server.',+ args: [],+ resolve: function resolve(_source, _args, _context, _ref4) {+ var schema = _ref4.schema;+ return schema;+ },+ isDeprecated: false,+ deprecationReason: undefined,+ extensions: undefined,+ astNode: undefined+};+var TypeMetaFieldDef = {+ name: '__type',+ type: __Type,+ description: 'Request the type information of a single type.',+ args: [{+ name: 'name',+ description: undefined,+ type: GraphQLNonNull(GraphQLString),+ defaultValue: undefined,+ extensions: undefined,+ astNode: undefined+ }],+ resolve: function resolve(_source, _ref5, _context, _ref6) {+ var name = _ref5.name;+ var schema = _ref6.schema;+ return schema.getType(name);+ },+ isDeprecated: false,+ deprecationReason: undefined,+ extensions: undefined,+ astNode: undefined+};+var TypeNameMetaFieldDef = {+ name: '__typename',+ type: GraphQLNonNull(GraphQLString),+ description: 'The name of the current Object type at runtime.',+ args: [],+ resolve: function resolve(_source, _args, _context, _ref7) {+ var parentType = _ref7.parentType;+ return parentType.name;+ },+ isDeprecated: false,+ deprecationReason: undefined,+ extensions: undefined,+ astNode: undefined+};+var introspectionTypes = Object.freeze([__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]);+function isIntrospectionType(type) {+ return introspectionTypes.some(function (_ref8) {+ var name = _ref8.name;+ return type.name === name;+ });+}++function _defineProperties$3(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); } }++function _createClass$3(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$3(Constructor.prototype, protoProps); if (staticProps) _defineProperties$3(Constructor, staticProps); return Constructor; }+/**+ * Test if the given value is a GraphQL directive.+ */++// eslint-disable-next-line no-redeclare+function isDirective(directive) {+ return instanceOf(directive, GraphQLDirective);+}+function assertDirective(directive) {+ if (!isDirective(directive)) {+ throw new Error("Expected ".concat(inspect(directive), " to be a GraphQL directive."));+ }++ return directive;+}+/**+ * Directives are used by the GraphQL runtime as a way of modifying execution+ * behavior. Type system creators will usually not create these directly.+ */++var GraphQLDirective = /*#__PURE__*/function () {+ function GraphQLDirective(config) {+ var _config$isRepeatable, _config$args;++ this.name = config.name;+ this.description = config.description;+ this.locations = config.locations;+ this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false;+ this.extensions = config.extensions && toObjMap(config.extensions);+ this.astNode = config.astNode;+ config.name || devAssert(0, 'Directive must be named.');+ Array.isArray(config.locations) || devAssert(0, "@".concat(config.name, " locations must be an Array."));+ var args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {};+ isObjectLike(args) && !Array.isArray(args) || devAssert(0, "@".concat(config.name, " args must be an object with argument names as keys."));+ this.args = objectEntries(args).map(function (_ref) {+ var argName = _ref[0],+ argConfig = _ref[1];+ return {+ name: argName,+ description: argConfig.description,+ type: argConfig.type,+ defaultValue: argConfig.defaultValue,+ extensions: argConfig.extensions && toObjMap(argConfig.extensions),+ astNode: argConfig.astNode+ };+ });+ }++ var _proto = GraphQLDirective.prototype;++ _proto.toConfig = function toConfig() {+ return {+ name: this.name,+ description: this.description,+ locations: this.locations,+ args: argsToArgsConfig(this.args),+ isRepeatable: this.isRepeatable,+ extensions: this.extensions,+ astNode: this.astNode+ };+ };++ _proto.toString = function toString() {+ return '@' + this.name;+ };++ _proto.toJSON = function toJSON() {+ return this.toString();+ } // $FlowFixMe Flow doesn't support computed properties yet+ ;++ _createClass$3(GraphQLDirective, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'GraphQLDirective';+ }+ }]);++ return GraphQLDirective;+}(); // Print a simplified form when appearing in `inspect` and `util.inspect`.++defineInspect(GraphQLDirective);++/**+ * Used to conditionally include fields or fragments.+ */+var GraphQLIncludeDirective = new GraphQLDirective({+ name: 'include',+ description: 'Directs the executor to include this field or fragment only when the `if` argument is true.',+ locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT],+ args: {+ if: {+ type: GraphQLNonNull(GraphQLBoolean),+ description: 'Included when true.'+ }+ }+});+/**+ * Used to conditionally skip (exclude) fields or fragments.+ */++var GraphQLSkipDirective = new GraphQLDirective({+ name: 'skip',+ description: 'Directs the executor to skip this field or fragment when the `if` argument is true.',+ locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT],+ args: {+ if: {+ type: GraphQLNonNull(GraphQLBoolean),+ description: 'Skipped when true.'+ }+ }+});+/**+ * Constant string used for default reason for a deprecation.+ */++var DEFAULT_DEPRECATION_REASON = 'No longer supported';+/**+ * Used to declare element of a GraphQL schema as deprecated.+ */++var GraphQLDeprecatedDirective = new GraphQLDirective({+ name: 'deprecated',+ description: 'Marks an element of a GraphQL schema as no longer supported.',+ locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.ENUM_VALUE],+ args: {+ reason: {+ type: GraphQLString,+ description: 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).',+ defaultValue: DEFAULT_DEPRECATION_REASON+ }+ }+});+/**+ * Used to provide a URL for specifying the behaviour of custom scalar definitions.+ */++var GraphQLSpecifiedByDirective = new GraphQLDirective({+ name: 'specifiedBy',+ description: 'Exposes a URL that specifies the behaviour of this scalar.',+ locations: [DirectiveLocation.SCALAR],+ args: {+ url: {+ type: GraphQLNonNull(GraphQLString),+ description: 'The URL that specifies the behaviour of this scalar.'+ }+ }+});+/**+ * The full list of specified directives.+ */++var specifiedDirectives = Object.freeze([GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, GraphQLSpecifiedByDirective]);+function isSpecifiedDirective(directive) {+ return specifiedDirectives.some(function (_ref2) {+ var name = _ref2.name;+ return name === directive.name;+ });+}++function _defineProperties$4(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); } }++function _createClass$4(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$4(Constructor.prototype, protoProps); if (staticProps) _defineProperties$4(Constructor, staticProps); return Constructor; }+/**+ * Test if the given value is a GraphQL schema.+ */++// eslint-disable-next-line no-redeclare+function isSchema(schema) {+ return instanceOf(schema, GraphQLSchema);+}+function assertSchema(schema) {+ if (!isSchema(schema)) {+ throw new Error("Expected ".concat(inspect(schema), " to be a GraphQL schema."));+ }++ return schema;+}+/**+ * Schema Definition+ *+ * A Schema is created by supplying the root types of each type of operation,+ * query and mutation (optional). A schema definition is then supplied to the+ * validator and executor.+ *+ * Example:+ *+ * const MyAppSchema = new GraphQLSchema({+ * query: MyAppQueryRootType,+ * mutation: MyAppMutationRootType,+ * })+ *+ * Note: When the schema is constructed, by default only the types that are+ * reachable by traversing the root types are included, other types must be+ * explicitly referenced.+ *+ * Example:+ *+ * const characterInterface = new GraphQLInterfaceType({+ * name: 'Character',+ * ...+ * });+ *+ * const humanType = new GraphQLObjectType({+ * name: 'Human',+ * interfaces: [characterInterface],+ * ...+ * });+ *+ * const droidType = new GraphQLObjectType({+ * name: 'Droid',+ * interfaces: [characterInterface],+ * ...+ * });+ *+ * const schema = new GraphQLSchema({+ * query: new GraphQLObjectType({+ * name: 'Query',+ * fields: {+ * hero: { type: characterInterface, ... },+ * }+ * }),+ * ...+ * // Since this schema references only the `Character` interface it's+ * // necessary to explicitly list the types that implement it if+ * // you want them to be included in the final schema.+ * types: [humanType, droidType],+ * })+ *+ * Note: If an array of `directives` are provided to GraphQLSchema, that will be+ * the exact list of directives represented and allowed. If `directives` is not+ * provided then a default set of the specified directives (e.g. @include and+ * @skip) will be used. If you wish to provide *additional* directives to these+ * specified directives, you must explicitly declare them. Example:+ *+ * const MyAppSchema = new GraphQLSchema({+ * ...+ * directives: specifiedDirectives.concat([ myCustomDirective ]),+ * })+ *+ */++var GraphQLSchema = /*#__PURE__*/function () {+ // Used as a cache for validateSchema().+ function GraphQLSchema(config) {+ var _config$directives;++ // If this schema was built from a source known to be valid, then it may be+ // marked with assumeValid to avoid an additional type system validation.+ this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors.++ isObjectLike(config) || devAssert(0, 'Must provide configuration object.');+ !config.types || Array.isArray(config.types) || devAssert(0, "\"types\" must be Array if provided but got: ".concat(inspect(config.types), "."));+ !config.directives || Array.isArray(config.directives) || devAssert(0, '"directives" must be Array if provided but got: ' + "".concat(inspect(config.directives), "."));+ this.description = config.description;+ this.extensions = config.extensions && toObjMap(config.extensions);+ this.astNode = config.astNode;+ this.extensionASTNodes = config.extensionASTNodes;+ this._queryType = config.query;+ this._mutationType = config.mutation;+ this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default.++ this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : specifiedDirectives; // To preserve order of user-provided types, we add first to add them to+ // the set of "collected" types, so `collectReferencedTypes` ignore them.++ var allReferencedTypes = new Set(config.types);++ if (config.types != null) {+ for (var _i2 = 0, _config$types2 = config.types; _i2 < _config$types2.length; _i2++) {+ var type = _config$types2[_i2];+ // When we ready to process this type, we remove it from "collected" types+ // and then add it together with all dependent types in the correct position.+ allReferencedTypes.delete(type);+ collectReferencedTypes(type, allReferencedTypes);+ }+ }++ if (this._queryType != null) {+ collectReferencedTypes(this._queryType, allReferencedTypes);+ }++ if (this._mutationType != null) {+ collectReferencedTypes(this._mutationType, allReferencedTypes);+ }++ if (this._subscriptionType != null) {+ collectReferencedTypes(this._subscriptionType, allReferencedTypes);+ }++ for (var _i4 = 0, _this$_directives2 = this._directives; _i4 < _this$_directives2.length; _i4++) {+ var directive = _this$_directives2[_i4];++ // Directives are not validated until validateSchema() is called.+ if (isDirective(directive)) {+ for (var _i6 = 0, _directive$args2 = directive.args; _i6 < _directive$args2.length; _i6++) {+ var arg = _directive$args2[_i6];+ collectReferencedTypes(arg.type, allReferencedTypes);+ }+ }+ }++ collectReferencedTypes(__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema.++ this._typeMap = Object.create(null);+ this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name.++ this._implementationsMap = Object.create(null);++ for (var _i8 = 0, _arrayFrom2 = arrayFrom(allReferencedTypes); _i8 < _arrayFrom2.length; _i8++) {+ var namedType = _arrayFrom2[_i8];++ if (namedType == null) {+ continue;+ }++ var typeName = namedType.name;+ typeName || devAssert(0, 'One of the provided types for building the Schema is missing a name.');++ if (this._typeMap[typeName] !== undefined) {+ throw new Error("Schema must contain uniquely named types but contains multiple types named \"".concat(typeName, "\"."));+ }++ this._typeMap[typeName] = namedType;++ if (isInterfaceType(namedType)) {+ // Store implementations by interface.+ for (var _i10 = 0, _namedType$getInterfa2 = namedType.getInterfaces(); _i10 < _namedType$getInterfa2.length; _i10++) {+ var iface = _namedType$getInterfa2[_i10];++ if (isInterfaceType(iface)) {+ var implementations = this._implementationsMap[iface.name];++ if (implementations === undefined) {+ implementations = this._implementationsMap[iface.name] = {+ objects: [],+ interfaces: []+ };+ }++ implementations.interfaces.push(namedType);+ }+ }+ } else if (isObjectType(namedType)) {+ // Store implementations by objects.+ for (var _i12 = 0, _namedType$getInterfa4 = namedType.getInterfaces(); _i12 < _namedType$getInterfa4.length; _i12++) {+ var _iface = _namedType$getInterfa4[_i12];++ if (isInterfaceType(_iface)) {+ var _implementations = this._implementationsMap[_iface.name];++ if (_implementations === undefined) {+ _implementations = this._implementationsMap[_iface.name] = {+ objects: [],+ interfaces: []+ };+ }++ _implementations.objects.push(namedType);+ }+ }+ }+ }+ }++ var _proto = GraphQLSchema.prototype;++ _proto.getQueryType = function getQueryType() {+ return this._queryType;+ };++ _proto.getMutationType = function getMutationType() {+ return this._mutationType;+ };++ _proto.getSubscriptionType = function getSubscriptionType() {+ return this._subscriptionType;+ };++ _proto.getTypeMap = function getTypeMap() {+ return this._typeMap;+ };++ _proto.getType = function getType(name) {+ return this.getTypeMap()[name];+ };++ _proto.getPossibleTypes = function getPossibleTypes(abstractType) {+ return isUnionType(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects;+ };++ _proto.getImplementations = function getImplementations(interfaceType) {+ var implementations = this._implementationsMap[interfaceType.name];+ return implementations !== null && implementations !== void 0 ? implementations : {+ objects: [],+ interfaces: []+ };+ } // @deprecated: use isSubType instead - will be removed in v16.+ ;++ _proto.isPossibleType = function isPossibleType(abstractType, possibleType) {+ return this.isSubType(abstractType, possibleType);+ };++ _proto.isSubType = function isSubType(abstractType, maybeSubType) {+ var map = this._subTypeMap[abstractType.name];++ if (map === undefined) {+ map = Object.create(null);++ if (isUnionType(abstractType)) {+ for (var _i14 = 0, _abstractType$getType2 = abstractType.getTypes(); _i14 < _abstractType$getType2.length; _i14++) {+ var type = _abstractType$getType2[_i14];+ map[type.name] = true;+ }+ } else {+ var implementations = this.getImplementations(abstractType);++ for (var _i16 = 0, _implementations$obje2 = implementations.objects; _i16 < _implementations$obje2.length; _i16++) {+ var _type = _implementations$obje2[_i16];+ map[_type.name] = true;+ }++ for (var _i18 = 0, _implementations$inte2 = implementations.interfaces; _i18 < _implementations$inte2.length; _i18++) {+ var _type2 = _implementations$inte2[_i18];+ map[_type2.name] = true;+ }+ }++ this._subTypeMap[abstractType.name] = map;+ }++ return map[maybeSubType.name] !== undefined;+ };++ _proto.getDirectives = function getDirectives() {+ return this._directives;+ };++ _proto.getDirective = function getDirective(name) {+ return find(this.getDirectives(), function (directive) {+ return directive.name === name;+ });+ };++ _proto.toConfig = function toConfig() {+ var _this$extensionASTNod;++ return {+ description: this.description,+ query: this.getQueryType(),+ mutation: this.getMutationType(),+ subscription: this.getSubscriptionType(),+ types: objectValues(this.getTypeMap()),+ directives: this.getDirectives().slice(),+ extensions: this.extensions,+ astNode: this.astNode,+ extensionASTNodes: (_this$extensionASTNod = this.extensionASTNodes) !== null && _this$extensionASTNod !== void 0 ? _this$extensionASTNod : [],+ assumeValid: this.__validationErrors !== undefined+ };+ } // $FlowFixMe Flow doesn't support computed properties yet+ ;++ _createClass$4(GraphQLSchema, [{+ key: SYMBOL_TO_STRING_TAG,+ get: function get() {+ return 'GraphQLSchema';+ }+ }]);++ return GraphQLSchema;+}();++function collectReferencedTypes(type, typeSet) {+ var namedType = getNamedType(type);++ if (!typeSet.has(namedType)) {+ typeSet.add(namedType);++ if (isUnionType(namedType)) {+ for (var _i20 = 0, _namedType$getTypes2 = namedType.getTypes(); _i20 < _namedType$getTypes2.length; _i20++) {+ var memberType = _namedType$getTypes2[_i20];+ collectReferencedTypes(memberType, typeSet);+ }+ } else if (isObjectType(namedType) || isInterfaceType(namedType)) {+ for (var _i22 = 0, _namedType$getInterfa6 = namedType.getInterfaces(); _i22 < _namedType$getInterfa6.length; _i22++) {+ var interfaceType = _namedType$getInterfa6[_i22];+ collectReferencedTypes(interfaceType, typeSet);+ }++ for (var _i24 = 0, _objectValues2 = objectValues(namedType.getFields()); _i24 < _objectValues2.length; _i24++) {+ var field = _objectValues2[_i24];+ collectReferencedTypes(field.type, typeSet);++ for (var _i26 = 0, _field$args2 = field.args; _i26 < _field$args2.length; _i26++) {+ var arg = _field$args2[_i26];+ collectReferencedTypes(arg.type, typeSet);+ }+ }+ } else if (isInputObjectType(namedType)) {+ for (var _i28 = 0, _objectValues4 = objectValues(namedType.getFields()); _i28 < _objectValues4.length; _i28++) {+ var _field = _objectValues4[_i28];+ collectReferencedTypes(_field.type, typeSet);+ }+ }+ }++ return typeSet;+}++/**+ * Implements the "Type Validation" sub-sections of the specification's+ * "Type System" section.+ *+ * Validation runs synchronously, returning an array of encountered errors, or+ * an empty array if no errors were encountered and the Schema is valid.+ */++function validateSchema(schema) {+ // First check to ensure the provided value is in fact a GraphQLSchema.+ assertSchema(schema); // If this Schema has already been validated, return the previous results.++ if (schema.__validationErrors) {+ return schema.__validationErrors;+ } // Validate the schema, producing a list of errors.+++ var context = new SchemaValidationContext(schema);+ validateRootTypes(context);+ validateDirectives(context);+ validateTypes(context); // Persist the results of validation before returning to ensure validation+ // does not run multiple times for this schema.++ var errors = context.getErrors();+ schema.__validationErrors = errors;+ return errors;+}+/**+ * Utility function which asserts a schema is valid by throwing an error if+ * it is invalid.+ */++function assertValidSchema(schema) {+ var errors = validateSchema(schema);++ if (errors.length !== 0) {+ throw new Error(errors.map(function (error) {+ return error.message;+ }).join('\n\n'));+ }+}++var SchemaValidationContext = /*#__PURE__*/function () {+ function SchemaValidationContext(schema) {+ this._errors = [];+ this.schema = schema;+ }++ var _proto = SchemaValidationContext.prototype;++ _proto.reportError = function reportError(message, nodes) {+ var _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes;++ this.addError(new GraphQLError(message, _nodes));+ };++ _proto.addError = function addError(error) {+ this._errors.push(error);+ };++ _proto.getErrors = function getErrors() {+ return this._errors;+ };++ return SchemaValidationContext;+}();++function validateRootTypes(context) {+ var schema = context.schema;+ var queryType = schema.getQueryType();++ if (!queryType) {+ context.reportError('Query root type must be provided.', schema.astNode);+ } else if (!isObjectType(queryType)) {+ var _getOperationTypeNode;++ context.reportError("Query root type must be Object type, it cannot be ".concat(inspect(queryType), "."), (_getOperationTypeNode = getOperationTypeNode(schema, 'query')) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode);+ }++ var mutationType = schema.getMutationType();++ if (mutationType && !isObjectType(mutationType)) {+ var _getOperationTypeNode2;++ context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat(inspect(mutationType), "."), (_getOperationTypeNode2 = getOperationTypeNode(schema, 'mutation')) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode);+ }++ var subscriptionType = schema.getSubscriptionType();++ if (subscriptionType && !isObjectType(subscriptionType)) {+ var _getOperationTypeNode3;++ context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat(inspect(subscriptionType), "."), (_getOperationTypeNode3 = getOperationTypeNode(schema, 'subscription')) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode);+ }+}++function getOperationTypeNode(schema, operation) {+ var operationNodes = getAllSubNodes(schema, function (node) {+ return node.operationTypes;+ });++ for (var _i2 = 0; _i2 < operationNodes.length; _i2++) {+ var node = operationNodes[_i2];++ if (node.operation === operation) {+ return node.type;+ }+ }++ return undefined;+}++function validateDirectives(context) {+ for (var _i4 = 0, _context$schema$getDi2 = context.schema.getDirectives(); _i4 < _context$schema$getDi2.length; _i4++) {+ var directive = _context$schema$getDi2[_i4];++ // Ensure all directives are in fact GraphQL directives.+ if (!isDirective(directive)) {+ context.reportError("Expected directive but got: ".concat(inspect(directive), "."), directive === null || directive === void 0 ? void 0 : directive.astNode);+ continue;+ } // Ensure they are named correctly.+++ validateName(context, directive); // TODO: Ensure proper locations.+ // Ensure the arguments are valid.++ for (var _i6 = 0, _directive$args2 = directive.args; _i6 < _directive$args2.length; _i6++) {+ var arg = _directive$args2[_i6];+ // Ensure they are named correctly.+ validateName(context, arg); // Ensure the type is an input type.++ if (!isInputType(arg.type)) {+ context.reportError("The type of @".concat(directive.name, "(").concat(arg.name, ":) must be Input Type ") + "but got: ".concat(inspect(arg.type), "."), arg.astNode);+ }+ }+ }+}++function validateName(context, node) {+ // Ensure names are valid, however introspection types opt out.+ var error = isValidNameError(node.name);++ if (error) {+ context.addError(locatedError(error, node.astNode));+ }+}++function validateTypes(context) {+ var validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context);+ var typeMap = context.schema.getTypeMap();++ for (var _i8 = 0, _objectValues2 = objectValues(typeMap); _i8 < _objectValues2.length; _i8++) {+ var type = _objectValues2[_i8];++ // Ensure all provided types are in fact GraphQL type.+ if (!isNamedType(type)) {+ context.reportError("Expected GraphQL named type but got: ".concat(inspect(type), "."), type.astNode);+ continue;+ } // Ensure it is named correctly (excluding introspection types).+++ if (!isIntrospectionType(type)) {+ validateName(context, type);+ }++ if (isObjectType(type)) {+ // Ensure fields are valid+ validateFields(context, type); // Ensure objects implement the interfaces they claim to.++ validateInterfaces(context, type);+ } else if (isInterfaceType(type)) {+ // Ensure fields are valid.+ validateFields(context, type); // Ensure interfaces implement the interfaces they claim to.++ validateInterfaces(context, type);+ } else if (isUnionType(type)) {+ // Ensure Unions include valid member types.+ validateUnionMembers(context, type);+ } else if (isEnumType(type)) {+ // Ensure Enums have valid values.+ validateEnumValues(context, type);+ } else if (isInputObjectType(type)) {+ // Ensure Input Object fields are valid.+ validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references++ validateInputObjectCircularRefs(type);+ }+ }+}++function validateFields(context, type) {+ var fields = objectValues(type.getFields()); // Objects and Interfaces both must define one or more fields.++ if (fields.length === 0) {+ context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type));+ }++ for (var _i10 = 0; _i10 < fields.length; _i10++) {+ var field = fields[_i10];+ // Ensure they are named correctly.+ validateName(context, field); // Ensure the type is an output type++ if (!isOutputType(field.type)) {+ var _field$astNode;++ context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat(inspect(field.type), "."), (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type);+ } // Ensure the arguments are valid+++ for (var _i12 = 0, _field$args2 = field.args; _i12 < _field$args2.length; _i12++) {+ var arg = _field$args2[_i12];+ var argName = arg.name; // Ensure they are named correctly.++ validateName(context, arg); // Ensure the type is an input type++ if (!isInputType(arg.type)) {+ var _arg$astNode;++ context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat(inspect(arg.type), "."), (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type);+ }+ }+ }+}++function validateInterfaces(context, type) {+ var ifaceTypeNames = Object.create(null);++ for (var _i14 = 0, _type$getInterfaces2 = type.getInterfaces(); _i14 < _type$getInterfaces2.length; _i14++) {+ var iface = _type$getInterfaces2[_i14];++ if (!isInterfaceType(iface)) {+ context.reportError("Type ".concat(inspect(type), " must only implement Interface types, ") + "it cannot implement ".concat(inspect(iface), "."), getAllImplementsInterfaceNodes(type, iface));+ continue;+ }++ if (type === iface) {+ context.reportError("Type ".concat(type.name, " cannot implement itself because it would create a circular reference."), getAllImplementsInterfaceNodes(type, iface));+ continue;+ }++ if (ifaceTypeNames[iface.name]) {+ context.reportError("Type ".concat(type.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(type, iface));+ continue;+ }++ ifaceTypeNames[iface.name] = true;+ validateTypeImplementsAncestors(context, type, iface);+ validateTypeImplementsInterface(context, type, iface);+ }+}++function validateTypeImplementsInterface(context, type, iface) {+ var typeFieldMap = type.getFields(); // Assert each interface field is implemented.++ for (var _i16 = 0, _objectValues4 = objectValues(iface.getFields()); _i16 < _objectValues4.length; _i16++) {+ var ifaceField = _objectValues4[_i16];+ var fieldName = ifaceField.name;+ var typeField = typeFieldMap[fieldName]; // Assert interface field exists on type.++ if (!typeField) {+ context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ").concat(type.name, " does not provide it."), [ifaceField.astNode].concat(getAllNodes(type)));+ continue;+ } // Assert interface field type is satisfied by type field type, by being+ // a valid subtype. (covariant)+++ if (!isTypeSubTypeOf(context.schema, typeField.type, ifaceField.type)) {+ var _ifaceField$astNode, _typeField$astNode;++ context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat(inspect(ifaceField.type), " but ").concat(type.name, ".").concat(fieldName, " ") + "is type ".concat(inspect(typeField.type), "."), [// istanbul ignore next (TODO need to write coverage tests)+ (_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type, // istanbul ignore next (TODO need to write coverage tests)+ (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type]);+ } // Assert each interface field arg is implemented.+++ var _loop = function _loop(_i18, _ifaceField$args2) {+ var ifaceArg = _ifaceField$args2[_i18];+ var argName = ifaceArg.name;+ var typeArg = find(typeField.args, function (arg) {+ return arg.name === argName;+ }); // Assert interface field arg exists on object field.++ if (!typeArg) {+ context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) expected but ").concat(type.name, ".").concat(fieldName, " does not provide it."), [ifaceArg.astNode, typeField.astNode]);+ return "continue";+ } // Assert interface field arg type matches object field arg type.+ // (invariant)+ // TODO: change to contravariant?+++ if (!isEqualType(ifaceArg.type, typeArg.type)) {+ var _ifaceArg$astNode, _typeArg$astNode;++ context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat(inspect(ifaceArg.type), " but ") + "".concat(type.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat(inspect(typeArg.type), "."), [// istanbul ignore next (TODO need to write coverage tests)+ (_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type, // istanbul ignore next (TODO need to write coverage tests)+ (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type]);+ } // TODO: validate default values?++ };++ for (var _i18 = 0, _ifaceField$args2 = ifaceField.args; _i18 < _ifaceField$args2.length; _i18++) {+ var _ret = _loop(_i18, _ifaceField$args2);++ if (_ret === "continue") continue;+ } // Assert additional arguments must not be required.+++ var _loop2 = function _loop2(_i20, _typeField$args2) {+ var typeArg = _typeField$args2[_i20];+ var argName = typeArg.name;+ var ifaceArg = find(ifaceField.args, function (arg) {+ return arg.name === argName;+ });++ if (!ifaceArg && isRequiredArgument(typeArg)) {+ context.reportError("Object field ".concat(type.name, ".").concat(fieldName, " includes required argument ").concat(argName, " that is missing from the Interface field ").concat(iface.name, ".").concat(fieldName, "."), [typeArg.astNode, ifaceField.astNode]);+ }+ };++ for (var _i20 = 0, _typeField$args2 = typeField.args; _i20 < _typeField$args2.length; _i20++) {+ _loop2(_i20, _typeField$args2);+ }+ }+}++function validateTypeImplementsAncestors(context, type, iface) {+ var ifaceInterfaces = type.getInterfaces();++ for (var _i22 = 0, _iface$getInterfaces2 = iface.getInterfaces(); _i22 < _iface$getInterfaces2.length; _i22++) {+ var transitive = _iface$getInterfaces2[_i22];++ if (ifaceInterfaces.indexOf(transitive) === -1) {+ context.reportError(transitive === type ? "Type ".concat(type.name, " cannot implement ").concat(iface.name, " because it would create a circular reference.") : "Type ".concat(type.name, " must implement ").concat(transitive.name, " because it is implemented by ").concat(iface.name, "."), [].concat(getAllImplementsInterfaceNodes(iface, transitive), getAllImplementsInterfaceNodes(type, iface)));+ }+ }+}++function validateUnionMembers(context, union) {+ var memberTypes = union.getTypes();++ if (memberTypes.length === 0) {+ context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union));+ }++ var includedTypeNames = Object.create(null);++ for (var _i24 = 0; _i24 < memberTypes.length; _i24++) {+ var memberType = memberTypes[_i24];++ if (includedTypeNames[memberType.name]) {+ context.reportError("Union type ".concat(union.name, " can only include type ").concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name));+ continue;+ }++ includedTypeNames[memberType.name] = true;++ if (!isObjectType(memberType)) {+ context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat(inspect(memberType), "."), getUnionMemberTypeNodes(union, String(memberType)));+ }+ }+}++function validateEnumValues(context, enumType) {+ var enumValues = enumType.getValues();++ if (enumValues.length === 0) {+ context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType));+ }++ for (var _i26 = 0; _i26 < enumValues.length; _i26++) {+ var enumValue = enumValues[_i26];+ var valueName = enumValue.name; // Ensure valid name.++ validateName(context, enumValue);++ if (valueName === 'true' || valueName === 'false' || valueName === 'null') {+ context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode);+ }+ }+}++function validateInputFields(context, inputObj) {+ var fields = objectValues(inputObj.getFields());++ if (fields.length === 0) {+ context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj));+ } // Ensure the arguments are valid+++ for (var _i28 = 0; _i28 < fields.length; _i28++) {+ var field = fields[_i28];+ // Ensure they are named correctly.+ validateName(context, field); // Ensure the type is an input type++ if (!isInputType(field.type)) {+ var _field$astNode2;++ context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat(inspect(field.type), "."), (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type);+ }+ }+}++function createInputObjectCircularRefsValidator(context) {+ // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'.+ // Tracks already visited types to maintain O(N) and to ensure that cycles+ // are not redundantly reported.+ var visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors++ var fieldPath = []; // Position in the type path++ var fieldPathIndexByTypeName = Object.create(null);+ return detectCycleRecursive; // This does a straight-forward DFS to find cycles.+ // It does not terminate when a cycle was found but continues to explore+ // the graph to find all possible cycles.++ function detectCycleRecursive(inputObj) {+ if (visitedTypes[inputObj.name]) {+ return;+ }++ visitedTypes[inputObj.name] = true;+ fieldPathIndexByTypeName[inputObj.name] = fieldPath.length;+ var fields = objectValues(inputObj.getFields());++ for (var _i30 = 0; _i30 < fields.length; _i30++) {+ var field = fields[_i30];++ if (isNonNullType(field.type) && isInputObjectType(field.type.ofType)) {+ var fieldType = field.type.ofType;+ var cycleIndex = fieldPathIndexByTypeName[fieldType.name];+ fieldPath.push(field);++ if (cycleIndex === undefined) {+ detectCycleRecursive(fieldType);+ } else {+ var cyclePath = fieldPath.slice(cycleIndex);+ var pathStr = cyclePath.map(function (fieldObj) {+ return fieldObj.name;+ }).join('.');+ context.reportError("Cannot reference Input Object \"".concat(fieldType.name, "\" within itself through a series of non-null fields: \"").concat(pathStr, "\"."), cyclePath.map(function (fieldObj) {+ return fieldObj.astNode;+ }));+ }++ fieldPath.pop();+ }+ }++ fieldPathIndexByTypeName[inputObj.name] = undefined;+ }+}++function getAllNodes(object) {+ var astNode = object.astNode,+ extensionASTNodes = object.extensionASTNodes;+ return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes !== null && extensionASTNodes !== void 0 ? extensionASTNodes : [];+}++function getAllSubNodes(object, getter) {+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ return flatMap(getAllNodes(object), function (item) {+ var _getter;++ return (_getter = getter(item)) !== null && _getter !== void 0 ? _getter : [];+ });+}++function getAllImplementsInterfaceNodes(type, iface) {+ return getAllSubNodes(type, function (typeNode) {+ return typeNode.interfaces;+ }).filter(function (ifaceNode) {+ return ifaceNode.name.value === iface.name;+ });+}++function getUnionMemberTypeNodes(union, typeName) {+ return getAllSubNodes(union, function (unionNode) {+ return unionNode.types;+ }).filter(function (typeNode) {+ return typeNode.name.value === typeName;+ });+}++/**+ * Given a Schema and an AST node describing a type, return a GraphQLType+ * definition which applies to that type. For example, if provided the parsed+ * AST node for `[User]`, a GraphQLList instance will be returned, containing+ * the type called "User" found in the schema. If a type called "User" is not+ * found in the schema, then undefined will be returned.+ */++/* eslint-disable no-redeclare */++function typeFromAST(schema, typeNode) {+ /* eslint-enable no-redeclare */+ var innerType;++ if (typeNode.kind === Kind.LIST_TYPE) {+ innerType = typeFromAST(schema, typeNode.type);+ return innerType && GraphQLList(innerType);+ }++ if (typeNode.kind === Kind.NON_NULL_TYPE) {+ innerType = typeFromAST(schema, typeNode.type);+ return innerType && GraphQLNonNull(innerType);+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (typeNode.kind === Kind.NAMED_TYPE) {+ return schema.getType(typeNode.name.value);+ } // istanbul ignore next (Not reachable. All possible type nodes have been considered)+++ invariant(0, 'Unexpected type node: ' + inspect(typeNode));+}++/**+ * TypeInfo is a utility class which, given a GraphQL schema, can keep track+ * of the current field and type definitions at any point in a GraphQL document+ * AST during a recursive descent by calling `enter(node)` and `leave(node)`.+ */++var TypeInfo = /*#__PURE__*/function () {+ function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order+ // to support non-spec-compliant code bases. You should never need to use it.+ // It may disappear in the future.+ getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals+ // beginning somewhere other than documents.+ initialType) {+ this._schema = schema;+ this._typeStack = [];+ this._parentTypeStack = [];+ this._inputTypeStack = [];+ this._fieldDefStack = [];+ this._defaultValueStack = [];+ this._directive = null;+ this._argument = null;+ this._enumValue = null;+ this._getFieldDef = getFieldDefFn !== null && getFieldDefFn !== void 0 ? getFieldDefFn : getFieldDef;++ if (initialType) {+ if (isInputType(initialType)) {+ this._inputTypeStack.push(initialType);+ }++ if (isCompositeType(initialType)) {+ this._parentTypeStack.push(initialType);+ }++ if (isOutputType(initialType)) {+ this._typeStack.push(initialType);+ }+ }+ }++ var _proto = TypeInfo.prototype;++ _proto.getType = function getType() {+ if (this._typeStack.length > 0) {+ return this._typeStack[this._typeStack.length - 1];+ }+ };++ _proto.getParentType = function getParentType() {+ if (this._parentTypeStack.length > 0) {+ return this._parentTypeStack[this._parentTypeStack.length - 1];+ }+ };++ _proto.getInputType = function getInputType() {+ if (this._inputTypeStack.length > 0) {+ return this._inputTypeStack[this._inputTypeStack.length - 1];+ }+ };++ _proto.getParentInputType = function getParentInputType() {+ if (this._inputTypeStack.length > 1) {+ return this._inputTypeStack[this._inputTypeStack.length - 2];+ }+ };++ _proto.getFieldDef = function getFieldDef() {+ if (this._fieldDefStack.length > 0) {+ return this._fieldDefStack[this._fieldDefStack.length - 1];+ }+ };++ _proto.getDefaultValue = function getDefaultValue() {+ if (this._defaultValueStack.length > 0) {+ return this._defaultValueStack[this._defaultValueStack.length - 1];+ }+ };++ _proto.getDirective = function getDirective() {+ return this._directive;+ };++ _proto.getArgument = function getArgument() {+ return this._argument;+ };++ _proto.getEnumValue = function getEnumValue() {+ return this._enumValue;+ };++ _proto.enter = function enter(node) {+ var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop+ // any assumptions of a valid schema to ensure runtime types are properly+ // checked before continuing since TypeInfo is used as part of validation+ // which occurs before guarantees of schema and document validity.++ switch (node.kind) {+ case Kind.SELECTION_SET:+ {+ var namedType = getNamedType(this.getType());++ this._parentTypeStack.push(isCompositeType(namedType) ? namedType : undefined);++ break;+ }++ case Kind.FIELD:+ {+ var parentType = this.getParentType();+ var fieldDef;+ var fieldType;++ if (parentType) {+ fieldDef = this._getFieldDef(schema, parentType, node);++ if (fieldDef) {+ fieldType = fieldDef.type;+ }+ }++ this._fieldDefStack.push(fieldDef);++ this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined);++ break;+ }++ case Kind.DIRECTIVE:+ this._directive = schema.getDirective(node.name.value);+ break;++ case Kind.OPERATION_DEFINITION:+ {+ var type;++ switch (node.operation) {+ case 'query':+ type = schema.getQueryType();+ break;++ case 'mutation':+ type = schema.getMutationType();+ break;++ case 'subscription':+ type = schema.getSubscriptionType();+ break;+ }++ this._typeStack.push(isObjectType(type) ? type : undefined);++ break;+ }++ case Kind.INLINE_FRAGMENT:+ case Kind.FRAGMENT_DEFINITION:+ {+ var typeConditionAST = node.typeCondition;+ var outputType = typeConditionAST ? typeFromAST(schema, typeConditionAST) : getNamedType(this.getType());++ this._typeStack.push(isOutputType(outputType) ? outputType : undefined);++ break;+ }++ case Kind.VARIABLE_DEFINITION:+ {+ var inputType = typeFromAST(schema, node.type);++ this._inputTypeStack.push(isInputType(inputType) ? inputType : undefined);++ break;+ }++ case Kind.ARGUMENT:+ {+ var _this$getDirective;++ var argDef;+ var argType;+ var fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef();++ if (fieldOrDirective) {+ argDef = find(fieldOrDirective.args, function (arg) {+ return arg.name === node.name.value;+ });++ if (argDef) {+ argType = argDef.type;+ }+ }++ this._argument = argDef;++ this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);++ this._inputTypeStack.push(isInputType(argType) ? argType : undefined);++ break;+ }++ case Kind.LIST:+ {+ var listType = getNullableType(this.getInputType());+ var itemType = isListType(listType) ? listType.ofType : listType; // List positions never have a default value.++ this._defaultValueStack.push(undefined);++ this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined);++ break;+ }++ case Kind.OBJECT_FIELD:+ {+ var objectType = getNamedType(this.getInputType());+ var inputFieldType;+ var inputField;++ if (isInputObjectType(objectType)) {+ inputField = objectType.getFields()[node.name.value];++ if (inputField) {+ inputFieldType = inputField.type;+ }+ }++ this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined);++ this._inputTypeStack.push(isInputType(inputFieldType) ? inputFieldType : undefined);++ break;+ }++ case Kind.ENUM:+ {+ var enumType = getNamedType(this.getInputType());+ var enumValue;++ if (isEnumType(enumType)) {+ enumValue = enumType.getValue(node.value);+ }++ this._enumValue = enumValue;+ break;+ }+ }+ };++ _proto.leave = function leave(node) {+ switch (node.kind) {+ case Kind.SELECTION_SET:+ this._parentTypeStack.pop();++ break;++ case Kind.FIELD:+ this._fieldDefStack.pop();++ this._typeStack.pop();++ break;++ case Kind.DIRECTIVE:+ this._directive = null;+ break;++ case Kind.OPERATION_DEFINITION:+ case Kind.INLINE_FRAGMENT:+ case Kind.FRAGMENT_DEFINITION:+ this._typeStack.pop();++ break;++ case Kind.VARIABLE_DEFINITION:+ this._inputTypeStack.pop();++ break;++ case Kind.ARGUMENT:+ this._argument = null;++ this._defaultValueStack.pop();++ this._inputTypeStack.pop();++ break;++ case Kind.LIST:+ case Kind.OBJECT_FIELD:+ this._defaultValueStack.pop();++ this._inputTypeStack.pop();++ break;++ case Kind.ENUM:+ this._enumValue = null;+ break;+ }+ };++ return TypeInfo;+}();+/**+ * Not exactly the same as the executor's definition of getFieldDef, in this+ * statically evaluated environment we do not always have an Object type,+ * and need to handle Interface and Union types.+ */++function getFieldDef(schema, parentType, fieldNode) {+ var name = fieldNode.name.value;++ if (name === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {+ return SchemaMetaFieldDef;+ }++ if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {+ return TypeMetaFieldDef;+ }++ if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) {+ return TypeNameMetaFieldDef;+ }++ if (isObjectType(parentType) || isInterfaceType(parentType)) {+ return parentType.getFields()[name];+ }+}+/**+ * 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;+ }+ };+}++function isDefinitionNode(node) {+ return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node);+}+function isExecutableDefinitionNode(node) {+ return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION;+}+function isSelectionNode(node) {+ return node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_SPREAD || node.kind === Kind.INLINE_FRAGMENT;+}+function isValueNode(node) {+ return node.kind === Kind.VARIABLE || node.kind === Kind.INT || node.kind === Kind.FLOAT || node.kind === Kind.STRING || node.kind === Kind.BOOLEAN || node.kind === Kind.NULL || node.kind === Kind.ENUM || node.kind === Kind.LIST || node.kind === Kind.OBJECT;+}+function isTypeNode(node) {+ return node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || node.kind === Kind.NON_NULL_TYPE;+}+function isTypeSystemDefinitionNode(node) {+ return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION;+}+function isTypeDefinitionNode(node) {+ return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION;+}+function isTypeSystemExtensionNode(node) {+ return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);+}+function isTypeExtensionNode(node) {+ return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION;+}++/**+ * Executable definitions+ *+ * A GraphQL document is only valid for execution if all definitions are either+ * operation or fragment definitions.+ */+function ExecutableDefinitionsRule(context) {+ return {+ Document: function Document(node) {+ for (var _i2 = 0, _node$definitions2 = node.definitions; _i2 < _node$definitions2.length; _i2++) {+ var definition = _node$definitions2[_i2];++ if (!isExecutableDefinitionNode(definition)) {+ var defName = definition.kind === Kind.SCHEMA_DEFINITION || definition.kind === Kind.SCHEMA_EXTENSION ? 'schema' : '"' + definition.name.value + '"';+ context.reportError(new GraphQLError("The ".concat(defName, " definition is not executable."), definition));+ }+ }++ return false;+ }+ };+}++/**+ * Unique operation names+ *+ * A GraphQL document is only valid if all defined operations have unique names.+ */+function UniqueOperationNamesRule(context) {+ var knownOperationNames = Object.create(null);+ return {+ OperationDefinition: function OperationDefinition(node) {+ var operationName = node.name;++ if (operationName) {+ if (knownOperationNames[operationName.value]) {+ context.reportError(new GraphQLError("There can be only one operation named \"".concat(operationName.value, "\"."), [knownOperationNames[operationName.value], operationName]));+ } else {+ knownOperationNames[operationName.value] = operationName;+ }+ }++ return false;+ },+ FragmentDefinition: function FragmentDefinition() {+ return false;+ }+ };+}++/**+ * Lone anonymous operation+ *+ * A GraphQL document is only valid if when it contains an anonymous operation+ * (the query short-hand) that it contains only that one operation definition.+ */+function LoneAnonymousOperationRule(context) {+ var operationCount = 0;+ return {+ Document: function Document(node) {+ operationCount = node.definitions.filter(function (definition) {+ return definition.kind === Kind.OPERATION_DEFINITION;+ }).length;+ },+ OperationDefinition: function OperationDefinition(node) {+ if (!node.name && operationCount > 1) {+ context.reportError(new GraphQLError('This anonymous operation must be the only defined operation.', node));+ }+ }+ };+}++/**+ * Subscriptions must only include one field.+ *+ * A GraphQL subscription is valid only if it contains a single root field.+ */+function SingleFieldSubscriptionsRule(context) {+ return {+ OperationDefinition: function OperationDefinition(node) {+ if (node.operation === 'subscription') {+ if (node.selectionSet.selections.length !== 1) {+ context.reportError(new GraphQLError(node.name ? "Subscription \"".concat(node.name.value, "\" must select only one top level field.") : 'Anonymous Subscription must select only one top level field.', node.selectionSet.selections.slice(1)));+ }+ }+ }+ };+}++/**+ * Known type names+ *+ * A GraphQL document is only valid if referenced types (specifically+ * variable definitions and fragment conditions) are defined by the type schema.+ */+function KnownTypeNamesRule(context) {+ var schema = context.getSchema();+ var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);+ var definedTypes = Object.create(null);++ for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {+ var def = _context$getDocument$2[_i2];++ if (isTypeDefinitionNode(def)) {+ definedTypes[def.name.value] = true;+ }+ }++ var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));+ return {+ NamedType: function NamedType(node, _1, parent, _2, ancestors) {+ var typeName = node.name.value;++ if (!existingTypesMap[typeName] && !definedTypes[typeName]) {+ var _ancestors$;++ var definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent;+ var isSDL = definitionNode != null && isSDLNode(definitionNode);++ if (isSDL && isStandardTypeName(typeName)) {+ return;+ }++ var suggestedTypes = suggestionList(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames);+ context.reportError(new GraphQLError("Unknown type \"".concat(typeName, "\".") + didYouMean(suggestedTypes), node));+ }+ }+ };+}+var standardTypeNames = [].concat(specifiedScalarTypes, introspectionTypes).map(function (type) {+ return type.name;+});++function isStandardTypeName(typeName) {+ return standardTypeNames.indexOf(typeName) !== -1;+}++function isSDLNode(value) {+ return !Array.isArray(value) && (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value));+}++/**+ * Fragments on composite type+ *+ * Fragments use a type condition to determine if they apply, since fragments+ * can only be spread into a composite type (object, interface, or union), the+ * type condition must also be a composite type.+ */+function FragmentsOnCompositeTypesRule(context) {+ return {+ InlineFragment: function InlineFragment(node) {+ var typeCondition = node.typeCondition;++ if (typeCondition) {+ var type = typeFromAST(context.getSchema(), typeCondition);++ if (type && !isCompositeType(type)) {+ var typeStr = print(typeCondition);+ context.reportError(new GraphQLError("Fragment cannot condition on non composite type \"".concat(typeStr, "\"."), typeCondition));+ }+ }+ },+ FragmentDefinition: function FragmentDefinition(node) {+ var type = typeFromAST(context.getSchema(), node.typeCondition);++ if (type && !isCompositeType(type)) {+ var typeStr = print(node.typeCondition);+ context.reportError(new GraphQLError("Fragment \"".concat(node.name.value, "\" cannot condition on non composite type \"").concat(typeStr, "\"."), node.typeCondition));+ }+ }+ };+}++/**+ * Variables are input types+ *+ * A GraphQL operation is only valid if all the variables it defines are of+ * input types (scalar, enum, or input object).+ */+function VariablesAreInputTypesRule(context) {+ return {+ VariableDefinition: function VariableDefinition(node) {+ var type = typeFromAST(context.getSchema(), node.type);++ if (type && !isInputType(type)) {+ var variableName = node.variable.name.value;+ var typeName = print(node.type);+ context.reportError(new GraphQLError("Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\"."), node.type));+ }+ }+ };+}++/**+ * Scalar leafs+ *+ * A GraphQL document is valid only if all leaf fields (fields without+ * sub selections) are of scalar or enum types.+ */+function ScalarLeafsRule(context) {+ return {+ Field: function Field(node) {+ var type = context.getType();+ var selectionSet = node.selectionSet;++ if (type) {+ if (isLeafType(getNamedType(type))) {+ if (selectionSet) {+ var fieldName = node.name.value;+ var typeStr = inspect(type);+ context.reportError(new GraphQLError("Field \"".concat(fieldName, "\" must not have a selection since type \"").concat(typeStr, "\" has no subfields."), selectionSet));+ }+ } else if (!selectionSet) {+ var _fieldName = node.name.value;++ var _typeStr = inspect(type);++ context.reportError(new GraphQLError("Field \"".concat(_fieldName, "\" of type \"").concat(_typeStr, "\" must have a selection of subfields. Did you mean \"").concat(_fieldName, " { ... }\"?"), node));+ }+ }+ }+ };+}++/**+ * Fields on correct type+ *+ * A GraphQL document is only valid if all fields selected are defined by the+ * parent type, or are an allowed meta field such as __typename.+ */+function FieldsOnCorrectTypeRule(context) {+ return {+ Field: function Field(node) {+ var type = context.getParentType();++ if (type) {+ var fieldDef = context.getFieldDef();++ if (!fieldDef) {+ // This field doesn't exist, lets look for suggestions.+ var schema = context.getSchema();+ var fieldName = node.name.value; // First determine if there are any suggested types to condition on.++ var suggestion = didYouMean('to use an inline fragment on', getSuggestedTypeNames(schema, type, fieldName)); // If there are no suggested types, then perhaps this was a typo?++ if (suggestion === '') {+ suggestion = didYouMean(getSuggestedFieldNames(type, fieldName));+ } // Report an error, including helpful suggestions.+++ context.reportError(new GraphQLError("Cannot query field \"".concat(fieldName, "\" on type \"").concat(type.name, "\".") + suggestion, node));+ }+ }+ }+ };+}+/**+ * Go through all of the implementations of type, as well as the interfaces that+ * they implement. If any of those types include the provided field, suggest them,+ * sorted by how often the type is referenced.+ */++function getSuggestedTypeNames(schema, type, fieldName) {+ if (!isAbstractType(type)) {+ // Must be an Object type, which does not have possible fields.+ return [];+ }++ var suggestedTypes = new Set();+ var usageCount = Object.create(null);++ for (var _i2 = 0, _schema$getPossibleTy2 = schema.getPossibleTypes(type); _i2 < _schema$getPossibleTy2.length; _i2++) {+ var possibleType = _schema$getPossibleTy2[_i2];++ if (!possibleType.getFields()[fieldName]) {+ continue;+ } // This object type defines this field.+++ suggestedTypes.add(possibleType);+ usageCount[possibleType.name] = 1;++ for (var _i4 = 0, _possibleType$getInte2 = possibleType.getInterfaces(); _i4 < _possibleType$getInte2.length; _i4++) {+ var _usageCount$possibleI;++ var possibleInterface = _possibleType$getInte2[_i4];++ if (!possibleInterface.getFields()[fieldName]) {+ continue;+ } // This interface type defines this field.+++ suggestedTypes.add(possibleInterface);+ usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1;+ }+ }++ return arrayFrom(suggestedTypes).sort(function (typeA, typeB) {+ // Suggest both interface and object types based on how common they are.+ var usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name];++ if (usageCountDiff !== 0) {+ return usageCountDiff;+ } // Suggest super types first followed by subtypes+++ if (isInterfaceType(typeA) && schema.isSubType(typeA, typeB)) {+ return -1;+ }++ if (isInterfaceType(typeB) && schema.isSubType(typeB, typeA)) {+ return 1;+ }++ return typeA.name.localeCompare(typeB.name);+ }).map(function (x) {+ return x.name;+ });+}+/**+ * For the field name provided, determine if there are any similar field names+ * that may be the result of a typo.+ */+++function getSuggestedFieldNames(type, fieldName) {+ if (isObjectType(type) || isInterfaceType(type)) {+ var possibleFieldNames = Object.keys(type.getFields());+ return suggestionList(fieldName, possibleFieldNames);+ } // Otherwise, must be a Union type, which does not define fields.+++ return [];+}++/**+ * Unique fragment names+ *+ * A GraphQL document is only valid if all defined fragments have unique names.+ */+function UniqueFragmentNamesRule(context) {+ var knownFragmentNames = Object.create(null);+ return {+ OperationDefinition: function OperationDefinition() {+ return false;+ },+ FragmentDefinition: function FragmentDefinition(node) {+ var fragmentName = node.name.value;++ if (knownFragmentNames[fragmentName]) {+ context.reportError(new GraphQLError("There can be only one fragment named \"".concat(fragmentName, "\"."), [knownFragmentNames[fragmentName], node.name]));+ } else {+ knownFragmentNames[fragmentName] = node.name;+ }++ return false;+ }+ };+}++/**+ * Known fragment names+ *+ * A GraphQL document is only valid if all `...Fragment` fragment spreads refer+ * to fragments defined in the same document.+ */+function KnownFragmentNamesRule(context) {+ return {+ FragmentSpread: function FragmentSpread(node) {+ var fragmentName = node.name.value;+ var fragment = context.getFragment(fragmentName);++ if (!fragment) {+ context.reportError(new GraphQLError("Unknown fragment \"".concat(fragmentName, "\"."), node.name));+ }+ }+ };+}++/**+ * No unused fragments+ *+ * A GraphQL document is only valid if all fragment definitions are spread+ * within operations, or spread within other fragments spread within operations.+ */+function NoUnusedFragmentsRule(context) {+ var operationDefs = [];+ var fragmentDefs = [];+ return {+ OperationDefinition: function OperationDefinition(node) {+ operationDefs.push(node);+ return false;+ },+ FragmentDefinition: function FragmentDefinition(node) {+ fragmentDefs.push(node);+ return false;+ },+ Document: {+ leave: function leave() {+ var fragmentNameUsed = Object.create(null);++ for (var _i2 = 0; _i2 < operationDefs.length; _i2++) {+ var operation = operationDefs[_i2];++ for (var _i4 = 0, _context$getRecursive2 = context.getRecursivelyReferencedFragments(operation); _i4 < _context$getRecursive2.length; _i4++) {+ var fragment = _context$getRecursive2[_i4];+ fragmentNameUsed[fragment.name.value] = true;+ }+ }++ for (var _i6 = 0; _i6 < fragmentDefs.length; _i6++) {+ var fragmentDef = fragmentDefs[_i6];+ var fragName = fragmentDef.name.value;++ if (fragmentNameUsed[fragName] !== true) {+ context.reportError(new GraphQLError("Fragment \"".concat(fragName, "\" is never used."), fragmentDef));+ }+ }+ }+ }+ };+}++/**+ * Possible fragment spread+ *+ * A fragment spread is only valid if the type condition could ever possibly+ * be true: if there is a non-empty intersection of the possible parent types,+ * and possible types which pass the type condition.+ */+function PossibleFragmentSpreadsRule(context) {+ return {+ InlineFragment: function InlineFragment(node) {+ var fragType = context.getType();+ var parentType = context.getParentType();++ if (isCompositeType(fragType) && isCompositeType(parentType) && !doTypesOverlap(context.getSchema(), fragType, parentType)) {+ var parentTypeStr = inspect(parentType);+ var fragTypeStr = inspect(fragType);+ context.reportError(new GraphQLError("Fragment cannot be spread here as objects of type \"".concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node));+ }+ },+ FragmentSpread: function FragmentSpread(node) {+ var fragName = node.name.value;+ var fragType = getFragmentType(context, fragName);+ var parentType = context.getParentType();++ if (fragType && parentType && !doTypesOverlap(context.getSchema(), fragType, parentType)) {+ var parentTypeStr = inspect(parentType);+ var fragTypeStr = inspect(fragType);+ context.reportError(new GraphQLError("Fragment \"".concat(fragName, "\" cannot be spread here as objects of type \"").concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node));+ }+ }+ };+}++function getFragmentType(context, name) {+ var frag = context.getFragment(name);++ if (frag) {+ var type = typeFromAST(context.getSchema(), frag.typeCondition);++ if (isCompositeType(type)) {+ return type;+ }+ }+}++function NoFragmentCyclesRule(context) {+ // Tracks already visited fragments to maintain O(N) and to ensure that cycles+ // are not redundantly reported.+ var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors++ var spreadPath = []; // Position in the spread path++ var spreadPathIndexByName = Object.create(null);+ return {+ OperationDefinition: function OperationDefinition() {+ return false;+ },+ FragmentDefinition: function FragmentDefinition(node) {+ detectCycleRecursive(node);+ return false;+ }+ }; // This does a straight-forward DFS to find cycles.+ // It does not terminate when a cycle was found but continues to explore+ // the graph to find all possible cycles.++ function detectCycleRecursive(fragment) {+ if (visitedFrags[fragment.name.value]) {+ return;+ }++ var fragmentName = fragment.name.value;+ visitedFrags[fragmentName] = true;+ var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);++ if (spreadNodes.length === 0) {+ return;+ }++ spreadPathIndexByName[fragmentName] = spreadPath.length;++ for (var _i2 = 0; _i2 < spreadNodes.length; _i2++) {+ var spreadNode = spreadNodes[_i2];+ var spreadName = spreadNode.name.value;+ var cycleIndex = spreadPathIndexByName[spreadName];+ spreadPath.push(spreadNode);++ if (cycleIndex === undefined) {+ var spreadFragment = context.getFragment(spreadName);++ if (spreadFragment) {+ detectCycleRecursive(spreadFragment);+ }+ } else {+ var cyclePath = spreadPath.slice(cycleIndex);+ var viaPath = cyclePath.slice(0, -1).map(function (s) {+ return '"' + s.name.value + '"';+ }).join(', ');+ context.reportError(new GraphQLError("Cannot spread fragment \"".concat(spreadName, "\" within itself") + (viaPath !== '' ? " via ".concat(viaPath, ".") : '.'), cyclePath));+ }++ spreadPath.pop();+ }++ spreadPathIndexByName[fragmentName] = undefined;+ }+}++/**+ * Unique variable names+ *+ * A GraphQL operation is only valid if all its variables are uniquely named.+ */+function UniqueVariableNamesRule(context) {+ var knownVariableNames = Object.create(null);+ return {+ OperationDefinition: function OperationDefinition() {+ knownVariableNames = Object.create(null);+ },+ VariableDefinition: function VariableDefinition(node) {+ var variableName = node.variable.name.value;++ if (knownVariableNames[variableName]) {+ context.reportError(new GraphQLError("There can be only one variable named \"$".concat(variableName, "\"."), [knownVariableNames[variableName], node.variable.name]));+ } else {+ knownVariableNames[variableName] = node.variable.name;+ }+ }+ };+}++/**+ * No undefined variables+ *+ * A GraphQL operation is only valid if all variables encountered, both directly+ * and via fragment spreads, are defined by that operation.+ */+function NoUndefinedVariablesRule(context) {+ var variableNameDefined = Object.create(null);+ return {+ OperationDefinition: {+ enter: function enter() {+ variableNameDefined = Object.create(null);+ },+ leave: function leave(operation) {+ var usages = context.getRecursiveVariableUsages(operation);++ for (var _i2 = 0; _i2 < usages.length; _i2++) {+ var _ref2 = usages[_i2];+ var node = _ref2.node;+ var varName = node.name.value;++ if (variableNameDefined[varName] !== true) {+ context.reportError(new GraphQLError(operation.name ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(varName, "\" is not defined."), [node, operation]));+ }+ }+ }+ },+ VariableDefinition: function VariableDefinition(node) {+ variableNameDefined[node.variable.name.value] = true;+ }+ };+}++/**+ * No unused variables+ *+ * A GraphQL operation is only valid if all variables defined by an operation+ * are used, either directly or within a spread fragment.+ */+function NoUnusedVariablesRule(context) {+ var variableDefs = [];+ return {+ OperationDefinition: {+ enter: function enter() {+ variableDefs = [];+ },+ leave: function leave(operation) {+ var variableNameUsed = Object.create(null);+ var usages = context.getRecursiveVariableUsages(operation);++ for (var _i2 = 0; _i2 < usages.length; _i2++) {+ var _ref2 = usages[_i2];+ var node = _ref2.node;+ variableNameUsed[node.name.value] = true;+ }++ for (var _i4 = 0, _variableDefs2 = variableDefs; _i4 < _variableDefs2.length; _i4++) {+ var variableDef = _variableDefs2[_i4];+ var variableName = variableDef.variable.name.value;++ if (variableNameUsed[variableName] !== true) {+ context.reportError(new GraphQLError(operation.name ? "Variable \"$".concat(variableName, "\" is never used in operation \"").concat(operation.name.value, "\".") : "Variable \"$".concat(variableName, "\" is never used."), variableDef));+ }+ }+ }+ },+ VariableDefinition: function VariableDefinition(def) {+ variableDefs.push(def);+ }+ };+}++/**+ * Known directives+ *+ * A GraphQL document is only valid if all `@directives` are known by the+ * schema and legally positioned.+ */+function KnownDirectivesRule(context) {+ var locationsMap = Object.create(null);+ var schema = context.getSchema();+ var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;++ for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {+ var directive = definedDirectives[_i2];+ locationsMap[directive.name] = directive.locations;+ }++ var astDefinitions = context.getDocument().definitions;++ for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {+ var def = astDefinitions[_i4];++ if (def.kind === Kind.DIRECTIVE_DEFINITION) {+ locationsMap[def.name.value] = def.locations.map(function (name) {+ return name.value;+ });+ }+ }++ return {+ Directive: function Directive(node, _key, _parent, _path, ancestors) {+ var name = node.name.value;+ var locations = locationsMap[name];++ if (!locations) {+ context.reportError(new GraphQLError("Unknown directive \"@".concat(name, "\"."), node));+ return;+ }++ var candidateLocation = getDirectiveLocationForASTPath(ancestors);++ if (candidateLocation && locations.indexOf(candidateLocation) === -1) {+ context.reportError(new GraphQLError("Directive \"@".concat(name, "\" may not be used on ").concat(candidateLocation, "."), node));+ }+ }+ };+}++function getDirectiveLocationForASTPath(ancestors) {+ var appliedTo = ancestors[ancestors.length - 1];+ !Array.isArray(appliedTo) || invariant(0);++ switch (appliedTo.kind) {+ case Kind.OPERATION_DEFINITION:+ return getDirectiveLocationForOperation(appliedTo.operation);++ case Kind.FIELD:+ return DirectiveLocation.FIELD;++ case Kind.FRAGMENT_SPREAD:+ return DirectiveLocation.FRAGMENT_SPREAD;++ case Kind.INLINE_FRAGMENT:+ return DirectiveLocation.INLINE_FRAGMENT;++ case Kind.FRAGMENT_DEFINITION:+ return DirectiveLocation.FRAGMENT_DEFINITION;++ case Kind.VARIABLE_DEFINITION:+ return DirectiveLocation.VARIABLE_DEFINITION;++ case Kind.SCHEMA_DEFINITION:+ case Kind.SCHEMA_EXTENSION:+ return DirectiveLocation.SCHEMA;++ case Kind.SCALAR_TYPE_DEFINITION:+ case Kind.SCALAR_TYPE_EXTENSION:+ return DirectiveLocation.SCALAR;++ case Kind.OBJECT_TYPE_DEFINITION:+ case Kind.OBJECT_TYPE_EXTENSION:+ return DirectiveLocation.OBJECT;++ case Kind.FIELD_DEFINITION:+ return DirectiveLocation.FIELD_DEFINITION;++ case Kind.INTERFACE_TYPE_DEFINITION:+ case Kind.INTERFACE_TYPE_EXTENSION:+ return DirectiveLocation.INTERFACE;++ case Kind.UNION_TYPE_DEFINITION:+ case Kind.UNION_TYPE_EXTENSION:+ return DirectiveLocation.UNION;++ case Kind.ENUM_TYPE_DEFINITION:+ case Kind.ENUM_TYPE_EXTENSION:+ return DirectiveLocation.ENUM;++ case Kind.ENUM_VALUE_DEFINITION:+ return DirectiveLocation.ENUM_VALUE;++ case Kind.INPUT_OBJECT_TYPE_DEFINITION:+ case Kind.INPUT_OBJECT_TYPE_EXTENSION:+ return DirectiveLocation.INPUT_OBJECT;++ case Kind.INPUT_VALUE_DEFINITION:+ {+ var parentNode = ancestors[ancestors.length - 3];+ return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? DirectiveLocation.INPUT_FIELD_DEFINITION : DirectiveLocation.ARGUMENT_DEFINITION;+ }+ }+}++function getDirectiveLocationForOperation(operation) {+ switch (operation) {+ case 'query':+ return DirectiveLocation.QUERY;++ case 'mutation':+ return DirectiveLocation.MUTATION;++ case 'subscription':+ return DirectiveLocation.SUBSCRIPTION;+ } // istanbul ignore next (Not reachable. All possible types have been considered)+++ invariant(0, 'Unexpected operation: ' + inspect(operation));+}++/**+ * Unique directive names per location+ *+ * A GraphQL document is only valid if all non-repeatable directives at+ * a given location are uniquely named.+ */+function UniqueDirectivesPerLocationRule(context) {+ var uniqueDirectiveMap = Object.create(null);+ var schema = context.getSchema();+ var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;++ for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {+ var directive = definedDirectives[_i2];+ uniqueDirectiveMap[directive.name] = !directive.isRepeatable;+ }++ var astDefinitions = context.getDocument().definitions;++ for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {+ var def = astDefinitions[_i4];++ if (def.kind === Kind.DIRECTIVE_DEFINITION) {+ uniqueDirectiveMap[def.name.value] = !def.repeatable;+ }+ }++ var schemaDirectives = Object.create(null);+ var typeDirectivesMap = Object.create(null);+ return {+ // Many different AST nodes may contain directives. Rather than listing+ // them all, just listen for entering any node, and check to see if it+ // defines any directives.+ enter: function enter(node) {+ if (node.directives == null) {+ return;+ }++ var seenDirectives;++ if (node.kind === Kind.SCHEMA_DEFINITION || node.kind === Kind.SCHEMA_EXTENSION) {+ seenDirectives = schemaDirectives;+ } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) {+ var typeName = node.name.value;+ seenDirectives = typeDirectivesMap[typeName];++ if (seenDirectives === undefined) {+ typeDirectivesMap[typeName] = seenDirectives = Object.create(null);+ }+ } else {+ seenDirectives = Object.create(null);+ }++ for (var _i6 = 0, _node$directives2 = node.directives; _i6 < _node$directives2.length; _i6++) {+ var _directive = _node$directives2[_i6];+ var directiveName = _directive.name.value;++ if (uniqueDirectiveMap[directiveName]) {+ if (seenDirectives[directiveName]) {+ context.reportError(new GraphQLError("The directive \"@".concat(directiveName, "\" can only be used once at this location."), [seenDirectives[directiveName], _directive]));+ } else {+ seenDirectives[directiveName] = _directive;+ }+ }+ }+ }+ };+}++function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }++function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }++function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }++/**+ * Known argument names+ *+ * A GraphQL field is only valid if all supplied arguments are defined by+ * that field.+ */+function KnownArgumentNamesRule(context) {+ return _objectSpread(_objectSpread({}, KnownArgumentNamesOnDirectivesRule(context)), {}, {+ Argument: function Argument(argNode) {+ var argDef = context.getArgument();+ var fieldDef = context.getFieldDef();+ var parentType = context.getParentType();++ if (!argDef && fieldDef && parentType) {+ var argName = argNode.name.value;+ var knownArgsNames = fieldDef.args.map(function (arg) {+ return arg.name;+ });+ var suggestions = suggestionList(argName, knownArgsNames);+ context.reportError(new GraphQLError("Unknown argument \"".concat(argName, "\" on field \"").concat(parentType.name, ".").concat(fieldDef.name, "\".") + didYouMean(suggestions), argNode));+ }+ }+ });+}+/**+ * @internal+ */++function KnownArgumentNamesOnDirectivesRule(context) {+ var directiveArgs = Object.create(null);+ var schema = context.getSchema();+ var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;++ for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {+ var directive = definedDirectives[_i2];+ directiveArgs[directive.name] = directive.args.map(function (arg) {+ return arg.name;+ });+ }++ var astDefinitions = context.getDocument().definitions;++ for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {+ var def = astDefinitions[_i4];++ if (def.kind === Kind.DIRECTIVE_DEFINITION) {+ var _def$arguments;++ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var argsNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : [];+ directiveArgs[def.name.value] = argsNodes.map(function (arg) {+ return arg.name.value;+ });+ }+ }++ return {+ Directive: function Directive(directiveNode) {+ var directiveName = directiveNode.name.value;+ var knownArgs = directiveArgs[directiveName];++ if (directiveNode.arguments && knownArgs) {+ for (var _i6 = 0, _directiveNode$argume2 = directiveNode.arguments; _i6 < _directiveNode$argume2.length; _i6++) {+ var argNode = _directiveNode$argume2[_i6];+ var argName = argNode.name.value;++ if (knownArgs.indexOf(argName) === -1) {+ var suggestions = suggestionList(argName, knownArgs);+ context.reportError(new GraphQLError("Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\".") + didYouMean(suggestions), argNode));+ }+ }+ }++ return false;+ }+ };+}++/**+ * Unique argument names+ *+ * A GraphQL field or directive is only valid if all supplied arguments are+ * uniquely named.+ */+function UniqueArgumentNamesRule(context) {+ var knownArgNames = Object.create(null);+ return {+ Field: function Field() {+ knownArgNames = Object.create(null);+ },+ Directive: function Directive() {+ knownArgNames = Object.create(null);+ },+ Argument: function Argument(node) {+ var argName = node.name.value;++ if (knownArgNames[argName]) {+ context.reportError(new GraphQLError("There can be only one argument named \"".concat(argName, "\"."), [knownArgNames[argName], node.name]));+ } else {+ knownArgNames[argName] = node.name;+ }++ return false;+ }+ };+}++/**+ * Value literals of correct type+ *+ * A GraphQL document is only valid if all value literals are of the type+ * expected at their position.+ */+function ValuesOfCorrectTypeRule(context) {+ return {+ ListValue: function ListValue(node) {+ // Note: TypeInfo will traverse into a list's item type, so look to the+ // parent input type to check if it is a list.+ var type = getNullableType(context.getParentInputType());++ if (!isListType(type)) {+ isValidValueNode(context, node);+ return false; // Don't traverse further.+ }+ },+ ObjectValue: function ObjectValue(node) {+ var type = getNamedType(context.getInputType());++ if (!isInputObjectType(type)) {+ isValidValueNode(context, node);+ return false; // Don't traverse further.+ } // Ensure every required field exists.+++ var fieldNodeMap = keyMap(node.fields, function (field) {+ return field.name.value;+ });++ for (var _i2 = 0, _objectValues2 = objectValues(type.getFields()); _i2 < _objectValues2.length; _i2++) {+ var fieldDef = _objectValues2[_i2];+ var fieldNode = fieldNodeMap[fieldDef.name];++ if (!fieldNode && isRequiredInputField(fieldDef)) {+ var typeStr = inspect(fieldDef.type);+ context.reportError(new GraphQLError("Field \"".concat(type.name, ".").concat(fieldDef.name, "\" of required type \"").concat(typeStr, "\" was not provided."), node));+ }+ }+ },+ ObjectField: function ObjectField(node) {+ var parentType = getNamedType(context.getParentInputType());+ var fieldType = context.getInputType();++ if (!fieldType && isInputObjectType(parentType)) {+ var suggestions = suggestionList(node.name.value, Object.keys(parentType.getFields()));+ context.reportError(new GraphQLError("Field \"".concat(node.name.value, "\" is not defined by type \"").concat(parentType.name, "\".") + didYouMean(suggestions), node));+ }+ },+ NullValue: function NullValue(node) {+ var type = context.getInputType();++ if (isNonNullType(type)) {+ context.reportError(new GraphQLError("Expected value of type \"".concat(inspect(type), "\", found ").concat(print(node), "."), node));+ }+ },+ EnumValue: function EnumValue(node) {+ return isValidValueNode(context, node);+ },+ IntValue: function IntValue(node) {+ return isValidValueNode(context, node);+ },+ FloatValue: function FloatValue(node) {+ return isValidValueNode(context, node);+ },+ StringValue: function StringValue(node) {+ return isValidValueNode(context, node);+ },+ BooleanValue: function BooleanValue(node) {+ return isValidValueNode(context, node);+ }+ };+}+/**+ * Any value literal may be a valid representation of a Scalar, depending on+ * that scalar type.+ */++function isValidValueNode(context, node) {+ // Report any error at the full type expected by the location.+ var locationType = context.getInputType();++ if (!locationType) {+ return;+ }++ var type = getNamedType(locationType);++ if (!isLeafType(type)) {+ var typeStr = inspect(locationType);+ context.reportError(new GraphQLError("Expected value of type \"".concat(typeStr, "\", found ").concat(print(node), "."), node));+ return;+ } // Scalars and Enums determine if a literal value is valid via parseLiteral(),+ // which may throw or return an invalid value to indicate failure.+++ try {+ var parseResult = type.parseLiteral(node, undefined+ /* variables */+ );++ if (parseResult === undefined) {+ var _typeStr = inspect(locationType);++ context.reportError(new GraphQLError("Expected value of type \"".concat(_typeStr, "\", found ").concat(print(node), "."), node));+ }+ } catch (error) {+ var _typeStr2 = inspect(locationType);++ if (error instanceof GraphQLError) {+ context.reportError(error);+ } else {+ context.reportError(new GraphQLError("Expected value of type \"".concat(_typeStr2, "\", found ").concat(print(node), "; ") + error.message, node, undefined, undefined, undefined, error));+ }+ }+}++function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }++function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }++function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }++/**+ * Provided required arguments+ *+ * A field or directive is only valid if all required (non-null without a+ * default value) field arguments have been provided.+ */+function ProvidedRequiredArgumentsRule(context) {+ return _objectSpread$1(_objectSpread$1({}, ProvidedRequiredArgumentsOnDirectivesRule(context)), {}, {+ Field: {+ // Validate on leave to allow for deeper errors to appear first.+ leave: function leave(fieldNode) {+ var _fieldNode$arguments;++ var fieldDef = context.getFieldDef();++ if (!fieldDef) {+ return false;+ } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+++ var argNodes = (_fieldNode$arguments = fieldNode.arguments) !== null && _fieldNode$arguments !== void 0 ? _fieldNode$arguments : [];+ var argNodeMap = keyMap(argNodes, function (arg) {+ return arg.name.value;+ });++ for (var _i2 = 0, _fieldDef$args2 = fieldDef.args; _i2 < _fieldDef$args2.length; _i2++) {+ var argDef = _fieldDef$args2[_i2];+ var argNode = argNodeMap[argDef.name];++ if (!argNode && isRequiredArgument(argDef)) {+ var argTypeStr = inspect(argDef.type);+ context.reportError(new GraphQLError("Field \"".concat(fieldDef.name, "\" argument \"").concat(argDef.name, "\" of type \"").concat(argTypeStr, "\" is required, but it was not provided."), fieldNode));+ }+ }+ }+ }+ });+}+/**+ * @internal+ */++function ProvidedRequiredArgumentsOnDirectivesRule(context) {+ var requiredArgsMap = Object.create(null);+ var schema = context.getSchema();+ var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;++ for (var _i4 = 0; _i4 < definedDirectives.length; _i4++) {+ var directive = definedDirectives[_i4];+ requiredArgsMap[directive.name] = keyMap(directive.args.filter(isRequiredArgument), function (arg) {+ return arg.name;+ });+ }++ var astDefinitions = context.getDocument().definitions;++ for (var _i6 = 0; _i6 < astDefinitions.length; _i6++) {+ var def = astDefinitions[_i6];++ if (def.kind === Kind.DIRECTIVE_DEFINITION) {+ var _def$arguments;++ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var argNodes = (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : [];+ requiredArgsMap[def.name.value] = keyMap(argNodes.filter(isRequiredArgumentNode), function (arg) {+ return arg.name.value;+ });+ }+ }++ return {+ Directive: {+ // Validate on leave to allow for deeper errors to appear first.+ leave: function leave(directiveNode) {+ var directiveName = directiveNode.name.value;+ var requiredArgs = requiredArgsMap[directiveName];++ if (requiredArgs) {+ var _directiveNode$argume;++ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var _argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : [];++ var argNodeMap = keyMap(_argNodes, function (arg) {+ return arg.name.value;+ });++ for (var _i8 = 0, _Object$keys2 = Object.keys(requiredArgs); _i8 < _Object$keys2.length; _i8++) {+ var argName = _Object$keys2[_i8];++ if (!argNodeMap[argName]) {+ var argType = requiredArgs[argName].type;+ var argTypeStr = isType(argType) ? inspect(argType) : print(argType);+ context.reportError(new GraphQLError("Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type \"").concat(argTypeStr, "\" is required, but it was not provided."), directiveNode));+ }+ }+ }+ }+ }+ };+}++function isRequiredArgumentNode(arg) {+ return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null;+}++/**+ * Variables passed to field arguments conform to type+ */+function VariablesInAllowedPositionRule(context) {+ var varDefMap = Object.create(null);+ return {+ OperationDefinition: {+ enter: function enter() {+ varDefMap = Object.create(null);+ },+ leave: function leave(operation) {+ var usages = context.getRecursiveVariableUsages(operation);++ for (var _i2 = 0; _i2 < usages.length; _i2++) {+ var _ref2 = usages[_i2];+ var node = _ref2.node;+ var type = _ref2.type;+ var defaultValue = _ref2.defaultValue;+ var varName = node.name.value;+ var varDef = varDefMap[varName];++ if (varDef && type) {+ // A var type is allowed if it is the same or more strict (e.g. is+ // a subtype of) than the expected type. It can be more strict if+ // the variable type is non-null when the expected type is nullable.+ // If both are list types, the variable item type can be more strict+ // than the expected item type (contravariant).+ var schema = context.getSchema();+ var varType = typeFromAST(schema, varDef.type);++ if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) {+ var varTypeStr = inspect(varType);+ var typeStr = inspect(type);+ context.reportError(new GraphQLError("Variable \"$".concat(varName, "\" of type \"").concat(varTypeStr, "\" used in position expecting type \"").concat(typeStr, "\"."), [varDef, node]));+ }+ }+ }+ }+ },+ VariableDefinition: function VariableDefinition(node) {+ varDefMap[node.variable.name.value] = node;+ }+ };+}+/**+ * Returns true if the variable is allowed in the location it was found,+ * which includes considering if default values exist for either the variable+ * or the location at which it is located.+ */++function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) {+ if (isNonNullType(locationType) && !isNonNullType(varType)) {+ var hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== Kind.NULL;+ var hasLocationDefaultValue = locationDefaultValue !== undefined;++ if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) {+ return false;+ }++ var nullableLocationType = locationType.ofType;+ return isTypeSubTypeOf(schema, varType, nullableLocationType);+ }++ return isTypeSubTypeOf(schema, varType, locationType);+}++function reasonMessage(reason) {+ if (Array.isArray(reason)) {+ return reason.map(function (_ref) {+ var responseName = _ref[0],+ subReason = _ref[1];+ return "subfields \"".concat(responseName, "\" conflict because ") + reasonMessage(subReason);+ }).join(' and ');+ }++ return reason;+}+/**+ * Overlapping fields can be merged+ *+ * A selection set is only valid if all fields (including spreading any+ * fragments) either correspond to distinct response names or can be merged+ * without ambiguity.+ */+++function OverlappingFieldsCanBeMergedRule(context) {+ // A memoization for when two fragments are compared "between" each other for+ // conflicts. Two fragments may be compared many times, so memoizing this can+ // dramatically improve the performance of this validator.+ var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given+ // selection set. Selection sets may be asked for this information multiple+ // times, so this improves the performance of this validator.++ var cachedFieldsAndFragmentNames = new Map();+ return {+ SelectionSet: function SelectionSet(selectionSet) {+ var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet);++ for (var _i2 = 0; _i2 < conflicts.length; _i2++) {+ var _ref3 = conflicts[_i2];+ var _ref2$ = _ref3[0];+ var responseName = _ref2$[0];+ var reason = _ref2$[1];+ var fields1 = _ref3[1];+ var fields2 = _ref3[2];+ var reasonMsg = reasonMessage(reason);+ context.reportError(new GraphQLError("Fields \"".concat(responseName, "\" conflict because ").concat(reasonMsg, ". Use different aliases on the fields to fetch both if this was intentional."), fields1.concat(fields2)));+ }+ }+ };+}++/**+ * Algorithm:+ *+ * Conflicts occur when two fields exist in a query which will produce the same+ * response name, but represent differing values, thus creating a conflict.+ * The algorithm below finds all conflicts via making a series of comparisons+ * between fields. In order to compare as few fields as possible, this makes+ * a series of comparisons "within" sets of fields and "between" sets of fields.+ *+ * Given any selection set, a collection produces both a set of fields by+ * also including all inline fragments, as well as a list of fragments+ * referenced by fragment spreads.+ *+ * A) Each selection set represented in the document first compares "within" its+ * collected set of fields, finding any conflicts between every pair of+ * overlapping fields.+ * Note: This is the *only time* that a the fields "within" a set are compared+ * to each other. After this only fields "between" sets are compared.+ *+ * B) Also, if any fragment is referenced in a selection set, then a+ * comparison is made "between" the original set of fields and the+ * referenced fragment.+ *+ * C) Also, if multiple fragments are referenced, then comparisons+ * are made "between" each referenced fragment.+ *+ * D) When comparing "between" a set of fields and a referenced fragment, first+ * a comparison is made between each field in the original set of fields and+ * each field in the the referenced set of fields.+ *+ * E) Also, if any fragment is referenced in the referenced selection set,+ * then a comparison is made "between" the original set of fields and the+ * referenced fragment (recursively referring to step D).+ *+ * F) When comparing "between" two fragments, first a comparison is made between+ * each field in the first referenced set of fields and each field in the the+ * second referenced set of fields.+ *+ * G) Also, any fragments referenced by the first must be compared to the+ * second, and any fragments referenced by the second must be compared to the+ * first (recursively referring to step F).+ *+ * H) When comparing two fields, if both have selection sets, then a comparison+ * is made "between" both selection sets, first comparing the set of fields in+ * the first selection set with the set of fields in the second.+ *+ * I) Also, if any fragment is referenced in either selection set, then a+ * comparison is made "between" the other set of fields and the+ * referenced fragment.+ *+ * J) Also, if two fragments are referenced in both selection sets, then a+ * comparison is made "between" the two fragments.+ *+ */+// Find all conflicts found "within" a selection set, including those found+// via spreading in fragments. Called when visiting each SelectionSet in the+// GraphQL Document.+function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) {+ var conflicts = [];++ var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet),+ fieldMap = _getFieldsAndFragment[0],+ fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set.+ // Note: this is the *only place* `collectConflictsWithin` is called.+++ collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap);++ if (fragmentNames.length !== 0) {+ // (B) Then collect conflicts between these fields and those represented by+ // each spread fragment name found.+ for (var i = 0; i < fragmentNames.length; i++) {+ collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this+ // selection set to collect conflicts between fragments spread together.+ // This compares each item in the list of fragment names to every other+ // item in that same list (except for itself).++ for (var j = i + 1; j < fragmentNames.length; j++) {+ collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]);+ }+ }+ }++ return conflicts;+} // Collect all conflicts found between a set of fields and a fragment reference+// including via spreading in any nested fragments.+++function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) {+ var fragment = context.getFragment(fragmentName);++ if (!fragment) {+ return;+ }++ var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment),+ fieldMap2 = _getReferencedFieldsA[0],+ fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself.+++ if (fieldMap === fieldMap2) {+ return;+ } // (D) First collect any conflicts between the provided collection of fields+ // and the collection of fields represented by the given fragment.+++ collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields+ // and any fragment names found in the given fragment.++ for (var i = 0; i < fragmentNames2.length; i++) {+ collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]);+ }+} // Collect all conflicts found between two fragments, including via spreading in+// any nested fragments.+++function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) {+ // No need to compare a fragment to itself.+ if (fragmentName1 === fragmentName2) {+ return;+ } // Memoize so two fragments are not compared for conflicts more than once.+++ if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) {+ return;+ }++ comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);+ var fragment1 = context.getFragment(fragmentName1);+ var fragment2 = context.getFragment(fragmentName2);++ if (!fragment1 || !fragment2) {+ return;+ }++ var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1),+ fieldMap1 = _getReferencedFieldsA2[0],+ fragmentNames1 = _getReferencedFieldsA2[1];++ var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2),+ fieldMap2 = _getReferencedFieldsA3[0],+ fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields+ // (not including any nested fragments).+++ collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested+ // fragments spread in the second fragment.++ for (var j = 0; j < fragmentNames2.length; j++) {+ collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]);+ } // (G) Then collect conflicts between the second fragment and any nested+ // fragments spread in the first fragment.+++ for (var i = 0; i < fragmentNames1.length; i++) {+ collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2);+ }+} // Find all conflicts found between two selection sets, including those found+// via spreading in fragments. Called when determining if conflicts exist+// between the sub-fields of two overlapping fields.+++function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) {+ var conflicts = [];++ var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1),+ fieldMap1 = _getFieldsAndFragment2[0],+ fragmentNames1 = _getFieldsAndFragment2[1];++ var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2),+ fieldMap2 = _getFieldsAndFragment3[0],+ fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field.+++ collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and+ // those referenced by each fragment name associated with the second.++ if (fragmentNames2.length !== 0) {+ for (var j = 0; j < fragmentNames2.length; j++) {+ collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]);+ }+ } // (I) Then collect conflicts between the second collection of fields and+ // those referenced by each fragment name associated with the first.+++ if (fragmentNames1.length !== 0) {+ for (var i = 0; i < fragmentNames1.length; i++) {+ collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]);+ }+ } // (J) Also collect conflicts between any fragment names by the first and+ // fragment names by the second. This compares each item in the first set of+ // names to each item in the second set of names.+++ for (var _i3 = 0; _i3 < fragmentNames1.length; _i3++) {+ for (var _j = 0; _j < fragmentNames2.length; _j++) {+ collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i3], fragmentNames2[_j]);+ }+ }++ return conflicts;+} // Collect all Conflicts "within" one collection of fields.+++function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) {+ // A field map is a keyed collection, where each key represents a response+ // name and the value at that key is a list of all fields which provide that+ // response name. For every response name, if there are multiple fields, they+ // must be compared to find a potential conflict.+ for (var _i5 = 0, _objectEntries2 = objectEntries(fieldMap); _i5 < _objectEntries2.length; _i5++) {+ var _ref5 = _objectEntries2[_i5];+ var responseName = _ref5[0];+ var fields = _ref5[1];++ // This compares every field in the list to every other field in this list+ // (except to itself). If the list only has one item, nothing needs to+ // be compared.+ if (fields.length > 1) {+ for (var i = 0; i < fields.length; i++) {+ for (var j = i + 1; j < fields.length; j++) {+ var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive+ responseName, fields[i], fields[j]);++ if (conflict) {+ conflicts.push(conflict);+ }+ }+ }+ }+ }+} // Collect all Conflicts between two collections of fields. This is similar to,+// but different from the `collectConflictsWithin` function above. This check+// assumes that `collectConflictsWithin` has already been called on each+// provided collection of fields. This is true because this validator traverses+// each individual selection set.+++function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) {+ // A field map is a keyed collection, where each key represents a response+ // name and the value at that key is a list of all fields which provide that+ // response name. For any response name which appears in both provided field+ // maps, each field from the first field map must be compared to every field+ // in the second field map to find potential conflicts.+ for (var _i7 = 0, _Object$keys2 = Object.keys(fieldMap1); _i7 < _Object$keys2.length; _i7++) {+ var responseName = _Object$keys2[_i7];+ var fields2 = fieldMap2[responseName];++ if (fields2) {+ var fields1 = fieldMap1[responseName];++ for (var i = 0; i < fields1.length; i++) {+ for (var j = 0; j < fields2.length; j++) {+ var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]);++ if (conflict) {+ conflicts.push(conflict);+ }+ }+ }+ }+ }+} // Determines if there is a conflict between two particular fields, including+// comparing their sub-fields.+++function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) {+ var parentType1 = field1[0],+ node1 = field1[1],+ def1 = field1[2];+ var parentType2 = field2[0],+ node2 = field2[1],+ def2 = field2[2]; // If it is known that two fields could not possibly apply at the same+ // time, due to the parent types, then it is safe to permit them to diverge+ // in aliased field or arguments used as they will not present any ambiguity+ // by differing.+ // It is known that two parent types could never overlap if they are+ // different Object types. Interface or Union types might overlap - if not+ // in the current state of the schema, then perhaps in some future version,+ // thus may not safely diverge.++ var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && isObjectType(parentType1) && isObjectType(parentType2);++ if (!areMutuallyExclusive) {+ var _node1$arguments, _node2$arguments;++ // Two aliases must refer to the same field.+ var name1 = node1.name.value;+ var name2 = node2.name.value;++ if (name1 !== name2) {+ return [[responseName, "\"".concat(name1, "\" and \"").concat(name2, "\" are different fields")], [node1], [node2]];+ } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+++ var args1 = (_node1$arguments = node1.arguments) !== null && _node1$arguments !== void 0 ? _node1$arguments : []; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')++ var args2 = (_node2$arguments = node2.arguments) !== null && _node2$arguments !== void 0 ? _node2$arguments : []; // Two field calls must have the same arguments.++ if (!sameArguments(args1, args2)) {+ return [[responseName, 'they have differing arguments'], [node1], [node2]];+ }+ } // The return type for each field.+++ var type1 = def1 === null || def1 === void 0 ? void 0 : def1.type;+ var type2 = def2 === null || def2 === void 0 ? void 0 : def2.type;++ if (type1 && type2 && doTypesConflict(type1, type2)) {+ return [[responseName, "they return conflicting types \"".concat(inspect(type1), "\" and \"").concat(inspect(type2), "\"")], [node1], [node2]];+ } // Collect and compare sub-fields. Use the same "visited fragment names" list+ // for both collections so fields in a fragment reference are never+ // compared to themselves.+++ var selectionSet1 = node1.selectionSet;+ var selectionSet2 = node2.selectionSet;++ if (selectionSet1 && selectionSet2) {+ var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, getNamedType(type1), selectionSet1, getNamedType(type2), selectionSet2);+ return subfieldConflicts(conflicts, responseName, node1, node2);+ }+}++function sameArguments(arguments1, arguments2) {+ if (arguments1.length !== arguments2.length) {+ return false;+ }++ return arguments1.every(function (argument1) {+ var argument2 = find(arguments2, function (argument) {+ return argument.name.value === argument1.name.value;+ });++ if (!argument2) {+ return false;+ }++ return sameValue(argument1.value, argument2.value);+ });+}++function sameValue(value1, value2) {+ return print(value1) === print(value2);+} // Two types conflict if both types could not apply to a value simultaneously.+// Composite types are ignored as their individual field types will be compared+// later recursively. However List and Non-Null types must match.+++function doTypesConflict(type1, type2) {+ if (isListType(type1)) {+ return isListType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;+ }++ if (isListType(type2)) {+ return true;+ }++ if (isNonNullType(type1)) {+ return isNonNullType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;+ }++ if (isNonNullType(type2)) {+ return true;+ }++ if (isLeafType(type1) || isLeafType(type2)) {+ return type1 !== type2;+ }++ return false;+} // Given a selection set, return the collection of fields (a mapping of response+// name to field nodes and definitions) as well as a list of fragment names+// referenced via fragment spreads.+++function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) {+ var cached = cachedFieldsAndFragmentNames.get(selectionSet);++ if (!cached) {+ var nodeAndDefs = Object.create(null);+ var fragmentNames = Object.create(null);++ _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames);++ cached = [nodeAndDefs, Object.keys(fragmentNames)];+ cachedFieldsAndFragmentNames.set(selectionSet, cached);+ }++ return cached;+} // Given a reference to a fragment, return the represented collection of fields+// as well as a list of nested fragment names referenced via fragment spreads.+++function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) {+ // Short-circuit building a type from the node if possible.+ var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);++ if (cached) {+ return cached;+ }++ var fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition);+ return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet);+}++function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) {+ for (var _i9 = 0, _selectionSet$selecti2 = selectionSet.selections; _i9 < _selectionSet$selecti2.length; _i9++) {+ var selection = _selectionSet$selecti2[_i9];++ switch (selection.kind) {+ case Kind.FIELD:+ {+ var fieldName = selection.name.value;+ var fieldDef = void 0;++ if (isObjectType(parentType) || isInterfaceType(parentType)) {+ fieldDef = parentType.getFields()[fieldName];+ }++ var responseName = selection.alias ? selection.alias.value : fieldName;++ if (!nodeAndDefs[responseName]) {+ nodeAndDefs[responseName] = [];+ }++ nodeAndDefs[responseName].push([parentType, selection, fieldDef]);+ break;+ }++ case Kind.FRAGMENT_SPREAD:+ fragmentNames[selection.name.value] = true;+ break;++ case Kind.INLINE_FRAGMENT:+ {+ var typeCondition = selection.typeCondition;+ var inlineFragmentType = typeCondition ? typeFromAST(context.getSchema(), typeCondition) : parentType;++ _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames);++ break;+ }+ }+ }+} // Given a series of Conflicts which occurred between two sub-fields, generate+// a single Conflict.+++function subfieldConflicts(conflicts, responseName, node1, node2) {+ if (conflicts.length > 0) {+ return [[responseName, conflicts.map(function (_ref6) {+ var reason = _ref6[0];+ return reason;+ })], conflicts.reduce(function (allFields, _ref7) {+ var fields1 = _ref7[1];+ return allFields.concat(fields1);+ }, [node1]), conflicts.reduce(function (allFields, _ref8) {+ var fields2 = _ref8[2];+ return allFields.concat(fields2);+ }, [node2])];+ }+}+/**+ * A way to keep track of pairs of things when the ordering of the pair does+ * not matter. We do this by maintaining a sort of double adjacency sets.+ */+++var PairSet = /*#__PURE__*/function () {+ function PairSet() {+ this._data = Object.create(null);+ }++ var _proto = PairSet.prototype;++ _proto.has = function has(a, b, areMutuallyExclusive) {+ var first = this._data[a];+ var result = first && first[b];++ if (result === undefined) {+ return false;+ } // areMutuallyExclusive being false is a superset of being true,+ // hence if we want to know if this PairSet "has" these two with no+ // exclusivity, we have to ensure it was added as such.+++ if (areMutuallyExclusive === false) {+ return result === false;+ }++ return true;+ };++ _proto.add = function add(a, b, areMutuallyExclusive) {+ _pairSetAdd(this._data, a, b, areMutuallyExclusive);++ _pairSetAdd(this._data, b, a, areMutuallyExclusive);+ };++ return PairSet;+}();++function _pairSetAdd(data, a, b, areMutuallyExclusive) {+ var map = data[a];++ if (!map) {+ map = Object.create(null);+ data[a] = map;+ }++ map[b] = areMutuallyExclusive;+}++/**+ * Unique input field names+ *+ * A GraphQL input object value is only valid if all supplied fields are+ * uniquely named.+ */+function UniqueInputFieldNamesRule(context) {+ var knownNameStack = [];+ var knownNames = Object.create(null);+ return {+ ObjectValue: {+ enter: function enter() {+ knownNameStack.push(knownNames);+ knownNames = Object.create(null);+ },+ leave: function leave() {+ knownNames = knownNameStack.pop();+ }+ },+ ObjectField: function ObjectField(node) {+ var fieldName = node.name.value;++ if (knownNames[fieldName]) {+ context.reportError(new GraphQLError("There can be only one input field named \"".concat(fieldName, "\"."), [knownNames[fieldName], node.name]));+ } else {+ knownNames[fieldName] = node.name;+ }+ }+ };+}++/**+ * Lone Schema definition+ *+ * A GraphQL document is only valid if it contains only one schema definition.+ */+function LoneSchemaDefinitionRule(context) {+ var _ref, _ref2, _oldSchema$astNode;++ var oldSchema = context.getSchema();+ var alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType();+ var schemaDefinitionsCount = 0;+ return {+ SchemaDefinition: function SchemaDefinition(node) {+ if (alreadyDefined) {+ context.reportError(new GraphQLError('Cannot define a new schema within a schema extension.', node));+ return;+ }++ if (schemaDefinitionsCount > 0) {+ context.reportError(new GraphQLError('Must provide only one schema definition.', node));+ }++ ++schemaDefinitionsCount;+ }+ };+}++/**+ * Unique operation types+ *+ * A GraphQL document is only valid if it has only one type per operation.+ */+function UniqueOperationTypesRule(context) {+ var schema = context.getSchema();+ var definedOperationTypes = Object.create(null);+ var existingOperationTypes = schema ? {+ query: schema.getQueryType(),+ mutation: schema.getMutationType(),+ subscription: schema.getSubscriptionType()+ } : {};+ return {+ SchemaDefinition: checkOperationTypes,+ SchemaExtension: checkOperationTypes+ };++ function checkOperationTypes(node) {+ var _node$operationTypes;++ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : [];++ for (var _i2 = 0; _i2 < operationTypesNodes.length; _i2++) {+ var operationType = operationTypesNodes[_i2];+ var operation = operationType.operation;+ var alreadyDefinedOperationType = definedOperationTypes[operation];++ if (existingOperationTypes[operation]) {+ context.reportError(new GraphQLError("Type for ".concat(operation, " already defined in the schema. It cannot be redefined."), operationType));+ } else if (alreadyDefinedOperationType) {+ context.reportError(new GraphQLError("There can be only one ".concat(operation, " type in schema."), [alreadyDefinedOperationType, operationType]));+ } else {+ definedOperationTypes[operation] = operationType;+ }+ }++ return false;+ }+}++/**+ * Unique type names+ *+ * A GraphQL document is only valid if all defined types have unique names.+ */+function UniqueTypeNamesRule(context) {+ var knownTypeNames = Object.create(null);+ var schema = context.getSchema();+ return {+ ScalarTypeDefinition: checkTypeName,+ ObjectTypeDefinition: checkTypeName,+ InterfaceTypeDefinition: checkTypeName,+ UnionTypeDefinition: checkTypeName,+ EnumTypeDefinition: checkTypeName,+ InputObjectTypeDefinition: checkTypeName+ };++ function checkTypeName(node) {+ var typeName = node.name.value;++ if (schema === null || schema === void 0 ? void 0 : schema.getType(typeName)) {+ context.reportError(new GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also be defined in this type definition."), node.name));+ return;+ }++ if (knownTypeNames[typeName]) {+ context.reportError(new GraphQLError("There can be only one type named \"".concat(typeName, "\"."), [knownTypeNames[typeName], node.name]));+ } else {+ knownTypeNames[typeName] = node.name;+ }++ return false;+ }+}++/**+ * Unique enum value names+ *+ * A GraphQL enum type is only valid if all its values are uniquely named.+ */+function UniqueEnumValueNamesRule(context) {+ var schema = context.getSchema();+ var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);+ var knownValueNames = Object.create(null);+ return {+ EnumTypeDefinition: checkValueUniqueness,+ EnumTypeExtension: checkValueUniqueness+ };++ function checkValueUniqueness(node) {+ var _node$values;++ var typeName = node.name.value;++ if (!knownValueNames[typeName]) {+ knownValueNames[typeName] = Object.create(null);+ } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+++ var valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : [];+ var valueNames = knownValueNames[typeName];++ for (var _i2 = 0; _i2 < valueNodes.length; _i2++) {+ var valueDef = valueNodes[_i2];+ var valueName = valueDef.name.value;+ var existingType = existingTypeMap[typeName];++ if (isEnumType(existingType) && existingType.getValue(valueName)) {+ context.reportError(new GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. It cannot also be defined in this type extension."), valueDef.name));+ } else if (valueNames[valueName]) {+ context.reportError(new GraphQLError("Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once."), [valueNames[valueName], valueDef.name]));+ } else {+ valueNames[valueName] = valueDef.name;+ }+ }++ return false;+ }+}++/**+ * Unique field definition names+ *+ * A GraphQL complex type is only valid if all its fields are uniquely named.+ */+function UniqueFieldDefinitionNamesRule(context) {+ var schema = context.getSchema();+ var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);+ var knownFieldNames = Object.create(null);+ return {+ InputObjectTypeDefinition: checkFieldUniqueness,+ InputObjectTypeExtension: checkFieldUniqueness,+ InterfaceTypeDefinition: checkFieldUniqueness,+ InterfaceTypeExtension: checkFieldUniqueness,+ ObjectTypeDefinition: checkFieldUniqueness,+ ObjectTypeExtension: checkFieldUniqueness+ };++ function checkFieldUniqueness(node) {+ var _node$fields;++ var typeName = node.name.value;++ if (!knownFieldNames[typeName]) {+ knownFieldNames[typeName] = Object.create(null);+ } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+++ var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];+ var fieldNames = knownFieldNames[typeName];++ for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) {+ var fieldDef = fieldNodes[_i2];+ var fieldName = fieldDef.name.value;++ if (hasField(existingTypeMap[typeName], fieldName)) {+ context.reportError(new GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. It cannot also be defined in this type extension."), fieldDef.name));+ } else if (fieldNames[fieldName]) {+ context.reportError(new GraphQLError("Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once."), [fieldNames[fieldName], fieldDef.name]));+ } else {+ fieldNames[fieldName] = fieldDef.name;+ }+ }++ return false;+ }+}++function hasField(type, fieldName) {+ if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {+ return type.getFields()[fieldName];+ }++ return false;+}++/**+ * Unique directive names+ *+ * A GraphQL document is only valid if all defined directives have unique names.+ */+function UniqueDirectiveNamesRule(context) {+ var knownDirectiveNames = Object.create(null);+ var schema = context.getSchema();+ return {+ DirectiveDefinition: function DirectiveDefinition(node) {+ var directiveName = node.name.value;++ if (schema === null || schema === void 0 ? void 0 : schema.getDirective(directiveName)) {+ context.reportError(new GraphQLError("Directive \"@".concat(directiveName, "\" already exists in the schema. It cannot be redefined."), node.name));+ return;+ }++ if (knownDirectiveNames[directiveName]) {+ context.reportError(new GraphQLError("There can be only one directive named \"@".concat(directiveName, "\"."), [knownDirectiveNames[directiveName], node.name]));+ } else {+ knownDirectiveNames[directiveName] = node.name;+ }++ return false;+ }+ };+}++var _defKindToExtKind;++function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }++/**+ * Possible type extension+ *+ * A type extension is only valid if the type is defined and has the same kind.+ */+function PossibleTypeExtensionsRule(context) {+ var schema = context.getSchema();+ var definedTypes = Object.create(null);++ for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {+ var def = _context$getDocument$2[_i2];++ if (isTypeDefinitionNode(def)) {+ definedTypes[def.name.value] = def;+ }+ }++ return {+ ScalarTypeExtension: checkExtension,+ ObjectTypeExtension: checkExtension,+ InterfaceTypeExtension: checkExtension,+ UnionTypeExtension: checkExtension,+ EnumTypeExtension: checkExtension,+ InputObjectTypeExtension: checkExtension+ };++ function checkExtension(node) {+ var typeName = node.name.value;+ var defNode = definedTypes[typeName];+ var existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName);+ var expectedKind;++ if (defNode) {+ expectedKind = defKindToExtKind[defNode.kind];+ } else if (existingType) {+ expectedKind = typeToExtKind(existingType);+ }++ if (expectedKind) {+ if (expectedKind !== node.kind) {+ var kindStr = extensionKindToTypeName(node.kind);+ context.reportError(new GraphQLError("Cannot extend non-".concat(kindStr, " type \"").concat(typeName, "\"."), defNode ? [defNode, node] : node));+ }+ } else {+ var allTypeNames = Object.keys(definedTypes);++ if (schema) {+ allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap()));+ }++ var suggestedTypes = suggestionList(typeName, allTypeNames);+ context.reportError(new GraphQLError("Cannot extend type \"".concat(typeName, "\" because it is not defined.") + didYouMean(suggestedTypes), node.name));+ }+ }+}+var defKindToExtKind = (_defKindToExtKind = {}, _defineProperty$2(_defKindToExtKind, Kind.SCALAR_TYPE_DEFINITION, Kind.SCALAR_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.OBJECT_TYPE_DEFINITION, Kind.OBJECT_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.INTERFACE_TYPE_DEFINITION, Kind.INTERFACE_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.UNION_TYPE_DEFINITION, Kind.UNION_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.ENUM_TYPE_DEFINITION, Kind.ENUM_TYPE_EXTENSION), _defineProperty$2(_defKindToExtKind, Kind.INPUT_OBJECT_TYPE_DEFINITION, Kind.INPUT_OBJECT_TYPE_EXTENSION), _defKindToExtKind);++function typeToExtKind(type) {+ if (isScalarType(type)) {+ return Kind.SCALAR_TYPE_EXTENSION;+ }++ if (isObjectType(type)) {+ return Kind.OBJECT_TYPE_EXTENSION;+ }++ if (isInterfaceType(type)) {+ return Kind.INTERFACE_TYPE_EXTENSION;+ }++ if (isUnionType(type)) {+ return Kind.UNION_TYPE_EXTENSION;+ }++ if (isEnumType(type)) {+ return Kind.ENUM_TYPE_EXTENSION;+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isInputObjectType(type)) {+ return Kind.INPUT_OBJECT_TYPE_EXTENSION;+ } // istanbul ignore next (Not reachable. All possible types have been considered)+++ invariant(0, 'Unexpected type: ' + inspect(type));+}++function extensionKindToTypeName(kind) {+ switch (kind) {+ case Kind.SCALAR_TYPE_EXTENSION:+ return 'scalar';++ case Kind.OBJECT_TYPE_EXTENSION:+ return 'object';++ case Kind.INTERFACE_TYPE_EXTENSION:+ return 'interface';++ case Kind.UNION_TYPE_EXTENSION:+ return 'union';++ case Kind.ENUM_TYPE_EXTENSION:+ return 'enum';++ case Kind.INPUT_OBJECT_TYPE_EXTENSION:+ return 'input object';+ } // istanbul ignore next (Not reachable. All possible types have been considered)+++ invariant(0, 'Unexpected kind: ' + inspect(kind));+}++// Spec Section: "Executable Definitions"+/**+ * This set includes all validation rules defined by the GraphQL spec.+ *+ * The order of the rules in this list has been adjusted to lead to the+ * most clear output when encountering multiple validation errors.+ */++var specifiedRules = Object.freeze([ExecutableDefinitionsRule, UniqueOperationNamesRule, LoneAnonymousOperationRule, SingleFieldSubscriptionsRule, KnownTypeNamesRule, FragmentsOnCompositeTypesRule, VariablesAreInputTypesRule, ScalarLeafsRule, FieldsOnCorrectTypeRule, UniqueFragmentNamesRule, KnownFragmentNamesRule, NoUnusedFragmentsRule, PossibleFragmentSpreadsRule, NoFragmentCyclesRule, UniqueVariableNamesRule, NoUndefinedVariablesRule, NoUnusedVariablesRule, KnownDirectivesRule, UniqueDirectivesPerLocationRule, KnownArgumentNamesRule, UniqueArgumentNamesRule, ValuesOfCorrectTypeRule, ProvidedRequiredArgumentsRule, VariablesInAllowedPositionRule, OverlappingFieldsCanBeMergedRule, UniqueInputFieldNamesRule]);+/**+ * @internal+ */++var specifiedSDLRules = Object.freeze([LoneSchemaDefinitionRule, UniqueOperationTypesRule, UniqueTypeNamesRule, UniqueEnumValueNamesRule, UniqueFieldDefinitionNamesRule, UniqueDirectiveNamesRule, KnownTypeNamesRule, KnownDirectivesRule, UniqueDirectivesPerLocationRule, PossibleTypeExtensionsRule, KnownArgumentNamesOnDirectivesRule, UniqueArgumentNamesRule, UniqueInputFieldNamesRule, ProvidedRequiredArgumentsOnDirectivesRule]);++function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }++/**+ * An instance of this class is passed as the "this" context to all validators,+ * allowing access to commonly useful contextual information from within a+ * validation rule.+ */+var ASTValidationContext = /*#__PURE__*/function () {+ function ASTValidationContext(ast, onError) {+ this._ast = ast;+ this._fragments = undefined;+ this._fragmentSpreads = new Map();+ this._recursivelyReferencedFragments = new Map();+ this._onError = onError;+ }++ var _proto = ASTValidationContext.prototype;++ _proto.reportError = function reportError(error) {+ this._onError(error);+ };++ _proto.getDocument = function getDocument() {+ return this._ast;+ };++ _proto.getFragment = function getFragment(name) {+ var fragments = this._fragments;++ if (!fragments) {+ this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) {+ if (statement.kind === Kind.FRAGMENT_DEFINITION) {+ frags[statement.name.value] = statement;+ }++ return frags;+ }, Object.create(null));+ }++ return fragments[name];+ };++ _proto.getFragmentSpreads = function getFragmentSpreads(node) {+ var spreads = this._fragmentSpreads.get(node);++ if (!spreads) {+ spreads = [];+ var setsToVisit = [node];++ while (setsToVisit.length !== 0) {+ var set = setsToVisit.pop();++ for (var _i2 = 0, _set$selections2 = set.selections; _i2 < _set$selections2.length; _i2++) {+ var selection = _set$selections2[_i2];++ if (selection.kind === Kind.FRAGMENT_SPREAD) {+ spreads.push(selection);+ } else if (selection.selectionSet) {+ setsToVisit.push(selection.selectionSet);+ }+ }+ }++ this._fragmentSpreads.set(node, spreads);+ }++ return spreads;+ };++ _proto.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) {+ var fragments = this._recursivelyReferencedFragments.get(operation);++ if (!fragments) {+ fragments = [];+ var collectedNames = Object.create(null);+ var nodesToVisit = [operation.selectionSet];++ while (nodesToVisit.length !== 0) {+ var node = nodesToVisit.pop();++ for (var _i4 = 0, _this$getFragmentSpre2 = this.getFragmentSpreads(node); _i4 < _this$getFragmentSpre2.length; _i4++) {+ var spread = _this$getFragmentSpre2[_i4];+ var fragName = spread.name.value;++ if (collectedNames[fragName] !== true) {+ collectedNames[fragName] = true;+ var fragment = this.getFragment(fragName);++ if (fragment) {+ fragments.push(fragment);+ nodesToVisit.push(fragment.selectionSet);+ }+ }+ }+ }++ this._recursivelyReferencedFragments.set(operation, fragments);+ }++ return fragments;+ };++ return ASTValidationContext;+}();+var SDLValidationContext = /*#__PURE__*/function (_ASTValidationContext) {+ _inheritsLoose(SDLValidationContext, _ASTValidationContext);++ function SDLValidationContext(ast, schema, onError) {+ var _this;++ _this = _ASTValidationContext.call(this, ast, onError) || this;+ _this._schema = schema;+ return _this;+ }++ var _proto2 = SDLValidationContext.prototype;++ _proto2.getSchema = function getSchema() {+ return this._schema;+ };++ return SDLValidationContext;+}(ASTValidationContext);+var ValidationContext = /*#__PURE__*/function (_ASTValidationContext2) {+ _inheritsLoose(ValidationContext, _ASTValidationContext2);++ function ValidationContext(schema, ast, typeInfo, onError) {+ var _this2;++ _this2 = _ASTValidationContext2.call(this, ast, onError) || this;+ _this2._schema = schema;+ _this2._typeInfo = typeInfo;+ _this2._variableUsages = new Map();+ _this2._recursiveVariableUsages = new Map();+ return _this2;+ }++ var _proto3 = ValidationContext.prototype;++ _proto3.getSchema = function getSchema() {+ return this._schema;+ };++ _proto3.getVariableUsages = function getVariableUsages(node) {+ var usages = this._variableUsages.get(node);++ if (!usages) {+ var newUsages = [];+ var typeInfo = new TypeInfo(this._schema);+ visit(node, visitWithTypeInfo(typeInfo, {+ VariableDefinition: function VariableDefinition() {+ return false;+ },+ Variable: function Variable(variable) {+ newUsages.push({+ node: variable,+ type: typeInfo.getInputType(),+ defaultValue: typeInfo.getDefaultValue()+ });+ }+ }));+ usages = newUsages;++ this._variableUsages.set(node, usages);+ }++ return usages;+ };++ _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) {+ var usages = this._recursiveVariableUsages.get(operation);++ if (!usages) {+ usages = this.getVariableUsages(operation);++ for (var _i6 = 0, _this$getRecursivelyR2 = this.getRecursivelyReferencedFragments(operation); _i6 < _this$getRecursivelyR2.length; _i6++) {+ var frag = _this$getRecursivelyR2[_i6];+ usages = usages.concat(this.getVariableUsages(frag));+ }++ this._recursiveVariableUsages.set(operation, usages);+ }++ return usages;+ };++ _proto3.getType = function getType() {+ return this._typeInfo.getType();+ };++ _proto3.getParentType = function getParentType() {+ return this._typeInfo.getParentType();+ };++ _proto3.getInputType = function getInputType() {+ return this._typeInfo.getInputType();+ };++ _proto3.getParentInputType = function getParentInputType() {+ return this._typeInfo.getParentInputType();+ };++ _proto3.getFieldDef = function getFieldDef() {+ return this._typeInfo.getFieldDef();+ };++ _proto3.getDirective = function getDirective() {+ return this._typeInfo.getDirective();+ };++ _proto3.getArgument = function getArgument() {+ return this._typeInfo.getArgument();+ };++ _proto3.getEnumValue = function getEnumValue() {+ return this._typeInfo.getEnumValue();+ };++ return ValidationContext;+}(ASTValidationContext);++/**+ * Implements the "Validation" section of the spec.+ *+ * Validation runs synchronously, returning an array of encountered errors, or+ * an empty array if no errors were encountered and the document is valid.+ *+ * A list of specific validation rules may be provided. If not provided, the+ * default list of rules defined by the GraphQL specification will be used.+ *+ * Each validation rules is a function which returns a visitor+ * (see the language/visitor API). Visitor methods are expected to return+ * GraphQLErrors, or Arrays of GraphQLErrors when invalid.+ *+ * Optionally a custom TypeInfo instance may be provided. If not provided, one+ * will be created from the provided schema.+ */++function validate(schema, documentAST) {+ var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedRules;+ var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new TypeInfo(schema);+ var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {+ maxErrors: undefined+ };+ documentAST || devAssert(0, 'Must provide document.'); // If the schema used for validation is invalid, throw an error.++ assertValidSchema(schema);+ var abortObj = Object.freeze({});+ var errors = [];+ var context = new ValidationContext(schema, documentAST, typeInfo, function (error) {+ if (options.maxErrors != null && errors.length >= options.maxErrors) {+ errors.push(new GraphQLError('Too many validation errors, error limit reached. Validation aborted.'));+ throw abortObj;+ }++ errors.push(error);+ }); // This uses a specialized visitor which runs multiple visitors in parallel,+ // while maintaining the visitor skip and break API.++ var visitor = visitInParallel(rules.map(function (rule) {+ return rule(context);+ })); // Visit the whole document with each instance of all provided rules.++ try {+ visit(documentAST, visitWithTypeInfo(typeInfo, visitor));+ } catch (e) {+ if (e !== abortObj) {+ throw e;+ }+ }++ return errors;+}+/**+ * @internal+ */++function validateSDL(documentAST, schemaToExtend) {+ var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedSDLRules;+ var errors = [];+ var context = new SDLValidationContext(documentAST, schemaToExtend, function (error) {+ errors.push(error);+ });+ var visitors = rules.map(function (rule) {+ return rule(context);+ });+ visit(documentAST, visitInParallel(visitors));+ return errors;+}+/**+ * Utility function which asserts a SDL document is valid by throwing an error+ * if it is invalid.+ *+ * @internal+ */++function assertValidSDL(documentAST) {+ var errors = validateSDL(documentAST);++ if (errors.length !== 0) {+ throw new Error(errors.map(function (error) {+ return error.message;+ }).join('\n\n'));+ }+}+/**+ * Utility function which asserts a SDL document is valid by throwing an error+ * if it is invalid.+ *+ * @internal+ */++function assertValidSDLExtension(documentAST, schema) {+ var errors = validateSDL(documentAST, schema);++ if (errors.length !== 0) {+ throw new Error(errors.map(function (error) {+ return error.message;+ }).join('\n\n'));+ }+}++/**+ * Memoizes the provided three-argument function.+ */+function memoize3(fn) {+ var cache0;++ function memoized(a1, a2, a3) {+ if (!cache0) {+ cache0 = new WeakMap();+ }++ var cache1 = cache0.get(a1);+ var cache2;++ if (cache1) {+ cache2 = cache1.get(a2);++ if (cache2) {+ var cachedValue = cache2.get(a3);++ if (cachedValue !== undefined) {+ return cachedValue;+ }+ }+ } else {+ cache1 = new WeakMap();+ cache0.set(a1, cache1);+ }++ if (!cache2) {+ cache2 = new WeakMap();+ cache1.set(a2, cache2);+ }++ var newValue = fn(a1, a2, a3);+ cache2.set(a3, newValue);+ return newValue;+ }++ return memoized;+}++/**+ * Similar to Array.prototype.reduce(), however the reducing callback may return+ * a Promise, in which case reduction will continue after each promise resolves.+ *+ * If the callback does not return a Promise, then this function will also not+ * return a Promise.+ */++function promiseReduce(values, callback, initialValue) {+ return values.reduce(function (previous, value) {+ return isPromise(previous) ? previous.then(function (resolved) {+ return callback(resolved, value);+ }) : callback(previous, value);+ }, initialValue);+}++/**+ * This function transforms a JS object `ObjMap<Promise<T>>` into+ * a `Promise<ObjMap<T>>`+ *+ * This is akin to bluebird's `Promise.props`, but implemented only using+ * `Promise.all` so it will work with any implementation of ES6 promises.+ */+function promiseForObject(object) {+ var keys = Object.keys(object);+ var valuesAndPromises = keys.map(function (name) {+ return object[name];+ });+ return Promise.all(valuesAndPromises).then(function (values) {+ return values.reduce(function (resolvedObject, value, i) {+ resolvedObject[keys[i]] = value;+ return resolvedObject;+ }, Object.create(null));+ });+}++/**+ * Given a Path and a key, return a new Path containing the new key.+ */+function addPath(prev, key, typename) {+ return {+ prev: prev,+ key: key,+ typename: typename+ };+}+/**+ * Given a Path, return an Array of the path keys.+ */++function pathToArray(path) {+ var flattened = [];+ var curr = path;++ while (curr) {+ flattened.push(curr.key);+ curr = curr.prev;+ }++ return flattened.reverse();+}++/**+ * Extracts the root type of the operation from the schema.+ */+function getOperationRootType(schema, operation) {+ if (operation.operation === 'query') {+ var queryType = schema.getQueryType();++ if (!queryType) {+ throw new GraphQLError('Schema does not define the required query root type.', operation);+ }++ return queryType;+ }++ if (operation.operation === 'mutation') {+ var mutationType = schema.getMutationType();++ if (!mutationType) {+ throw new GraphQLError('Schema is not configured for mutations.', operation);+ }++ return mutationType;+ }++ if (operation.operation === 'subscription') {+ var subscriptionType = schema.getSubscriptionType();++ if (!subscriptionType) {+ throw new GraphQLError('Schema is not configured for subscriptions.', operation);+ }++ return subscriptionType;+ }++ throw new GraphQLError('Can only have query, mutation and subscription operations.', operation);+}++/**+ * Build a string describing the path.+ */+function printPathArray(path) {+ return path.map(function (key) {+ return typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key;+ }).join('');+}++/**+ * Produces a JavaScript value given a GraphQL Value AST.+ *+ * A GraphQL type must be provided, which will be used to interpret different+ * GraphQL Value literals.+ *+ * Returns `undefined` when the value could not be validly coerced according to+ * the provided type.+ *+ * | GraphQL Value | JSON Value |+ * | -------------------- | ------------- |+ * | Input Object | Object |+ * | List | Array |+ * | Boolean | Boolean |+ * | String | String |+ * | Int / Float | Number |+ * | Enum Value | Mixed |+ * | NullValue | null |+ *+ */++function valueFromAST(valueNode, type, variables) {+ if (!valueNode) {+ // When there is no node, then there is also no value.+ // Importantly, this is different from returning the value null.+ return;+ }++ if (valueNode.kind === Kind.VARIABLE) {+ var variableName = valueNode.name.value;++ if (variables == null || variables[variableName] === undefined) {+ // No valid return value.+ return;+ }++ var variableValue = variables[variableName];++ if (variableValue === null && isNonNullType(type)) {+ return; // Invalid: intentionally return no value.+ } // Note: This does no further checking that this variable is correct.+ // This assumes that this query has been validated and the variable+ // usage here is of the correct type.+++ return variableValue;+ }++ if (isNonNullType(type)) {+ if (valueNode.kind === Kind.NULL) {+ return; // Invalid: intentionally return no value.+ }++ return valueFromAST(valueNode, type.ofType, variables);+ }++ if (valueNode.kind === Kind.NULL) {+ // This is explicitly returning the value null.+ return null;+ }++ if (isListType(type)) {+ var itemType = type.ofType;++ if (valueNode.kind === Kind.LIST) {+ var coercedValues = [];++ for (var _i2 = 0, _valueNode$values2 = valueNode.values; _i2 < _valueNode$values2.length; _i2++) {+ var itemNode = _valueNode$values2[_i2];++ if (isMissingVariable(itemNode, variables)) {+ // If an array contains a missing variable, it is either coerced to+ // null or if the item type is non-null, it considered invalid.+ if (isNonNullType(itemType)) {+ return; // Invalid: intentionally return no value.+ }++ coercedValues.push(null);+ } else {+ var itemValue = valueFromAST(itemNode, itemType, variables);++ if (itemValue === undefined) {+ return; // Invalid: intentionally return no value.+ }++ coercedValues.push(itemValue);+ }+ }++ return coercedValues;+ }++ var coercedValue = valueFromAST(valueNode, itemType, variables);++ if (coercedValue === undefined) {+ return; // Invalid: intentionally return no value.+ }++ return [coercedValue];+ }++ if (isInputObjectType(type)) {+ if (valueNode.kind !== Kind.OBJECT) {+ return; // Invalid: intentionally return no value.+ }++ var coercedObj = Object.create(null);+ var fieldNodes = keyMap(valueNode.fields, function (field) {+ return field.name.value;+ });++ for (var _i4 = 0, _objectValues2 = objectValues(type.getFields()); _i4 < _objectValues2.length; _i4++) {+ var field = _objectValues2[_i4];+ var fieldNode = fieldNodes[field.name];++ if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {+ if (field.defaultValue !== undefined) {+ coercedObj[field.name] = field.defaultValue;+ } else if (isNonNullType(field.type)) {+ return; // Invalid: intentionally return no value.+ }++ continue;+ }++ var fieldValue = valueFromAST(fieldNode.value, field.type, variables);++ if (fieldValue === undefined) {+ return; // Invalid: intentionally return no value.+ }++ coercedObj[field.name] = fieldValue;+ }++ return coercedObj;+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isLeafType(type)) {+ // Scalars and Enums fulfill parsing a literal value via parseLiteral().+ // Invalid values represent a failure to parse correctly, in which case+ // no value is returned.+ var result;++ try {+ result = type.parseLiteral(valueNode, variables);+ } catch (_error) {+ return; // Invalid: intentionally return no value.+ }++ if (result === undefined) {+ return; // Invalid: intentionally return no value.+ }++ return result;+ } // istanbul ignore next (Not reachable. All possible input types have been considered)+++ invariant(0, 'Unexpected input type: ' + inspect(type));+} // Returns true if the provided valueNode is a variable which is not defined+// in the set of variables.++function isMissingVariable(valueNode, variables) {+ return valueNode.kind === Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === undefined);+}++/**+ * Coerces a JavaScript value given a GraphQL Input Type.+ */+function coerceInputValue(inputValue, type) {+ var onError = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultOnError;+ return coerceInputValueImpl(inputValue, type, onError);+}++function defaultOnError(path, invalidValue, error) {+ var errorPrefix = 'Invalid value ' + inspect(invalidValue);++ if (path.length > 0) {+ errorPrefix += " at \"value".concat(printPathArray(path), "\"");+ }++ error.message = errorPrefix + ': ' + error.message;+ throw error;+}++function coerceInputValueImpl(inputValue, type, onError, path) {+ if (isNonNullType(type)) {+ if (inputValue != null) {+ return coerceInputValueImpl(inputValue, type.ofType, onError, path);+ }++ onError(pathToArray(path), inputValue, new GraphQLError("Expected non-nullable type \"".concat(inspect(type), "\" not to be null.")));+ return;+ }++ if (inputValue == null) {+ // Explicitly return the value null.+ return null;+ }++ if (isListType(type)) {+ var itemType = type.ofType;++ if (isCollection(inputValue)) {+ return arrayFrom(inputValue, function (itemValue, index) {+ var itemPath = addPath(path, index, undefined);+ return coerceInputValueImpl(itemValue, itemType, onError, itemPath);+ });+ } // Lists accept a non-list value as a list of one.+++ return [coerceInputValueImpl(inputValue, itemType, onError, path)];+ }++ if (isInputObjectType(type)) {+ if (!isObjectLike(inputValue)) {+ onError(pathToArray(path), inputValue, new GraphQLError("Expected type \"".concat(type.name, "\" to be an object.")));+ return;+ }++ var coercedValue = {};+ var fieldDefs = type.getFields();++ for (var _i2 = 0, _objectValues2 = objectValues(fieldDefs); _i2 < _objectValues2.length; _i2++) {+ var field = _objectValues2[_i2];+ var fieldValue = inputValue[field.name];++ if (fieldValue === undefined) {+ if (field.defaultValue !== undefined) {+ coercedValue[field.name] = field.defaultValue;+ } else if (isNonNullType(field.type)) {+ var typeStr = inspect(field.type);+ onError(pathToArray(path), inputValue, new GraphQLError("Field \"".concat(field.name, "\" of required type \"").concat(typeStr, "\" was not provided.")));+ }++ continue;+ }++ coercedValue[field.name] = coerceInputValueImpl(fieldValue, field.type, onError, addPath(path, field.name, type.name));+ } // Ensure every provided field is defined.+++ for (var _i4 = 0, _Object$keys2 = Object.keys(inputValue); _i4 < _Object$keys2.length; _i4++) {+ var fieldName = _Object$keys2[_i4];++ if (!fieldDefs[fieldName]) {+ var suggestions = suggestionList(fieldName, Object.keys(type.getFields()));+ onError(pathToArray(path), inputValue, new GraphQLError("Field \"".concat(fieldName, "\" is not defined by type \"").concat(type.name, "\".") + didYouMean(suggestions)));+ }+ }++ return coercedValue;+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isLeafType(type)) {+ var parseResult; // Scalars and Enums determine if a input value is valid via parseValue(),+ // which can throw to indicate failure. If it throws, maintain a reference+ // to the original error.++ try {+ parseResult = type.parseValue(inputValue);+ } catch (error) {+ if (error instanceof GraphQLError) {+ onError(pathToArray(path), inputValue, error);+ } else {+ onError(pathToArray(path), inputValue, new GraphQLError("Expected type \"".concat(type.name, "\". ") + error.message, undefined, undefined, undefined, undefined, error));+ }++ return;+ }++ if (parseResult === undefined) {+ onError(pathToArray(path), inputValue, new GraphQLError("Expected type \"".concat(type.name, "\".")));+ }++ return parseResult;+ } // istanbul ignore next (Not reachable. All possible input types have been considered)+++ invariant(0, 'Unexpected input type: ' + inspect(type));+}++/**+ * Prepares an object map of variableValues of the correct type based on the+ * provided variable definitions and arbitrary input. If the input cannot be+ * parsed to match the variable definitions, a GraphQLError will be thrown.+ *+ * Note: The returned value is a plain Object with a prototype, since it is+ * exposed to user code. Care should be taken to not pull values from the+ * Object prototype.+ *+ * @internal+ */+function getVariableValues(schema, varDefNodes, inputs, options) {+ var errors = [];+ var maxErrors = options === null || options === void 0 ? void 0 : options.maxErrors;++ try {+ var coerced = coerceVariableValues(schema, varDefNodes, inputs, function (error) {+ if (maxErrors != null && errors.length >= maxErrors) {+ throw new GraphQLError('Too many errors processing variables, error limit reached. Execution aborted.');+ }++ errors.push(error);+ });++ if (errors.length === 0) {+ return {+ coerced: coerced+ };+ }+ } catch (error) {+ errors.push(error);+ }++ return {+ errors: errors+ };+}++function coerceVariableValues(schema, varDefNodes, inputs, onError) {+ var coercedValues = {};++ var _loop = function _loop(_i2) {+ var varDefNode = varDefNodes[_i2];+ var varName = varDefNode.variable.name.value;+ var varType = typeFromAST(schema, varDefNode.type);++ if (!isInputType(varType)) {+ // Must use input types for variables. This should be caught during+ // validation, however is checked again here for safety.+ var varTypeStr = print(varDefNode.type);+ onError(new GraphQLError("Variable \"$".concat(varName, "\" expected value of type \"").concat(varTypeStr, "\" which cannot be used as an input type."), varDefNode.type));+ return "continue";+ }++ if (!hasOwnProperty(inputs, varName)) {+ if (varDefNode.defaultValue) {+ coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType);+ } else if (isNonNullType(varType)) {+ var _varTypeStr = inspect(varType);++ onError(new GraphQLError("Variable \"$".concat(varName, "\" of required type \"").concat(_varTypeStr, "\" was not provided."), varDefNode));+ }++ return "continue";+ }++ var value = inputs[varName];++ if (value === null && isNonNullType(varType)) {+ var _varTypeStr2 = inspect(varType);++ onError(new GraphQLError("Variable \"$".concat(varName, "\" of non-null type \"").concat(_varTypeStr2, "\" must not be null."), varDefNode));+ return "continue";+ }++ coercedValues[varName] = coerceInputValue(value, varType, function (path, invalidValue, error) {+ var prefix = "Variable \"$".concat(varName, "\" got invalid value ") + inspect(invalidValue);++ if (path.length > 0) {+ prefix += " at \"".concat(varName).concat(printPathArray(path), "\"");+ }++ onError(new GraphQLError(prefix + '; ' + error.message, varDefNode, undefined, undefined, undefined, error.originalError));+ });+ };++ for (var _i2 = 0; _i2 < varDefNodes.length; _i2++) {+ var _ret = _loop(_i2);++ if (_ret === "continue") continue;+ }++ return coercedValues;+}+/**+ * Prepares an object map of argument values given a list of argument+ * definitions and list of argument AST nodes.+ *+ * Note: The returned value is a plain Object with a prototype, since it is+ * exposed to user code. Care should be taken to not pull values from the+ * Object prototype.+ *+ * @internal+ */+++function getArgumentValues(def, node, variableValues) {+ var _node$arguments;++ var coercedValues = {}; // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')++ var argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : [];+ var argNodeMap = keyMap(argumentNodes, function (arg) {+ return arg.name.value;+ });++ for (var _i4 = 0, _def$args2 = def.args; _i4 < _def$args2.length; _i4++) {+ var argDef = _def$args2[_i4];+ var name = argDef.name;+ var argType = argDef.type;+ var argumentNode = argNodeMap[name];++ if (!argumentNode) {+ if (argDef.defaultValue !== undefined) {+ coercedValues[name] = argDef.defaultValue;+ } else if (isNonNullType(argType)) {+ throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + 'was not provided.', node);+ }++ continue;+ }++ var valueNode = argumentNode.value;+ var isNull = valueNode.kind === Kind.NULL;++ if (valueNode.kind === Kind.VARIABLE) {+ var variableName = valueNode.name.value;++ if (variableValues == null || !hasOwnProperty(variableValues, variableName)) {+ if (argDef.defaultValue !== undefined) {+ coercedValues[name] = argDef.defaultValue;+ } else if (isNonNullType(argType)) {+ 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);+ }++ continue;+ }++ isNull = variableValues[variableName] == null;+ }++ if (isNull && isNonNullType(argType)) {+ throw new GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat(inspect(argType), "\" ") + 'must not be null.', valueNode);+ }++ var coercedValue = valueFromAST(valueNode, argType, variableValues);++ if (coercedValue === undefined) {+ // Note: ValuesOfCorrectTypeRule validation should catch this before+ // execution. This is a runtime check to ensure execution does not+ // continue with an invalid argument value.+ throw new GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat(print(valueNode), "."), valueNode);+ }++ coercedValues[name] = coercedValue;+ }++ return coercedValues;+}+/**+ * Prepares an object map of argument values given a directive definition+ * and a AST node which may contain directives. Optionally also accepts a map+ * of variable values.+ *+ * If the directive does not exist on the node, returns undefined.+ *+ * Note: The returned value is a plain Object with a prototype, since it is+ * exposed to user code. Care should be taken to not pull values from the+ * Object prototype.+ */++function getDirectiveValues(directiveDef, node, variableValues) {+ var directiveNode = node.directives && find(node.directives, function (directive) {+ return directive.name.value === directiveDef.name;+ });++ if (directiveNode) {+ return getArgumentValues(directiveDef, directiveNode, variableValues);+ }+}++function hasOwnProperty(obj, prop) {+ return Object.prototype.hasOwnProperty.call(obj, prop);+}++/**+ * Terminology+ *+ * "Definitions" are the generic name for top-level statements in the document.+ * Examples of this include:+ * 1) Operations (such as a query)+ * 2) Fragments+ *+ * "Operations" are a generic name for requests in the document.+ * Examples of this include:+ * 1) query,+ * 2) mutation+ *+ * "Selections" are the definitions that can appear legally and at+ * single level of the query. These include:+ * 1) field references e.g "a"+ * 2) fragment "spreads" e.g. "...c"+ * 3) inline fragment "spreads" e.g. "...on Type { a }"+ */++/**+ * Data that must be available at all points during query execution.+ *+ * Namely, schema of the type system that is currently executing,+ * and the fragments defined in the query document+ */++function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {+ /* eslint-enable no-redeclare */+ // Extract arguments from object args if provided.+ return arguments.length === 1 ? executeImpl(argsOrSchema) : executeImpl({+ schema: argsOrSchema,+ document: document,+ rootValue: rootValue,+ contextValue: contextValue,+ variableValues: variableValues,+ operationName: operationName,+ fieldResolver: fieldResolver,+ typeResolver: typeResolver+ });+}+/**+ * Also implements the "Evaluating requests" section of the GraphQL specification.+ * However, it guarantees to complete synchronously (or throw an error) assuming+ * that all field resolvers are also synchronous.+ */++function executeSync(args) {+ var result = executeImpl(args); // Assert that the execution was synchronous.++ if (isPromise(result)) {+ throw new Error('GraphQL execution failed to complete synchronously.');+ }++ return result;+}++function executeImpl(args) {+ var schema = args.schema,+ document = args.document,+ rootValue = args.rootValue,+ contextValue = args.contextValue,+ variableValues = args.variableValues,+ operationName = args.operationName,+ fieldResolver = args.fieldResolver,+ typeResolver = args.typeResolver; // If arguments are missing or incorrect, throw an error.++ assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,+ // a "Response" with only errors is returned.++ var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver); // Return early errors if execution context failed.++ if (Array.isArray(exeContext)) {+ return {+ errors: exeContext+ };+ } // Return a Promise that will eventually resolve to the data described by+ // The "Response" section of the GraphQL specification.+ //+ // If errors are encountered while executing a GraphQL field, only that+ // field and its descendants will be omitted, and sibling fields will still+ // be executed. An execution which encounters errors will still result in a+ // resolved Promise.+++ var data = executeOperation(exeContext, exeContext.operation, rootValue);+ return buildResponse(exeContext, data);+}+/**+ * Given a completed execution context and data, build the { errors, data }+ * response defined by the "Response" section of the GraphQL specification.+ */+++function buildResponse(exeContext, data) {+ if (isPromise(data)) {+ return data.then(function (resolved) {+ return buildResponse(exeContext, resolved);+ });+ }++ return exeContext.errors.length === 0 ? {+ data: data+ } : {+ errors: exeContext.errors,+ data: data+ };+}+/**+ * Essential assertions before executing to provide developer feedback for+ * improper use of the GraphQL library.+ *+ * @internal+ */+++function assertValidExecutionArguments(schema, document, rawVariableValues) {+ document || devAssert(0, 'Must provide document.'); // If the schema used for execution is invalid, throw an error.++ assertValidSchema(schema); // Variables, if provided, must be an object.++ rawVariableValues == null || isObjectLike(rawVariableValues) || devAssert(0, 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.');+}+/**+ * Constructs a ExecutionContext object from the arguments passed to+ * execute, which we will pass throughout the other execution methods.+ *+ * Throws a GraphQLError if a valid execution context cannot be created.+ *+ * @internal+ */++function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver, typeResolver) {+ var _definition$name, _operation$variableDe;++ var operation;+ var fragments = Object.create(null);++ for (var _i2 = 0, _document$definitions2 = document.definitions; _i2 < _document$definitions2.length; _i2++) {+ var definition = _document$definitions2[_i2];++ switch (definition.kind) {+ case Kind.OPERATION_DEFINITION:+ if (operationName == null) {+ if (operation !== undefined) {+ return [new GraphQLError('Must provide operation name if query contains multiple operations.')];+ }++ operation = definition;+ } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {+ operation = definition;+ }++ break;++ case Kind.FRAGMENT_DEFINITION:+ fragments[definition.name.value] = definition;+ break;+ }+ }++ if (!operation) {+ if (operationName != null) {+ return [new GraphQLError("Unknown operation named \"".concat(operationName, "\"."))];+ }++ return [new GraphQLError('Must provide an operation.')];+ } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+++ var variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : [];+ var coercedVariableValues = getVariableValues(schema, variableDefinitions, rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {}, {+ maxErrors: 50+ });++ if (coercedVariableValues.errors) {+ return coercedVariableValues.errors;+ }++ return {+ schema: schema,+ fragments: fragments,+ rootValue: rootValue,+ contextValue: contextValue,+ operation: operation,+ variableValues: coercedVariableValues.coerced,+ fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver,+ typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver,+ errors: []+ };+}+/**+ * Implements the "Evaluating operations" section of the spec.+ */++function executeOperation(exeContext, operation, rootValue) {+ var type = getOperationRootType(exeContext.schema, operation);+ var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null));+ var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level,+ // at which point we still log the error and null the parent field, which+ // in this case is the entire response.+ //+ // Similar to completeValueCatchingError.++ try {+ var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields);++ if (isPromise(result)) {+ return result.then(undefined, function (error) {+ exeContext.errors.push(error);+ return Promise.resolve(null);+ });+ }++ return result;+ } catch (error) {+ exeContext.errors.push(error);+ return null;+ }+}+/**+ * Implements the "Evaluating selection sets" section of the spec+ * for "write" mode.+ */+++function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {+ return promiseReduce(Object.keys(fields), function (results, responseName) {+ var fieldNodes = fields[responseName];+ var fieldPath = addPath(path, responseName, parentType.name);+ var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);++ if (result === undefined) {+ return results;+ }++ if (isPromise(result)) {+ return result.then(function (resolvedResult) {+ results[responseName] = resolvedResult;+ return results;+ });+ }++ results[responseName] = result;+ return results;+ }, Object.create(null));+}+/**+ * Implements the "Evaluating selection sets" section of the spec+ * for "read" mode.+ */+++function executeFields(exeContext, parentType, sourceValue, path, fields) {+ var results = Object.create(null);+ var containsPromise = false;++ for (var _i4 = 0, _Object$keys2 = Object.keys(fields); _i4 < _Object$keys2.length; _i4++) {+ var responseName = _Object$keys2[_i4];+ var fieldNodes = fields[responseName];+ var fieldPath = addPath(path, responseName, parentType.name);+ var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath);++ if (result !== undefined) {+ results[responseName] = result;++ if (!containsPromise && isPromise(result)) {+ containsPromise = true;+ }+ }+ } // If there are no promises, we can just return the object+++ if (!containsPromise) {+ return results;+ } // Otherwise, results is a map from field name to the result of resolving that+ // field, which is possibly a promise. Return a promise that will return this+ // same map, but with any promises replaced with the values they resolved to.+++ return promiseForObject(results);+}+/**+ * Given a selectionSet, adds all of the fields in that selection to+ * the passed in map of fields, and returns it at the end.+ *+ * CollectFields requires the "runtime type" of an object. For a field which+ * returns an Interface or Union type, the "runtime type" will be the actual+ * Object type returned by that field.+ *+ * @internal+ */+++function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {+ for (var _i6 = 0, _selectionSet$selecti2 = selectionSet.selections; _i6 < _selectionSet$selecti2.length; _i6++) {+ var selection = _selectionSet$selecti2[_i6];++ switch (selection.kind) {+ case Kind.FIELD:+ {+ if (!shouldIncludeNode(exeContext, selection)) {+ continue;+ }++ var name = getFieldEntryKey(selection);++ if (!fields[name]) {+ fields[name] = [];+ }++ fields[name].push(selection);+ break;+ }++ case Kind.INLINE_FRAGMENT:+ {+ if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {+ continue;+ }++ collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);+ break;+ }++ case Kind.FRAGMENT_SPREAD:+ {+ var fragName = selection.name.value;++ if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) {+ continue;+ }++ visitedFragmentNames[fragName] = true;+ var fragment = exeContext.fragments[fragName];++ if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {+ continue;+ }++ collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);+ break;+ }+ }+ }++ return fields;+}+/**+ * Determines if a field should be included based on the @include and @skip+ * directives, where @skip has higher precedence than @include.+ */++function shouldIncludeNode(exeContext, node) {+ var skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues);++ if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {+ return false;+ }++ var include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues);++ if ((include === null || include === void 0 ? void 0 : include.if) === false) {+ return false;+ }++ return true;+}+/**+ * Determines if a fragment is applicable to the given type.+ */+++function doesFragmentConditionMatch(exeContext, fragment, type) {+ var typeConditionNode = fragment.typeCondition;++ if (!typeConditionNode) {+ return true;+ }++ var conditionalType = typeFromAST(exeContext.schema, typeConditionNode);++ if (conditionalType === type) {+ return true;+ }++ if (isAbstractType(conditionalType)) {+ return exeContext.schema.isSubType(conditionalType, type);+ }++ return false;+}+/**+ * Implements the logic to compute the key of a given field's entry+ */+++function getFieldEntryKey(node) {+ return node.alias ? node.alias.value : node.name.value;+}+/**+ * Resolves the field on the given source object. In particular, this+ * figures out the value that the field returns by calling its resolve function,+ * then calls completeValue to complete promises, serialize scalars, or execute+ * the sub-selection-set for objects.+ */+++function resolveField(exeContext, parentType, source, fieldNodes, path) {+ var _fieldDef$resolve;++ var fieldNode = fieldNodes[0];+ var fieldName = fieldNode.name.value;+ var fieldDef = getFieldDef$1(exeContext.schema, parentType, fieldName);++ if (!fieldDef) {+ return;+ }++ var resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver;+ var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal+ // or abrupt (error).++ var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info);+ return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result);+}+/**+ * @internal+ */+++function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {+ // The resolve function's optional fourth argument is a collection of+ // information about the current execution state.+ return {+ fieldName: fieldDef.name,+ fieldNodes: fieldNodes,+ returnType: fieldDef.type,+ parentType: parentType,+ path: path,+ schema: exeContext.schema,+ fragments: exeContext.fragments,+ rootValue: exeContext.rootValue,+ operation: exeContext.operation,+ variableValues: exeContext.variableValues+ };+}+/**+ * Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField`+ * function. Returns the result of resolveFn or the abrupt-return Error object.+ *+ * @internal+ */++function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) {+ try {+ // Build a JS object of arguments from the field.arguments AST, using the+ // variables scope to fulfill any variable references.+ // TODO: find a way to memoize, in case this field is within a List type.+ var args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that+ // is provided to every resolve function within an execution. It is commonly+ // used to represent an authenticated user, or request-specific caches.++ var _contextValue = exeContext.contextValue;+ var result = resolveFn(source, args, _contextValue, info);+ return isPromise(result) ? result.then(undefined, asErrorInstance) : result;+ } catch (error) {+ return asErrorInstance(error);+ }+} // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a+// consistent Error interface.++function asErrorInstance(error) {+ if (error instanceof Error) {+ return error;+ }++ return new Error('Unexpected error value: ' + inspect(error));+} // This is a small wrapper around completeValue which detects and logs errors+// in the execution context.+++function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) {+ try {+ var completed;++ if (isPromise(result)) {+ completed = result.then(function (resolved) {+ return completeValue(exeContext, returnType, fieldNodes, info, path, resolved);+ });+ } else {+ completed = completeValue(exeContext, returnType, fieldNodes, info, path, result);+ }++ if (isPromise(completed)) {+ // Note: we don't rely on a `catch` method, but we do expect "thenable"+ // to take a second callback for the error case.+ return completed.then(undefined, function (error) {+ return handleFieldError(error, fieldNodes, path, returnType, exeContext);+ });+ }++ return completed;+ } catch (error) {+ return handleFieldError(error, fieldNodes, path, returnType, exeContext);+ }+}++function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) {+ var error = locatedError(asErrorInstance(rawError), fieldNodes, pathToArray(path)); // If the field type is non-nullable, then it is resolved without any+ // protection from errors, however it still properly locates the error.++ if (isNonNullType(returnType)) {+ throw error;+ } // Otherwise, error protection is applied, logging the error and resolving+ // a null value for this field if one is encountered.+++ exeContext.errors.push(error);+ return null;+}+/**+ * Implements the instructions for completeValue as defined in the+ * "Field entries" section of the spec.+ *+ * If the field type is Non-Null, then this recursively completes the value+ * for the inner type. It throws a field error if that completion returns null,+ * as per the "Nullability" section of the spec.+ *+ * If the field type is a List, then this recursively completes the value+ * for the inner type on each item in the list.+ *+ * If the field type is a Scalar or Enum, ensures the completed value is a legal+ * value of the type by calling the `serialize` method of GraphQL type+ * definition.+ *+ * If the field is an abstract type, determine the runtime type of the value+ * and then complete based on that type+ *+ * Otherwise, the field type expects a sub-selection set, and will complete the+ * value by evaluating all sub-selections.+ */+++function completeValue(exeContext, returnType, fieldNodes, info, path, result) {+ // If result is an Error, throw a located error.+ if (result instanceof Error) {+ throw result;+ } // If field type is NonNull, complete for inner type, and throw field error+ // if result is null.+++ if (isNonNullType(returnType)) {+ var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result);++ if (completed === null) {+ throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, "."));+ }++ return completed;+ } // If result value is null or undefined then return null.+++ if (result == null) {+ return null;+ } // If field type is List, complete each item in the list with the inner type+++ if (isListType(returnType)) {+ return completeListValue(exeContext, returnType, fieldNodes, info, path, result);+ } // If field type is a leaf type, Scalar or Enum, serialize to a valid value,+ // returning null if serialization is not possible.+++ if (isLeafType(returnType)) {+ return completeLeafValue(returnType, result);+ } // If field type is an abstract type, Interface or Union, determine the+ // runtime Object type and complete for that type.+++ if (isAbstractType(returnType)) {+ return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result);+ } // If field type is Object, execute and complete all sub-selections.+ // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isObjectType(returnType)) {+ return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result);+ } // istanbul ignore next (Not reachable. All possible output types have been considered)+++ invariant(0, 'Cannot complete value of unexpected output type: ' + inspect(returnType));+}+/**+ * Complete a list value by completing each item in the list with the+ * inner type+ */+++function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {+ if (!isCollection(result)) {+ throw new GraphQLError("Expected Iterable, but did not find one for field \"".concat(info.parentType.name, ".").concat(info.fieldName, "\"."));+ } // This is specified as a simple map, however we're optimizing the path+ // where the list contains no Promises by avoiding creating another Promise.+++ var itemType = returnType.ofType;+ var containsPromise = false;+ var completedResults = arrayFrom(result, function (item, index) {+ // No need to modify the info object containing the path,+ // since from here on it is not ever accessed by resolver functions.+ var fieldPath = addPath(path, index, undefined);+ var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item);++ if (!containsPromise && isPromise(completedItem)) {+ containsPromise = true;+ }++ return completedItem;+ });+ return containsPromise ? Promise.all(completedResults) : completedResults;+}+/**+ * Complete a Scalar or Enum by serializing to a valid value, returning+ * null if serialization is not possible.+ */+++function completeLeafValue(returnType, result) {+ var serializedResult = returnType.serialize(result);++ if (serializedResult === undefined) {+ throw new Error("Expected a value of type \"".concat(inspect(returnType), "\" but ") + "received: ".concat(inspect(result)));+ }++ return serializedResult;+}+/**+ * Complete a value of an abstract type by determining the runtime object type+ * of that value, then complete the value for that type.+ */+++function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {+ var _returnType$resolveTy;++ var resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver;+ var contextValue = exeContext.contextValue;+ var runtimeType = resolveTypeFn(result, contextValue, info, returnType);++ if (isPromise(runtimeType)) {+ return runtimeType.then(function (resolvedRuntimeType) {+ return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);+ });+ }++ return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result);+}++function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) {+ var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName;++ if (!isObjectType(runtimeType)) {+ throw new GraphQLError("Abstract type \"".concat(returnType.name, "\" must resolve to an Object type at runtime for field \"").concat(info.parentType.name, ".").concat(info.fieldName, "\" with ") + "value ".concat(inspect(result), ", received \"").concat(inspect(runtimeType), "\". ") + "Either the \"".concat(returnType.name, "\" type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."), fieldNodes);+ }++ if (!exeContext.schema.isSubType(returnType, runtimeType)) {+ throw new GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type for \"").concat(returnType.name, "\"."), fieldNodes);+ }++ return runtimeType;+}+/**+ * Complete an Object value by executing all sub-selections.+ */+++function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {+ // If there is an isTypeOf predicate function, call it with the+ // current result. If isTypeOf returns false, then raise an error rather+ // than continuing execution.+ if (returnType.isTypeOf) {+ var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);++ if (isPromise(isTypeOf)) {+ return isTypeOf.then(function (resolvedIsTypeOf) {+ if (!resolvedIsTypeOf) {+ throw invalidReturnTypeError(returnType, result, fieldNodes);+ }++ return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);+ });+ }++ if (!isTypeOf) {+ throw invalidReturnTypeError(returnType, result, fieldNodes);+ }+ }++ return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result);+}++function invalidReturnTypeError(returnType, result, fieldNodes) {+ return new GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat(inspect(result), "."), fieldNodes);+}++function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) {+ // Collect sub-fields to execute to complete this value.+ var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);+ return executeFields(exeContext, returnType, result, path, subFieldNodes);+}+/**+ * A memoized collection of relevant subfields with regard to the return+ * type. Memoizing ensures the subfields are not repeatedly calculated, which+ * saves overhead when resolving lists of values.+ */+++var collectSubfields = memoize3(_collectSubfields);++function _collectSubfields(exeContext, returnType, fieldNodes) {+ var subFieldNodes = Object.create(null);+ var visitedFragmentNames = Object.create(null);++ for (var _i8 = 0; _i8 < fieldNodes.length; _i8++) {+ var node = fieldNodes[_i8];++ if (node.selectionSet) {+ subFieldNodes = collectFields(exeContext, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames);+ }+ }++ return subFieldNodes;+}+/**+ * If a resolveType function is not given, then a default resolve behavior is+ * used which attempts two strategies:+ *+ * First, See if the provided value has a `__typename` field defined, if so, use+ * that value as name of the resolved type.+ *+ * Otherwise, test each possible type for the abstract type by calling+ * isTypeOf for the object being coerced, returning the first type that matches.+ */+++var defaultTypeResolver = function defaultTypeResolver(value, contextValue, info, abstractType) {+ // First, look for `__typename`.+ if (isObjectLike(value) && typeof value.__typename === 'string') {+ return value.__typename;+ } // Otherwise, test each possible type.+++ var possibleTypes = info.schema.getPossibleTypes(abstractType);+ var promisedIsTypeOfResults = [];++ for (var i = 0; i < possibleTypes.length; i++) {+ var type = possibleTypes[i];++ if (type.isTypeOf) {+ var isTypeOfResult = type.isTypeOf(value, contextValue, info);++ if (isPromise(isTypeOfResult)) {+ promisedIsTypeOfResults[i] = isTypeOfResult;+ } else if (isTypeOfResult) {+ return type;+ }+ }+ }++ if (promisedIsTypeOfResults.length) {+ return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) {+ for (var _i9 = 0; _i9 < isTypeOfResults.length; _i9++) {+ if (isTypeOfResults[_i9]) {+ return possibleTypes[_i9];+ }+ }+ });+ }+};+/**+ * If a resolve function is not given, then a default resolve behavior is used+ * which takes the property of the source object of the same name as the field+ * and returns it as the result, or if it's a function, returns the result+ * of calling that function while passing along args and context value.+ */++var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) {+ // ensure source is a value for which property access is acceptable.+ if (isObjectLike(source) || typeof source === 'function') {+ var property = source[info.fieldName];++ if (typeof property === 'function') {+ return source[info.fieldName](args, contextValue, info);+ }++ return property;+ }+};+/**+ * This method looks up the field on the given type definition.+ * It has special casing for the three introspection fields,+ * __schema, __type and __typename. __typename is special because+ * it can always be queried as a field, even in situations where no+ * other fields are allowed, like on a Union. __schema and __type+ * could get automatically added to the query type, but that would+ * require mutating type definitions, which would cause issues.+ *+ * @internal+ */++function getFieldDef$1(schema, parentType, fieldName) {+ if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {+ return SchemaMetaFieldDef;+ } else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {+ return TypeMetaFieldDef;+ } else if (fieldName === TypeNameMetaFieldDef.name) {+ return TypeNameMetaFieldDef;+ }++ return parentType.getFields()[fieldName];+}++/**+ * This is the primary entry point function for fulfilling GraphQL operations+ * by parsing, validating, and executing a GraphQL document along side a+ * GraphQL schema.+ *+ * More sophisticated GraphQL servers, such as those which persist queries,+ * may wish to separate the validation and execution phases to a static time+ * tooling step, and a server runtime step.+ *+ * Accepts either an object with named arguments, or individual arguments:+ *+ * schema:+ * The GraphQL type system to use when validating and executing a query.+ * source:+ * A GraphQL language formatted string representing the requested operation.+ * rootValue:+ * The value provided as the first argument to resolver functions on the top+ * level type (e.g. the query object type).+ * contextValue:+ * The context value is provided as an argument to resolver functions after+ * field arguments. It is used to pass shared information useful at any point+ * during executing this query, for example the currently logged in user and+ * connections to databases or other services.+ * variableValues:+ * A mapping of variable name to runtime value to use for all variables+ * defined in the requestString.+ * operationName:+ * The name of the operation to use if requestString contains multiple+ * possible operations. Can be omitted if requestString contains only+ * one operation.+ * fieldResolver:+ * A resolver function to use when one is not provided by the schema.+ * If not provided, the default field resolver is used (which looks for a+ * value or method on the source value with the field's name).+ * typeResolver:+ * A type resolver function to use when none is provided by the schema.+ * If not provided, the default type resolver is used (which looks for a+ * `__typename` field or alternatively calls the `isTypeOf` method).+ */++function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {+ var _arguments = arguments;++ /* eslint-enable no-redeclare */+ // Always return a Promise for a consistent API.+ return new Promise(function (resolve) {+ return resolve( // Extract arguments from object args if provided.+ _arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({+ schema: argsOrSchema,+ source: source,+ rootValue: rootValue,+ contextValue: contextValue,+ variableValues: variableValues,+ operationName: operationName,+ fieldResolver: fieldResolver,+ typeResolver: typeResolver+ }));+ });+}+/**+ * The graphqlSync function also fulfills GraphQL operations by parsing,+ * validating, and executing a GraphQL document along side a GraphQL schema.+ * However, it guarantees to complete synchronously (or throw an error) assuming+ * that all field resolvers are also synchronous.+ */++function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) {+ /* eslint-enable no-redeclare */+ // Extract arguments from object args if provided.+ var result = arguments.length === 1 ? graphqlImpl(argsOrSchema) : graphqlImpl({+ schema: argsOrSchema,+ source: source,+ rootValue: rootValue,+ contextValue: contextValue,+ variableValues: variableValues,+ operationName: operationName,+ fieldResolver: fieldResolver,+ typeResolver: typeResolver+ }); // Assert that the execution was synchronous.++ if (isPromise(result)) {+ throw new Error('GraphQL execution failed to complete synchronously.');+ }++ return result;+}++function graphqlImpl(args) {+ var schema = args.schema,+ source = args.source,+ rootValue = args.rootValue,+ contextValue = args.contextValue,+ variableValues = args.variableValues,+ operationName = args.operationName,+ fieldResolver = args.fieldResolver,+ typeResolver = args.typeResolver; // Validate Schema++ var schemaValidationErrors = validateSchema(schema);++ if (schemaValidationErrors.length > 0) {+ return {+ errors: schemaValidationErrors+ };+ } // Parse+++ var document;++ try {+ document = parse(source);+ } catch (syntaxError) {+ return {+ errors: [syntaxError]+ };+ } // Validate+++ var validationErrors = validate(schema, document);++ if (validationErrors.length > 0) {+ return {+ errors: validationErrors+ };+ } // Execute+++ return execute({+ schema: schema,+ document: document,+ rootValue: rootValue,+ contextValue: contextValue,+ variableValues: variableValues,+ operationName: operationName,+ fieldResolver: fieldResolver,+ typeResolver: typeResolver+ });+}++function _defineProperty$3(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }++/**+ * Given an AsyncIterable and a callback function, return an AsyncIterator+ * which produces values mapped via calling the callback function.+ */+function mapAsyncIterator(iterable, callback, rejectCallback) {+ // $FlowFixMe+ var iteratorMethod = iterable[SYMBOL_ASYNC_ITERATOR];+ var iterator = iteratorMethod.call(iterable);+ var $return;+ var abruptClose;++ if (typeof iterator.return === 'function') {+ $return = iterator.return;++ abruptClose = function abruptClose(error) {+ var rethrow = function rethrow() {+ return Promise.reject(error);+ };++ return $return.call(iterator).then(rethrow, rethrow);+ };+ }++ function mapResult(result) {+ return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);+ }++ var mapReject;++ if (rejectCallback) {+ // Capture rejectCallback to ensure it cannot be null.+ var reject = rejectCallback;++ mapReject = function mapReject(error) {+ return asyncMapValue(error, reject).then(iteratorResult, abruptClose);+ };+ }+ /* TODO: Flow doesn't support symbols as keys:+ https://github.com/facebook/flow/issues/3258 */+++ return _defineProperty$3({+ next: function next() {+ return iterator.next().then(mapResult, mapReject);+ },+ return: function _return() {+ return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({+ value: undefined,+ done: true+ });+ },+ throw: function _throw(error) {+ if (typeof iterator.throw === 'function') {+ return iterator.throw(error).then(mapResult, mapReject);+ }++ return Promise.reject(error).catch(abruptClose);+ }+ }, SYMBOL_ASYNC_ITERATOR, function () {+ return this;+ });+}++function asyncMapValue(value, callback) {+ return new Promise(function (resolve) {+ return resolve(callback(value));+ });+}++function iteratorResult(value) {+ return {+ value: value,+ done: false+ };+}++function _typeof$4(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$4 = function _typeof(obj) { return typeof obj; }; } else { _typeof$4 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$4(obj); }+function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) {+ /* eslint-enable no-redeclare */+ // Extract arguments from object args if provided.+ return arguments.length === 1 ? subscribeImpl(argsOrSchema) : subscribeImpl({+ schema: argsOrSchema,+ document: document,+ rootValue: rootValue,+ contextValue: contextValue,+ variableValues: variableValues,+ operationName: operationName,+ fieldResolver: fieldResolver,+ subscribeFieldResolver: subscribeFieldResolver+ });+}+/**+ * This function checks if the error is a GraphQLError. If it is, report it as+ * an ExecutionResult, containing only errors and no data. Otherwise treat the+ * error as a system-class error and re-throw it.+ */++function reportGraphQLError(error) {+ if (error instanceof GraphQLError) {+ return {+ errors: [error]+ };+ }++ throw error;+}++function subscribeImpl(args) {+ var schema = args.schema,+ document = args.document,+ rootValue = args.rootValue,+ contextValue = args.contextValue,+ variableValues = args.variableValues,+ operationName = args.operationName,+ fieldResolver = args.fieldResolver,+ subscribeFieldResolver = args.subscribeFieldResolver;+ var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal+ // GraphQL `execute` function, with `payload` as the rootValue.+ // This implements the "MapSourceToResponseEvent" algorithm described in+ // the GraphQL specification. The `execute` function provides the+ // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the+ // "ExecuteQuery" algorithm, for which `execute` is also used.++ var mapSourceToResponse = function mapSourceToResponse(payload) {+ return execute({+ schema: schema,+ document: document,+ rootValue: payload,+ contextValue: contextValue,+ variableValues: variableValues,+ operationName: operationName,+ fieldResolver: fieldResolver+ });+ }; // Resolve the Source Stream, then map every source value to a+ // ExecutionResult value as described above.+++ return sourcePromise.then(function (resultOrStream) {+ return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used.+ isAsyncIterable(resultOrStream) ? mapAsyncIterator(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream+ );+ });+}+/**+ * Implements the "CreateSourceEventStream" algorithm described in the+ * GraphQL specification, resolving the subscription source event stream.+ *+ * Returns a Promise which resolves to either an AsyncIterable (if successful)+ * or an ExecutionResult (error). The promise will be rejected if the schema or+ * other arguments to this function are invalid, or if the resolved event stream+ * is not an async iterable.+ *+ * If the client-provided arguments to this function do not result in a+ * compliant subscription, a GraphQL Response (ExecutionResult) with+ * descriptive errors and no data will be returned.+ *+ * If the the source stream could not be created due to faulty subscription+ * resolver logic or underlying systems, the promise will resolve to a single+ * ExecutionResult containing `errors` and no `data`.+ *+ * If the operation succeeded, the promise resolves to the AsyncIterable for the+ * event stream returned by the resolver.+ *+ * A Source Event Stream represents a sequence of events, each of which triggers+ * a GraphQL execution for that event.+ *+ * This may be useful when hosting the stateful subscription service in a+ * different process or machine than the stateless GraphQL execution engine,+ * or otherwise separating these two steps. For more on this, see the+ * "Supporting Subscriptions at Scale" information in the GraphQL specification.+ */+++function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) {+ // If arguments are missing or incorrectly typed, this is an internal+ // developer mistake which should throw an early error.+ assertValidExecutionArguments(schema, document, variableValues);++ try {+ var _fieldDef$subscribe;++ // If a valid context cannot be created due to incorrect arguments,+ // this will throw an error.+ var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed.++ if (Array.isArray(exeContext)) {+ return Promise.resolve({+ errors: exeContext+ });+ }++ var type = getOperationRootType(schema, exeContext.operation);+ var fields = collectFields(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null));+ var responseNames = Object.keys(fields);+ var responseName = responseNames[0];+ var fieldNodes = fields[responseName];+ var fieldNode = fieldNodes[0];+ var fieldName = fieldNode.name.value;+ var fieldDef = getFieldDef$1(schema, type, fieldName);++ if (!fieldDef) {+ throw new GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes);+ } // Call the `subscribe()` resolver or the default resolver to produce an+ // AsyncIterable yielding raw payloads.+++ var resolveFn = (_fieldDef$subscribe = fieldDef.subscribe) !== null && _fieldDef$subscribe !== void 0 ? _fieldDef$subscribe : exeContext.fieldResolver;+ var path = addPath(undefined, responseName, type.name);+ var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream"+ // algorithm from GraphQL specification. It differs from+ // "ResolveFieldValue" due to providing a different `resolveFn`.++ var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type.++ return Promise.resolve(result).then(function (eventStream) {+ // If eventStream is an Error, rethrow a located error.+ if (eventStream instanceof Error) {+ return {+ errors: [locatedError(eventStream, fieldNodes, pathToArray(path))]+ };+ } // Assert field returned an event stream, otherwise yield an error.+++ if (isAsyncIterable(eventStream)) {+ // Note: isAsyncIterable above ensures this will be correct.+ return eventStream;+ }++ throw new Error('Subscription field must return Async Iterable. ' + "Received: ".concat(inspect(eventStream), "."));+ });+ } catch (error) {+ // As with reportGraphQLError above, if the error is a GraphQLError, report+ // it as an ExecutionResult; otherwise treat it as a system-class error and+ // re-throw it.+ return error instanceof GraphQLError ? Promise.resolve({+ errors: [error]+ }) : Promise.reject(error);+ }+}+/**+ * Returns true if the provided object implements the AsyncIterator protocol via+ * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method.+ */++function isAsyncIterable(maybeAsyncIterable) {+ if (maybeAsyncIterable == null || _typeof$4(maybeAsyncIterable) !== 'object') {+ return false;+ }++ return typeof maybeAsyncIterable[SYMBOL_ASYNC_ITERATOR] === 'function';+}++/**+ * No deprecated+ *+ * A GraphQL document is only valid if all selected fields and all used enum values have not been+ * deprecated.+ *+ * Note: This rule is optional and is not part of the Validation section of the GraphQL+ * Specification. The main purpose of this rule is detection of deprecated usages and not+ * necessarily to forbid their use when querying a service.+ */+function NoDeprecatedCustomRule(context) {+ return {+ Field: function Field(node) {+ var fieldDef = context.getFieldDef();+ var parentType = context.getParentType();++ if (parentType && (fieldDef === null || fieldDef === void 0 ? void 0 : fieldDef.deprecationReason) != null) {+ context.reportError(new GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated. ") + fieldDef.deprecationReason, node));+ }+ },+ EnumValue: function EnumValue(node) {+ var type = getNamedType(context.getInputType());+ var enumValue = context.getEnumValue();++ if (type && (enumValue === null || enumValue === void 0 ? void 0 : enumValue.deprecationReason) != null) {+ context.reportError(new GraphQLError("The enum value \"".concat(type.name, ".").concat(enumValue.name, "\" is deprecated. ") + enumValue.deprecationReason, node));+ }+ }+ };+}++/**+ * Prohibit introspection queries+ *+ * A GraphQL document is only valid if all fields selected are not fields that+ * return an introspection type.+ *+ * Note: This rule is optional and is not part of the Validation section of the+ * GraphQL Specification. This rule effectively disables introspection, which+ * does not reflect best practices and should only be done if absolutely necessary.+ */+function NoSchemaIntrospectionCustomRule(context) {+ return {+ Field: function Field(node) {+ var type = getNamedType(context.getType());++ if (type && isIntrospectionType(type)) {+ context.reportError(new GraphQLError("GraphQL introspection has been disabled, but the requested query contained the field \"".concat(node.name.value, "\"."), node));+ }+ }+ };+}++/**+ * Given a GraphQLError, format it according to the rules described by the+ * Response Format, Errors section of the GraphQL Specification.+ */+function formatError(error) {+ var _error$message;++ error || devAssert(0, 'Received null or undefined error.');+ var message = (_error$message = error.message) !== null && _error$message !== void 0 ? _error$message : 'An unknown error occurred.';+ var locations = error.locations;+ var path = error.path;+ var extensions = error.extensions;+ return extensions ? {+ message: message,+ locations: locations,+ path: path,+ extensions: extensions+ } : {+ message: message,+ locations: locations,+ path: path+ };+}+/**+ * @see https://github.com/graphql/graphql-spec/blob/master/spec/Section%207%20--%20Response.md#errors+ */++function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }++function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty$4(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }++function _defineProperty$4(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }++function getIntrospectionQuery(options) {+ var optionsWithDefault = _objectSpread$2({+ descriptions: true,+ specifiedByUrl: false,+ directiveIsRepeatable: false,+ schemaDescription: false+ }, options);++ var descriptions = optionsWithDefault.descriptions ? 'description' : '';+ var specifiedByUrl = optionsWithDefault.specifiedByUrl ? 'specifiedByUrl' : '';+ var directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? 'isRepeatable' : '';+ var schemaDescription = optionsWithDefault.schemaDescription ? descriptions : '';+ return "\n query IntrospectionQuery {\n __schema {\n ".concat(schemaDescription, "\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ").concat(descriptions, "\n ").concat(directiveIsRepeatable, "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions, "\n ").concat(specifiedByUrl, "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions, "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions, "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions, "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n ");+}++/**+ * Returns an operation AST given a document AST and optionally an operation+ * name. If a name is not provided, an operation is only returned if only one is+ * provided in the document.+ */++function getOperationAST(documentAST, operationName) {+ var operation = null;++ for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {+ var definition = _documentAST$definiti2[_i2];++ if (definition.kind === Kind.OPERATION_DEFINITION) {+ var _definition$name;++ if (operationName == null) {+ // If no operation name was provided, only return an Operation if there+ // is one defined in the document. Upon encountering the second, return+ // null.+ if (operation) {+ return null;+ }++ operation = definition;+ } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {+ return definition;+ }+ }+ }++ return operation;+}++var getOperationAST$1 = /*#__PURE__*/Object.freeze({+ __proto__: null,+ getOperationAST: getOperationAST+});++function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }++function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty$5(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }++function _defineProperty$5(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }+/**+ * Build an IntrospectionQuery from a GraphQLSchema+ *+ * IntrospectionQuery is useful for utilities that care about type and field+ * relationships, but do not need to traverse through those relationships.+ *+ * This is the inverse of buildClientSchema. The primary use case is outside+ * of the server context, for instance when doing schema comparisons.+ */++function introspectionFromSchema(schema, options) {+ var optionsWithDefaults = _objectSpread$3({+ directiveIsRepeatable: true,+ schemaDescription: true+ }, options);++ var document = parse(getIntrospectionQuery(optionsWithDefaults));+ var result = executeSync({+ schema: schema,+ document: document+ });+ !result.errors && result.data || invariant(0);+ return result.data;+}++/**+ * Build a GraphQLSchema for use by client tools.+ *+ * Given the result of a client running the introspection query, creates and+ * returns a GraphQLSchema instance which can be then used with all graphql-js+ * tools, but cannot be used to execute a query, as introspection does not+ * represent the "resolver", "parse" or "serialize" functions or any other+ * server-internal mechanisms.+ *+ * This function expects a complete introspection result. Don't forget to check+ * the "errors" field of a server response before calling this function.+ */++function buildClientSchema(introspection, options) {+ isObjectLike(introspection) && isObjectLike(introspection.__schema) || devAssert(0, "Invalid or incomplete introspection result. Ensure that you are passing \"data\" property of introspection response and no \"errors\" was returned alongside: ".concat(inspect(introspection), ".")); // Get the schema from the introspection result.++ var schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each.++ var typeMap = keyValMap(schemaIntrospection.types, function (typeIntrospection) {+ return typeIntrospection.name;+ }, function (typeIntrospection) {+ return buildType(typeIntrospection);+ }); // Include standard types only if they are used.++ for (var _i2 = 0, _ref2 = [].concat(specifiedScalarTypes, introspectionTypes); _i2 < _ref2.length; _i2++) {+ var stdType = _ref2[_i2];++ if (typeMap[stdType.name]) {+ typeMap[stdType.name] = stdType;+ }+ } // Get the root Query, Mutation, and Subscription types.+++ var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null;+ var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null;+ var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if+ // directives were not queried for.++ var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types.++ return new GraphQLSchema({+ description: schemaIntrospection.description,+ query: queryType,+ mutation: mutationType,+ subscription: subscriptionType,+ types: objectValues(typeMap),+ directives: directives,+ assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid+ }); // Given a type reference in introspection, return the GraphQLType instance.+ // preferring cached instances before building new instances.++ function getType(typeRef) {+ if (typeRef.kind === TypeKind.LIST) {+ var itemRef = typeRef.ofType;++ if (!itemRef) {+ throw new Error('Decorated type deeper than introspection query.');+ }++ return GraphQLList(getType(itemRef));+ }++ if (typeRef.kind === TypeKind.NON_NULL) {+ var nullableRef = typeRef.ofType;++ if (!nullableRef) {+ throw new Error('Decorated type deeper than introspection query.');+ }++ var nullableType = getType(nullableRef);+ return GraphQLNonNull(assertNullableType(nullableType));+ }++ return getNamedType(typeRef);+ }++ function getNamedType(typeRef) {+ var typeName = typeRef.name;++ if (!typeName) {+ throw new Error("Unknown type reference: ".concat(inspect(typeRef), "."));+ }++ var type = typeMap[typeName];++ if (!type) {+ throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure that a full introspection query is used in order to build a client schema."));+ }++ return type;+ }++ function getObjectType(typeRef) {+ return assertObjectType(getNamedType(typeRef));+ }++ function getInterfaceType(typeRef) {+ return assertInterfaceType(getNamedType(typeRef));+ } // Given a type's introspection result, construct the correct+ // GraphQLType instance.+++ function buildType(type) {+ if (type != null && type.name != null && type.kind != null) {+ switch (type.kind) {+ case TypeKind.SCALAR:+ return buildScalarDef(type);++ case TypeKind.OBJECT:+ return buildObjectDef(type);++ case TypeKind.INTERFACE:+ return buildInterfaceDef(type);++ case TypeKind.UNION:+ return buildUnionDef(type);++ case TypeKind.ENUM:+ return buildEnumDef(type);++ case TypeKind.INPUT_OBJECT:+ return buildInputObjectDef(type);+ }+ }++ var typeStr = inspect(type);+ throw new Error("Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ".concat(typeStr, "."));+ }++ function buildScalarDef(scalarIntrospection) {+ return new GraphQLScalarType({+ name: scalarIntrospection.name,+ description: scalarIntrospection.description,+ specifiedByUrl: scalarIntrospection.specifiedByUrl+ });+ }++ function buildImplementationsList(implementingIntrospection) {+ // TODO: Temporary workaround until GraphQL ecosystem will fully support+ // 'interfaces' on interface types.+ if (implementingIntrospection.interfaces === null && implementingIntrospection.kind === TypeKind.INTERFACE) {+ return [];+ }++ if (!implementingIntrospection.interfaces) {+ var implementingIntrospectionStr = inspect(implementingIntrospection);+ throw new Error("Introspection result missing interfaces: ".concat(implementingIntrospectionStr, "."));+ }++ return implementingIntrospection.interfaces.map(getInterfaceType);+ }++ function buildObjectDef(objectIntrospection) {+ return new GraphQLObjectType({+ name: objectIntrospection.name,+ description: objectIntrospection.description,+ interfaces: function interfaces() {+ return buildImplementationsList(objectIntrospection);+ },+ fields: function fields() {+ return buildFieldDefMap(objectIntrospection);+ }+ });+ }++ function buildInterfaceDef(interfaceIntrospection) {+ return new GraphQLInterfaceType({+ name: interfaceIntrospection.name,+ description: interfaceIntrospection.description,+ interfaces: function interfaces() {+ return buildImplementationsList(interfaceIntrospection);+ },+ fields: function fields() {+ return buildFieldDefMap(interfaceIntrospection);+ }+ });+ }++ function buildUnionDef(unionIntrospection) {+ if (!unionIntrospection.possibleTypes) {+ var unionIntrospectionStr = inspect(unionIntrospection);+ throw new Error("Introspection result missing possibleTypes: ".concat(unionIntrospectionStr, "."));+ }++ return new GraphQLUnionType({+ name: unionIntrospection.name,+ description: unionIntrospection.description,+ types: function types() {+ return unionIntrospection.possibleTypes.map(getObjectType);+ }+ });+ }++ function buildEnumDef(enumIntrospection) {+ if (!enumIntrospection.enumValues) {+ var enumIntrospectionStr = inspect(enumIntrospection);+ throw new Error("Introspection result missing enumValues: ".concat(enumIntrospectionStr, "."));+ }++ return new GraphQLEnumType({+ name: enumIntrospection.name,+ description: enumIntrospection.description,+ values: keyValMap(enumIntrospection.enumValues, function (valueIntrospection) {+ return valueIntrospection.name;+ }, function (valueIntrospection) {+ return {+ description: valueIntrospection.description,+ deprecationReason: valueIntrospection.deprecationReason+ };+ })+ });+ }++ function buildInputObjectDef(inputObjectIntrospection) {+ if (!inputObjectIntrospection.inputFields) {+ var inputObjectIntrospectionStr = inspect(inputObjectIntrospection);+ throw new Error("Introspection result missing inputFields: ".concat(inputObjectIntrospectionStr, "."));+ }++ return new GraphQLInputObjectType({+ name: inputObjectIntrospection.name,+ description: inputObjectIntrospection.description,+ fields: function fields() {+ return buildInputValueDefMap(inputObjectIntrospection.inputFields);+ }+ });+ }++ function buildFieldDefMap(typeIntrospection) {+ if (!typeIntrospection.fields) {+ throw new Error("Introspection result missing fields: ".concat(inspect(typeIntrospection), "."));+ }++ return keyValMap(typeIntrospection.fields, function (fieldIntrospection) {+ return fieldIntrospection.name;+ }, buildField);+ }++ function buildField(fieldIntrospection) {+ var type = getType(fieldIntrospection.type);++ if (!isOutputType(type)) {+ var typeStr = inspect(type);+ throw new Error("Introspection must provide output type for fields, but received: ".concat(typeStr, "."));+ }++ if (!fieldIntrospection.args) {+ var fieldIntrospectionStr = inspect(fieldIntrospection);+ throw new Error("Introspection result missing field args: ".concat(fieldIntrospectionStr, "."));+ }++ return {+ description: fieldIntrospection.description,+ deprecationReason: fieldIntrospection.deprecationReason,+ type: type,+ args: buildInputValueDefMap(fieldIntrospection.args)+ };+ }++ function buildInputValueDefMap(inputValueIntrospections) {+ return keyValMap(inputValueIntrospections, function (inputValue) {+ return inputValue.name;+ }, buildInputValue);+ }++ function buildInputValue(inputValueIntrospection) {+ var type = getType(inputValueIntrospection.type);++ if (!isInputType(type)) {+ var typeStr = inspect(type);+ throw new Error("Introspection must provide input type for arguments, but received: ".concat(typeStr, "."));+ }++ var defaultValue = inputValueIntrospection.defaultValue != null ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) : undefined;+ return {+ description: inputValueIntrospection.description,+ type: type,+ defaultValue: defaultValue+ };+ }++ function buildDirective(directiveIntrospection) {+ if (!directiveIntrospection.args) {+ var directiveIntrospectionStr = inspect(directiveIntrospection);+ throw new Error("Introspection result missing directive args: ".concat(directiveIntrospectionStr, "."));+ }++ if (!directiveIntrospection.locations) {+ var _directiveIntrospectionStr = inspect(directiveIntrospection);++ throw new Error("Introspection result missing directive locations: ".concat(_directiveIntrospectionStr, "."));+ }++ return new GraphQLDirective({+ name: directiveIntrospection.name,+ description: directiveIntrospection.description,+ isRepeatable: directiveIntrospection.isRepeatable,+ locations: directiveIntrospection.locations.slice(),+ args: buildInputValueDefMap(directiveIntrospection.args)+ });+ }+}++function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }++function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty$6(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }++function _defineProperty$6(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }++/**+ * Produces a new schema given an existing schema and a document which may+ * contain GraphQL type extensions and definitions. The original schema will+ * remain unaltered.+ *+ * Because a schema represents a graph of references, a schema cannot be+ * extended without effectively making an entire copy. We do not know until it's+ * too late if subgraphs remain unchanged.+ *+ * This algorithm copies the provided schema, applying extensions while+ * producing the copy. The original schema remains unaltered.+ *+ * Accepts options as a third argument:+ *+ * - commentDescriptions:+ * Provide true to use preceding comments as the description.+ *+ */+function extendSchema(schema, documentAST, options) {+ assertSchema(schema);+ documentAST != null && documentAST.kind === Kind.DOCUMENT || devAssert(0, 'Must provide valid Document AST.');++ if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) {+ assertValidSDLExtension(documentAST, schema);+ }++ var schemaConfig = schema.toConfig();+ var extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options);+ return schemaConfig === extendedConfig ? schema : new GraphQLSchema(extendedConfig);+}+/**+ * @internal+ */++function extendSchemaImpl(schemaConfig, documentAST, options) {+ var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid;++ // Collect the type definitions and extensions found in the document.+ var typeDefs = [];+ var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can+ // have the same name. For example, a type named "skip".++ var directiveDefs = [];+ var schemaDef; // Schema extensions are collected which may add additional operation types.++ var schemaExtensions = [];++ for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {+ var def = _documentAST$definiti2[_i2];++ if (def.kind === Kind.SCHEMA_DEFINITION) {+ schemaDef = def;+ } else if (def.kind === Kind.SCHEMA_EXTENSION) {+ schemaExtensions.push(def);+ } else if (isTypeDefinitionNode(def)) {+ typeDefs.push(def);+ } else if (isTypeExtensionNode(def)) {+ var extendedTypeName = def.name.value;+ var existingTypeExtensions = typeExtensionsMap[extendedTypeName];+ typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def];+ } else if (def.kind === Kind.DIRECTIVE_DEFINITION) {+ directiveDefs.push(def);+ }+ } // If this document contains no new types, extensions, or directives then+ // return the same unmodified GraphQLSchema instance.+++ if (Object.keys(typeExtensionsMap).length === 0 && typeDefs.length === 0 && directiveDefs.length === 0 && schemaExtensions.length === 0 && schemaDef == null) {+ return schemaConfig;+ }++ var typeMap = Object.create(null);++ for (var _i4 = 0, _schemaConfig$types2 = schemaConfig.types; _i4 < _schemaConfig$types2.length; _i4++) {+ var existingType = _schemaConfig$types2[_i4];+ typeMap[existingType.name] = extendNamedType(existingType);+ }++ for (var _i6 = 0; _i6 < typeDefs.length; _i6++) {+ var _stdTypeMap$name;++ var typeNode = typeDefs[_i6];+ var name = typeNode.name.value;+ typeMap[name] = (_stdTypeMap$name = stdTypeMap[name]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode);+ }++ var operationTypes = _objectSpread$4(_objectSpread$4({+ // Get the extended root operation types.+ query: schemaConfig.query && replaceNamedType(schemaConfig.query),+ mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),+ subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription)+ }, schemaDef && getOperationTypes([schemaDef])), getOperationTypes(schemaExtensions)); // Then produce and return a Schema config with these types.+++ return _objectSpread$4(_objectSpread$4({+ description: (_schemaDef = schemaDef) === null || _schemaDef === void 0 ? void 0 : (_schemaDef$descriptio = _schemaDef.description) === null || _schemaDef$descriptio === void 0 ? void 0 : _schemaDef$descriptio.value+ }, operationTypes), {}, {+ types: objectValues(typeMap),+ directives: [].concat(schemaConfig.directives.map(replaceDirective), directiveDefs.map(buildDirective)),+ extensions: undefined,+ astNode: (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 ? _schemaDef2 : schemaConfig.astNode,+ extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),+ assumeValid: (_options$assumeValid = options === null || options === void 0 ? void 0 : options.assumeValid) !== null && _options$assumeValid !== void 0 ? _options$assumeValid : false+ }); // Below are functions used for producing this schema that have closed over+ // this scope and have access to the schema, cache, and newly defined types.++ function replaceType(type) {+ if (isListType(type)) {+ return new GraphQLList(replaceType(type.ofType));+ } else if (isNonNullType(type)) {+ return new GraphQLNonNull(replaceType(type.ofType));+ }++ return replaceNamedType(type);+ }++ function replaceNamedType(type) {+ // Note: While this could make early assertions to get the correctly+ // typed values, that would throw immediately while type system+ // validation with validateSchema() will produce more actionable results.+ return typeMap[type.name];+ }++ function replaceDirective(directive) {+ var config = directive.toConfig();+ return new GraphQLDirective(_objectSpread$4(_objectSpread$4({}, config), {}, {+ args: mapValue(config.args, extendArg)+ }));+ }++ function extendNamedType(type) {+ if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {+ // Builtin types are not extended.+ return type;+ }++ if (isScalarType(type)) {+ return extendScalarType(type);+ }++ if (isObjectType(type)) {+ return extendObjectType(type);+ }++ if (isInterfaceType(type)) {+ return extendInterfaceType(type);+ }++ if (isUnionType(type)) {+ return extendUnionType(type);+ }++ if (isEnumType(type)) {+ return extendEnumType(type);+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isInputObjectType(type)) {+ return extendInputObjectType(type);+ } // istanbul ignore next (Not reachable. All possible types have been considered)+++ invariant(0, 'Unexpected type: ' + inspect(type));+ }++ function extendInputObjectType(type) {+ var _typeExtensionsMap$co;++ var config = type.toConfig();+ var extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : [];+ return new GraphQLInputObjectType(_objectSpread$4(_objectSpread$4({}, config), {}, {+ fields: function fields() {+ return _objectSpread$4(_objectSpread$4({}, mapValue(config.fields, function (field) {+ return _objectSpread$4(_objectSpread$4({}, field), {}, {+ type: replaceType(field.type)+ });+ })), buildInputFieldMap(extensions));+ },+ extensionASTNodes: config.extensionASTNodes.concat(extensions)+ }));+ }++ function extendEnumType(type) {+ var _typeExtensionsMap$ty;++ var config = type.toConfig();+ var extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : [];+ return new GraphQLEnumType(_objectSpread$4(_objectSpread$4({}, config), {}, {+ values: _objectSpread$4(_objectSpread$4({}, config.values), buildEnumValueMap(extensions)),+ extensionASTNodes: config.extensionASTNodes.concat(extensions)+ }));+ }++ function extendScalarType(type) {+ var _typeExtensionsMap$co2;++ var config = type.toConfig();+ var extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : [];+ var specifiedByUrl = config.specifiedByUrl;++ for (var _i8 = 0; _i8 < extensions.length; _i8++) {+ var _getSpecifiedByUrl;++ var extensionNode = extensions[_i8];+ specifiedByUrl = (_getSpecifiedByUrl = getSpecifiedByUrl(extensionNode)) !== null && _getSpecifiedByUrl !== void 0 ? _getSpecifiedByUrl : specifiedByUrl;+ }++ return new GraphQLScalarType(_objectSpread$4(_objectSpread$4({}, config), {}, {+ specifiedByUrl: specifiedByUrl,+ extensionASTNodes: config.extensionASTNodes.concat(extensions)+ }));+ }++ function extendObjectType(type) {+ var _typeExtensionsMap$co3;++ var config = type.toConfig();+ var extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : [];+ return new GraphQLObjectType(_objectSpread$4(_objectSpread$4({}, config), {}, {+ interfaces: function interfaces() {+ return [].concat(type.getInterfaces().map(replaceNamedType), buildInterfaces(extensions));+ },+ fields: function fields() {+ return _objectSpread$4(_objectSpread$4({}, mapValue(config.fields, extendField)), buildFieldMap(extensions));+ },+ extensionASTNodes: config.extensionASTNodes.concat(extensions)+ }));+ }++ function extendInterfaceType(type) {+ var _typeExtensionsMap$co4;++ var config = type.toConfig();+ var extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : [];+ return new GraphQLInterfaceType(_objectSpread$4(_objectSpread$4({}, config), {}, {+ interfaces: function interfaces() {+ return [].concat(type.getInterfaces().map(replaceNamedType), buildInterfaces(extensions));+ },+ fields: function fields() {+ return _objectSpread$4(_objectSpread$4({}, mapValue(config.fields, extendField)), buildFieldMap(extensions));+ },+ extensionASTNodes: config.extensionASTNodes.concat(extensions)+ }));+ }++ function extendUnionType(type) {+ var _typeExtensionsMap$co5;++ var config = type.toConfig();+ var extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : [];+ return new GraphQLUnionType(_objectSpread$4(_objectSpread$4({}, config), {}, {+ types: function types() {+ return [].concat(type.getTypes().map(replaceNamedType), buildUnionTypes(extensions));+ },+ extensionASTNodes: config.extensionASTNodes.concat(extensions)+ }));+ }++ function extendField(field) {+ return _objectSpread$4(_objectSpread$4({}, field), {}, {+ type: replaceType(field.type),+ args: mapValue(field.args, extendArg)+ });+ }++ function extendArg(arg) {+ return _objectSpread$4(_objectSpread$4({}, arg), {}, {+ type: replaceType(arg.type)+ });+ }++ function getOperationTypes(nodes) {+ var opTypes = {};++ for (var _i10 = 0; _i10 < nodes.length; _i10++) {+ var _node$operationTypes;++ var node = nodes[_i10];+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : [];++ for (var _i12 = 0; _i12 < operationTypesNodes.length; _i12++) {+ var operationType = operationTypesNodes[_i12];+ opTypes[operationType.operation] = getNamedType(operationType.type);+ }+ } // Note: While this could make early assertions to get the correctly+ // typed values below, that would throw immediately while type system+ // validation with validateSchema() will produce more actionable results.+++ return opTypes;+ }++ function getNamedType(node) {+ var _stdTypeMap$name2;++ var name = node.name.value;+ var type = (_stdTypeMap$name2 = stdTypeMap[name]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name];++ if (type === undefined) {+ throw new Error("Unknown type: \"".concat(name, "\"."));+ }++ return type;+ }++ function getWrappedType(node) {+ if (node.kind === Kind.LIST_TYPE) {+ return new GraphQLList(getWrappedType(node.type));+ }++ if (node.kind === Kind.NON_NULL_TYPE) {+ return new GraphQLNonNull(getWrappedType(node.type));+ }++ return getNamedType(node);+ }++ function buildDirective(node) {+ var locations = node.locations.map(function (_ref) {+ var value = _ref.value;+ return value;+ });+ return new GraphQLDirective({+ name: node.name.value,+ description: getDescription(node, options),+ locations: locations,+ isRepeatable: node.repeatable,+ args: buildArgumentMap(node.arguments),+ astNode: node+ });+ }++ function buildFieldMap(nodes) {+ var fieldConfigMap = Object.create(null);++ for (var _i14 = 0; _i14 < nodes.length; _i14++) {+ var _node$fields;++ var node = nodes[_i14];+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var nodeFields = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];++ for (var _i16 = 0; _i16 < nodeFields.length; _i16++) {+ var field = nodeFields[_i16];+ fieldConfigMap[field.name.value] = {+ // Note: While this could make assertions to get the correctly typed+ // value, that would throw immediately while type system validation+ // with validateSchema() will produce more actionable results.+ type: getWrappedType(field.type),+ description: getDescription(field, options),+ args: buildArgumentMap(field.arguments),+ deprecationReason: getDeprecationReason(field),+ astNode: field+ };+ }+ }++ return fieldConfigMap;+ }++ function buildArgumentMap(args) {+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var argsNodes = args !== null && args !== void 0 ? args : [];+ var argConfigMap = Object.create(null);++ for (var _i18 = 0; _i18 < argsNodes.length; _i18++) {+ var arg = argsNodes[_i18];+ // Note: While this could make assertions to get the correctly typed+ // value, that would throw immediately while type system validation+ // with validateSchema() will produce more actionable results.+ var type = getWrappedType(arg.type);+ argConfigMap[arg.name.value] = {+ type: type,+ description: getDescription(arg, options),+ defaultValue: valueFromAST(arg.defaultValue, type),+ astNode: arg+ };+ }++ return argConfigMap;+ }++ function buildInputFieldMap(nodes) {+ var inputFieldMap = Object.create(null);++ for (var _i20 = 0; _i20 < nodes.length; _i20++) {+ var _node$fields2;++ var node = nodes[_i20];+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var fieldsNodes = (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : [];++ for (var _i22 = 0; _i22 < fieldsNodes.length; _i22++) {+ var field = fieldsNodes[_i22];+ // Note: While this could make assertions to get the correctly typed+ // value, that would throw immediately while type system validation+ // with validateSchema() will produce more actionable results.+ var type = getWrappedType(field.type);+ inputFieldMap[field.name.value] = {+ type: type,+ description: getDescription(field, options),+ defaultValue: valueFromAST(field.defaultValue, type),+ astNode: field+ };+ }+ }++ return inputFieldMap;+ }++ function buildEnumValueMap(nodes) {+ var enumValueMap = Object.create(null);++ for (var _i24 = 0; _i24 < nodes.length; _i24++) {+ var _node$values;++ var node = nodes[_i24];+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var valuesNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : [];++ for (var _i26 = 0; _i26 < valuesNodes.length; _i26++) {+ var value = valuesNodes[_i26];+ enumValueMap[value.name.value] = {+ description: getDescription(value, options),+ deprecationReason: getDeprecationReason(value),+ astNode: value+ };+ }+ }++ return enumValueMap;+ }++ function buildInterfaces(nodes) {+ var interfaces = [];++ for (var _i28 = 0; _i28 < nodes.length; _i28++) {+ var _node$interfaces;++ var node = nodes[_i28];+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var interfacesNodes = (_node$interfaces = node.interfaces) !== null && _node$interfaces !== void 0 ? _node$interfaces : [];++ for (var _i30 = 0; _i30 < interfacesNodes.length; _i30++) {+ var type = interfacesNodes[_i30];+ // Note: While this could make assertions to get the correctly typed+ // values below, that would throw immediately while type system+ // validation with validateSchema() will produce more actionable+ // results.+ interfaces.push(getNamedType(type));+ }+ }++ return interfaces;+ }++ function buildUnionTypes(nodes) {+ var types = [];++ for (var _i32 = 0; _i32 < nodes.length; _i32++) {+ var _node$types;++ var node = nodes[_i32];+ // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')+ var typeNodes = (_node$types = node.types) !== null && _node$types !== void 0 ? _node$types : [];++ for (var _i34 = 0; _i34 < typeNodes.length; _i34++) {+ var type = typeNodes[_i34];+ // Note: While this could make assertions to get the correctly typed+ // values below, that would throw immediately while type system+ // validation with validateSchema() will produce more actionable+ // results.+ types.push(getNamedType(type));+ }+ }++ return types;+ }++ function buildType(astNode) {+ var _typeExtensionsMap$na;++ var name = astNode.name.value;+ var description = getDescription(astNode, options);+ var extensionNodes = (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : [];++ switch (astNode.kind) {+ case Kind.OBJECT_TYPE_DEFINITION:+ {+ var extensionASTNodes = extensionNodes;+ var allNodes = [astNode].concat(extensionASTNodes);+ return new GraphQLObjectType({+ name: name,+ description: description,+ interfaces: function interfaces() {+ return buildInterfaces(allNodes);+ },+ fields: function fields() {+ return buildFieldMap(allNodes);+ },+ astNode: astNode,+ extensionASTNodes: extensionASTNodes+ });+ }++ case Kind.INTERFACE_TYPE_DEFINITION:+ {+ var _extensionASTNodes = extensionNodes;++ var _allNodes = [astNode].concat(_extensionASTNodes);++ return new GraphQLInterfaceType({+ name: name,+ description: description,+ interfaces: function interfaces() {+ return buildInterfaces(_allNodes);+ },+ fields: function fields() {+ return buildFieldMap(_allNodes);+ },+ astNode: astNode,+ extensionASTNodes: _extensionASTNodes+ });+ }++ case Kind.ENUM_TYPE_DEFINITION:+ {+ var _extensionASTNodes2 = extensionNodes;++ var _allNodes2 = [astNode].concat(_extensionASTNodes2);++ return new GraphQLEnumType({+ name: name,+ description: description,+ values: buildEnumValueMap(_allNodes2),+ astNode: astNode,+ extensionASTNodes: _extensionASTNodes2+ });+ }++ case Kind.UNION_TYPE_DEFINITION:+ {+ var _extensionASTNodes3 = extensionNodes;++ var _allNodes3 = [astNode].concat(_extensionASTNodes3);++ return new GraphQLUnionType({+ name: name,+ description: description,+ types: function types() {+ return buildUnionTypes(_allNodes3);+ },+ astNode: astNode,+ extensionASTNodes: _extensionASTNodes3+ });+ }++ case Kind.SCALAR_TYPE_DEFINITION:+ {+ var _extensionASTNodes4 = extensionNodes;+ return new GraphQLScalarType({+ name: name,+ description: description,+ specifiedByUrl: getSpecifiedByUrl(astNode),+ astNode: astNode,+ extensionASTNodes: _extensionASTNodes4+ });+ }++ case Kind.INPUT_OBJECT_TYPE_DEFINITION:+ {+ var _extensionASTNodes5 = extensionNodes;++ var _allNodes4 = [astNode].concat(_extensionASTNodes5);++ return new GraphQLInputObjectType({+ name: name,+ description: description,+ fields: function fields() {+ return buildInputFieldMap(_allNodes4);+ },+ astNode: astNode,+ extensionASTNodes: _extensionASTNodes5+ });+ }+ } // istanbul ignore next (Not reachable. All possible type definition nodes have been considered)+++ invariant(0, 'Unexpected type definition node: ' + inspect(astNode));+ }+}+var stdTypeMap = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) {+ return type.name;+});+/**+ * Given a field or enum value node, returns the string value for the+ * deprecation reason.+ */++function getDeprecationReason(node) {+ var deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node);+ return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason;+}+/**+ * Given a scalar node, returns the string value for the specifiedByUrl.+ */+++function getSpecifiedByUrl(node) {+ var specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node);+ return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url;+}+/**+ * Given an ast node, returns its string description.+ * @deprecated: provided to ease adoption and will be removed in v16.+ *+ * Accepts options as a second argument:+ *+ * - commentDescriptions:+ * Provide true to use preceding comments as the description.+ *+ */+++function getDescription(node, options) {+ if (node.description) {+ return node.description.value;+ }++ if ((options === null || options === void 0 ? void 0 : options.commentDescriptions) === true) {+ var rawValue = getLeadingCommentBlock(node);++ if (rawValue !== undefined) {+ return dedentBlockStringValue('\n' + rawValue);+ }+ }+}++function getLeadingCommentBlock(node) {+ var loc = node.loc;++ if (!loc) {+ return;+ }++ var comments = [];+ var token = loc.startToken.prev;++ while (token != null && token.kind === TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) {+ var value = String(token.value);+ comments.push(value);+ token = token.prev;+ }++ return comments.length > 0 ? comments.reverse().join('\n') : undefined;+}++/**+ * This takes the ast of a schema document produced by the parse function in+ * src/language/parser.js.+ *+ * If no schema definition is provided, then it will look for types named Query+ * and Mutation.+ *+ * Given that AST it constructs a GraphQLSchema. The resulting schema+ * has no resolve methods, so execution will use default resolvers.+ *+ * Accepts options as a second argument:+ *+ * - commentDescriptions:+ * Provide true to use preceding comments as the description.+ *+ */+function buildASTSchema(documentAST, options) {+ documentAST != null && documentAST.kind === Kind.DOCUMENT || devAssert(0, 'Must provide valid Document AST.');++ if ((options === null || options === void 0 ? void 0 : options.assumeValid) !== true && (options === null || options === void 0 ? void 0 : options.assumeValidSDL) !== true) {+ assertValidSDL(documentAST);+ }++ var emptySchemaConfig = {+ description: undefined,+ types: [],+ directives: [],+ extensions: undefined,+ extensionASTNodes: [],+ assumeValid: false+ };+ var config = extendSchemaImpl(emptySchemaConfig, documentAST, options);++ if (config.astNode == null) {+ for (var _i2 = 0, _config$types2 = config.types; _i2 < _config$types2.length; _i2++) {+ var type = _config$types2[_i2];++ switch (type.name) {+ // Note: While this could make early assertions to get the correctly+ // typed values below, that would throw immediately while type system+ // validation with validateSchema() will produce more actionable results.+ case 'Query':+ config.query = type;+ break;++ case 'Mutation':+ config.mutation = type;+ break;++ case 'Subscription':+ config.subscription = type;+ break;+ }+ }+ }++ var directives = config.directives; // If specified directives were not explicitly declared, add them.++ if (!directives.some(function (directive) {+ return directive.name === 'skip';+ })) {+ directives.push(GraphQLSkipDirective);+ }++ if (!directives.some(function (directive) {+ return directive.name === 'include';+ })) {+ directives.push(GraphQLIncludeDirective);+ }++ if (!directives.some(function (directive) {+ return directive.name === 'deprecated';+ })) {+ directives.push(GraphQLDeprecatedDirective);+ }++ if (!directives.some(function (directive) {+ return directive.name === 'specifiedBy';+ })) {+ directives.push(GraphQLSpecifiedByDirective);+ }++ return new GraphQLSchema(config);+}+/**+ * A helper function to build a GraphQLSchema directly from a source+ * document.+ */++function buildSchema(source, options) {+ var document = parse(source, {+ noLocation: options === null || options === void 0 ? void 0 : options.noLocation,+ allowLegacySDLEmptyFields: options === null || options === void 0 ? void 0 : options.allowLegacySDLEmptyFields,+ allowLegacySDLImplementsInterfaces: options === null || options === void 0 ? void 0 : options.allowLegacySDLImplementsInterfaces,+ experimentalFragmentVariables: options === null || options === void 0 ? void 0 : options.experimentalFragmentVariables+ });+ return buildASTSchema(document, {+ commentDescriptions: options === null || options === void 0 ? void 0 : options.commentDescriptions,+ assumeValidSDL: options === null || options === void 0 ? void 0 : options.assumeValidSDL,+ assumeValid: options === null || options === void 0 ? void 0 : options.assumeValid+ });+}++function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }++function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty$7(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }++function _defineProperty$7(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }+/**+ * Sort GraphQLSchema.+ *+ * This function returns a sorted copy of the given GraphQLSchema.+ */++function lexicographicSortSchema(schema) {+ var schemaConfig = schema.toConfig();+ var typeMap = keyValMap(sortByName(schemaConfig.types), function (type) {+ return type.name;+ }, sortNamedType);+ return new GraphQLSchema(_objectSpread$5(_objectSpread$5({}, schemaConfig), {}, {+ types: objectValues(typeMap),+ directives: sortByName(schemaConfig.directives).map(sortDirective),+ query: replaceMaybeType(schemaConfig.query),+ mutation: replaceMaybeType(schemaConfig.mutation),+ subscription: replaceMaybeType(schemaConfig.subscription)+ }));++ function replaceType(type) {+ if (isListType(type)) {+ return new GraphQLList(replaceType(type.ofType));+ } else if (isNonNullType(type)) {+ return new GraphQLNonNull(replaceType(type.ofType));+ }++ return replaceNamedType(type);+ }++ function replaceNamedType(type) {+ return typeMap[type.name];+ }++ function replaceMaybeType(maybeType) {+ return maybeType && replaceNamedType(maybeType);+ }++ function sortDirective(directive) {+ var config = directive.toConfig();+ return new GraphQLDirective(_objectSpread$5(_objectSpread$5({}, config), {}, {+ locations: sortBy(config.locations, function (x) {+ return x;+ }),+ args: sortArgs(config.args)+ }));+ }++ function sortArgs(args) {+ return sortObjMap(args, function (arg) {+ return _objectSpread$5(_objectSpread$5({}, arg), {}, {+ type: replaceType(arg.type)+ });+ });+ }++ function sortFields(fieldsMap) {+ return sortObjMap(fieldsMap, function (field) {+ return _objectSpread$5(_objectSpread$5({}, field), {}, {+ type: replaceType(field.type),+ args: sortArgs(field.args)+ });+ });+ }++ function sortInputFields(fieldsMap) {+ return sortObjMap(fieldsMap, function (field) {+ return _objectSpread$5(_objectSpread$5({}, field), {}, {+ type: replaceType(field.type)+ });+ });+ }++ function sortTypes(arr) {+ return sortByName(arr).map(replaceNamedType);+ }++ function sortNamedType(type) {+ if (isScalarType(type) || isIntrospectionType(type)) {+ return type;+ }++ if (isObjectType(type)) {+ var config = type.toConfig();+ return new GraphQLObjectType(_objectSpread$5(_objectSpread$5({}, config), {}, {+ interfaces: function interfaces() {+ return sortTypes(config.interfaces);+ },+ fields: function fields() {+ return sortFields(config.fields);+ }+ }));+ }++ if (isInterfaceType(type)) {+ var _config = type.toConfig();++ return new GraphQLInterfaceType(_objectSpread$5(_objectSpread$5({}, _config), {}, {+ interfaces: function interfaces() {+ return sortTypes(_config.interfaces);+ },+ fields: function fields() {+ return sortFields(_config.fields);+ }+ }));+ }++ if (isUnionType(type)) {+ var _config2 = type.toConfig();++ return new GraphQLUnionType(_objectSpread$5(_objectSpread$5({}, _config2), {}, {+ types: function types() {+ return sortTypes(_config2.types);+ }+ }));+ }++ if (isEnumType(type)) {+ var _config3 = type.toConfig();++ return new GraphQLEnumType(_objectSpread$5(_objectSpread$5({}, _config3), {}, {+ values: sortObjMap(_config3.values)+ }));+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isInputObjectType(type)) {+ var _config4 = type.toConfig();++ return new GraphQLInputObjectType(_objectSpread$5(_objectSpread$5({}, _config4), {}, {+ fields: function fields() {+ return sortInputFields(_config4.fields);+ }+ }));+ } // istanbul ignore next (Not reachable. All possible types have been considered)+++ invariant(0, 'Unexpected type: ' + inspect(type));+ }+}++function sortObjMap(map, sortValueFn) {+ var sortedMap = Object.create(null);+ var sortedKeys = sortBy(Object.keys(map), function (x) {+ return x;+ });++ for (var _i2 = 0; _i2 < sortedKeys.length; _i2++) {+ var key = sortedKeys[_i2];+ var value = map[key];+ sortedMap[key] = sortValueFn ? sortValueFn(value) : value;+ }++ return sortedMap;+}++function sortByName(array) {+ return sortBy(array, function (obj) {+ return obj.name;+ });+}++function sortBy(array, mapToKey) {+ return array.slice().sort(function (obj1, obj2) {+ var key1 = mapToKey(obj1);+ var key2 = mapToKey(obj2);+ return key1.localeCompare(key2);+ });+}++/**+ * Accepts options as a second argument:+ *+ * - commentDescriptions:+ * Provide true to use preceding comments as the description.+ *+ */+function printSchema(schema, options) {+ return printFilteredSchema(schema, function (n) {+ return !isSpecifiedDirective(n);+ }, isDefinedType, options);+}+function printIntrospectionSchema(schema, options) {+ return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType, options);+}++function isDefinedType(type) {+ return !isSpecifiedScalarType(type) && !isIntrospectionType(type);+}++function printFilteredSchema(schema, directiveFilter, typeFilter, options) {+ var directives = schema.getDirectives().filter(directiveFilter);+ var types = objectValues(schema.getTypeMap()).filter(typeFilter);+ return [printSchemaDefinition(schema)].concat(directives.map(function (directive) {+ return printDirective(directive, options);+ }), types.map(function (type) {+ return printType(type, options);+ })).filter(Boolean).join('\n\n') + '\n';+}++function printSchemaDefinition(schema) {+ if (schema.description == null && isSchemaOfCommonNames(schema)) {+ return;+ }++ var operationTypes = [];+ var queryType = schema.getQueryType();++ if (queryType) {+ operationTypes.push(" query: ".concat(queryType.name));+ }++ var mutationType = schema.getMutationType();++ if (mutationType) {+ operationTypes.push(" mutation: ".concat(mutationType.name));+ }++ var subscriptionType = schema.getSubscriptionType();++ if (subscriptionType) {+ operationTypes.push(" subscription: ".concat(subscriptionType.name));+ }++ return printDescription({}, schema) + "schema {\n".concat(operationTypes.join('\n'), "\n}");+}+/**+ * GraphQL schema define root types for each type of operation. These types are+ * the same as any other type and can be named in any manner, however there is+ * a common naming convention:+ *+ * schema {+ * query: Query+ * mutation: Mutation+ * }+ *+ * When using this naming convention, the schema description can be omitted.+ */+++function isSchemaOfCommonNames(schema) {+ var queryType = schema.getQueryType();++ if (queryType && queryType.name !== 'Query') {+ return false;+ }++ var mutationType = schema.getMutationType();++ if (mutationType && mutationType.name !== 'Mutation') {+ return false;+ }++ var subscriptionType = schema.getSubscriptionType();++ if (subscriptionType && subscriptionType.name !== 'Subscription') {+ return false;+ }++ return true;+}++function printType(type, options) {+ if (isScalarType(type)) {+ return printScalar(type, options);+ }++ if (isObjectType(type)) {+ return printObject(type, options);+ }++ if (isInterfaceType(type)) {+ return printInterface(type, options);+ }++ if (isUnionType(type)) {+ return printUnion(type, options);+ }++ if (isEnumType(type)) {+ return printEnum(type, options);+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isInputObjectType(type)) {+ return printInputObject(type, options);+ } // istanbul ignore next (Not reachable. All possible types have been considered)+++ invariant(0, 'Unexpected type: ' + inspect(type));+}++function printScalar(type, options) {+ return printDescription(options, type) + "scalar ".concat(type.name) + printSpecifiedByUrl(type);+}++function printImplementedInterfaces(type) {+ var interfaces = type.getInterfaces();+ return interfaces.length ? ' implements ' + interfaces.map(function (i) {+ return i.name;+ }).join(' & ') : '';+}++function printObject(type, options) {+ return printDescription(options, type) + "type ".concat(type.name) + printImplementedInterfaces(type) + printFields(options, type);+}++function printInterface(type, options) {+ return printDescription(options, type) + "interface ".concat(type.name) + printImplementedInterfaces(type) + printFields(options, type);+}++function printUnion(type, options) {+ var types = type.getTypes();+ var possibleTypes = types.length ? ' = ' + types.join(' | ') : '';+ return printDescription(options, type) + 'union ' + type.name + possibleTypes;+}++function printEnum(type, options) {+ var values = type.getValues().map(function (value, i) {+ return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value);+ });+ return printDescription(options, type) + "enum ".concat(type.name) + printBlock(values);+}++function printInputObject(type, options) {+ var fields = objectValues(type.getFields()).map(function (f, i) {+ return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f);+ });+ return printDescription(options, type) + "input ".concat(type.name) + printBlock(fields);+}++function printFields(options, type) {+ var fields = objectValues(type.getFields()).map(function (f, i) {+ return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f);+ });+ return printBlock(fields);+}++function printBlock(items) {+ return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : '';+}++function printArgs(options, args) {+ var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';++ if (args.length === 0) {+ return '';+ } // If every arg does not have a description, print them on one line.+++ if (args.every(function (arg) {+ return !arg.description;+ })) {+ return '(' + args.map(printInputValue).join(', ') + ')';+ }++ return '(\n' + args.map(function (arg, i) {+ return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg);+ }).join('\n') + '\n' + indentation + ')';+}++function printInputValue(arg) {+ var defaultAST = astFromValue(arg.defaultValue, arg.type);+ var argDecl = arg.name + ': ' + String(arg.type);++ if (defaultAST) {+ argDecl += " = ".concat(print(defaultAST));+ }++ return argDecl;+}++function printDirective(directive, options) {+ return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | ');+}++function printDeprecated(fieldOrEnumVal) {+ if (!fieldOrEnumVal.isDeprecated) {+ return '';+ }++ var reason = fieldOrEnumVal.deprecationReason;+ var reasonAST = astFromValue(reason, GraphQLString);++ if (reasonAST && reason !== DEFAULT_DEPRECATION_REASON) {+ return ' @deprecated(reason: ' + print(reasonAST) + ')';+ }++ return ' @deprecated';+}++function printSpecifiedByUrl(scalar) {+ if (scalar.specifiedByUrl == null) {+ return '';+ }++ var url = scalar.specifiedByUrl;+ var urlAST = astFromValue(url, GraphQLString);+ urlAST || invariant(0, 'Unexpected null value returned from `astFromValue` for specifiedByUrl');+ return ' @specifiedBy(url: ' + print(urlAST) + ')';+}++function printDescription(options, def) {+ var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';+ var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;+ var description = def.description;++ if (description == null) {+ return '';+ }++ if ((options === null || options === void 0 ? void 0 : options.commentDescriptions) === true) {+ return printDescriptionWithComments(description, indentation, firstInBlock);+ }++ var preferMultipleLines = description.length > 70;+ var blockString = printBlockString(description, '', preferMultipleLines);+ var prefix = indentation && !firstInBlock ? '\n' + indentation : indentation;+ return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n';+}++function printDescriptionWithComments(description, indentation, firstInBlock) {+ var prefix = indentation && !firstInBlock ? '\n' : '';+ var comment = description.split('\n').map(function (line) {+ return indentation + (line !== '' ? '# ' + line : '#');+ }).join('\n');+ return prefix + comment + '\n';+}++/**+ * Provided a collection of ASTs, presumably each from different files,+ * concatenate the ASTs together into batched AST, useful for validating many+ * GraphQL source files which together represent one conceptual application.+ */+function concatAST(asts) {+ return {+ kind: 'Document',+ definitions: flatMap(asts, function (ast) {+ return ast.definitions;+ })+ };+}++/**+ * separateOperations accepts a single AST document which may contain many+ * operations and fragments and returns a collection of AST documents each of+ * which contains a single operation as well the fragment definitions it+ * refers to.+ */++function separateOperations(documentAST) {+ var operations = [];+ var depGraph = Object.create(null);+ var fromName; // Populate metadata and build a dependency graph.++ visit(documentAST, {+ OperationDefinition: function OperationDefinition(node) {+ fromName = opName(node);+ operations.push(node);+ },+ FragmentDefinition: function FragmentDefinition(node) {+ fromName = node.name.value;+ },+ FragmentSpread: function FragmentSpread(node) {+ var toName = node.name.value;+ var dependents = depGraph[fromName];++ if (dependents === undefined) {+ dependents = depGraph[fromName] = Object.create(null);+ }++ dependents[toName] = true;+ }+ }); // For each operation, produce a new synthesized AST which includes only what+ // is necessary for completing that operation.++ var separatedDocumentASTs = Object.create(null);++ var _loop = function _loop(_i2) {+ var operation = operations[_i2];+ var operationName = opName(operation);+ var dependencies = Object.create(null);+ collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted+ // to retain the same order as the original document.++ separatedDocumentASTs[operationName] = {+ kind: Kind.DOCUMENT,+ definitions: documentAST.definitions.filter(function (node) {+ return node === operation || node.kind === Kind.FRAGMENT_DEFINITION && dependencies[node.name.value];+ })+ };+ };++ for (var _i2 = 0; _i2 < operations.length; _i2++) {+ _loop(_i2);+ }++ return separatedDocumentASTs;+}++// Provides the empty string for anonymous operations.+function opName(operation) {+ return operation.name ? operation.name.value : '';+} // From a dependency graph, collects a list of transitive dependencies by+// recursing through a dependency graph.+++function collectTransitiveDependencies(collected, depGraph, fromName) {+ var immediateDeps = depGraph[fromName];++ if (immediateDeps) {+ for (var _i4 = 0, _Object$keys2 = Object.keys(immediateDeps); _i4 < _Object$keys2.length; _i4++) {+ var toName = _Object$keys2[_i4];++ if (!collected[toName]) {+ collected[toName] = true;+ collectTransitiveDependencies(collected, depGraph, toName);+ }+ }+ }+}++/**+ * Strips characters that are not significant to the validity or execution+ * of a GraphQL document:+ * - UnicodeBOM+ * - WhiteSpace+ * - LineTerminator+ * - Comment+ * - Comma+ * - BlockString indentation+ *+ * Note: It is required to have a delimiter character between neighboring+ * non-punctuator tokens and this function always uses single space as delimiter.+ *+ * It is guaranteed that both input and output documents if parsed would result+ * in the exact same AST except for nodes location.+ *+ * Warning: It is guaranteed that this function will always produce stable results.+ * However, it's not guaranteed that it will stay the same between different+ * releases due to bugfixes or changes in the GraphQL specification.+ *+ * Query example:+ *+ * query SomeQuery($foo: String!, $bar: String) {+ * someField(foo: $foo, bar: $bar) {+ * a+ * b {+ * c+ * d+ * }+ * }+ * }+ *+ * Becomes:+ *+ * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}+ *+ * SDL example:+ *+ * """+ * Type description+ * """+ * type Foo {+ * """+ * Field description+ * """+ * bar: String+ * }+ *+ * Becomes:+ *+ * """Type description""" type Foo{"""Field description""" bar:String}+ */++function stripIgnoredCharacters(source) {+ var sourceObj = typeof source === 'string' ? new Source(source) : source;++ if (!(sourceObj instanceof Source)) {+ throw new TypeError("Must provide string or Source. Received: ".concat(inspect(sourceObj), "."));+ }++ var body = sourceObj.body;+ var lexer = new Lexer(sourceObj);+ var strippedBody = '';+ var wasLastAddedTokenNonPunctuator = false;++ while (lexer.advance().kind !== TokenKind.EOF) {+ var currentToken = lexer.token;+ var tokenKind = currentToken.kind;+ /**+ * Every two non-punctuator tokens should have space between them.+ * Also prevent case of non-punctuator token following by spread resulting+ * in invalid token (e.g. `1...` is invalid Float token).+ */++ var isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind);++ if (wasLastAddedTokenNonPunctuator) {+ if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) {+ strippedBody += ' ';+ }+ }++ var tokenBody = body.slice(currentToken.start, currentToken.end);++ if (tokenKind === TokenKind.BLOCK_STRING) {+ strippedBody += dedentBlockString(tokenBody);+ } else {+ strippedBody += tokenBody;+ }++ wasLastAddedTokenNonPunctuator = isNonPunctuator;+ }++ return strippedBody;+}++function dedentBlockString(blockStr) {+ // skip leading and trailing triple quotations+ var rawStr = blockStr.slice(3, -3);+ var body = dedentBlockStringValue(rawStr);+ var lines = body.split(/\r\n|[\n\r]/g);++ if (getBlockStringIndentation(lines) > 0) {+ body = '\n' + body;+ }++ var lastChar = body[body.length - 1];+ var hasTrailingQuote = lastChar === '"' && body.slice(-4) !== '\\"""';++ if (hasTrailingQuote || lastChar === '\\') {+ body += '\n';+ }++ return '"""' + body + '"""';+}++function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }++function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty$8(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }++function _defineProperty$8(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }+var BreakingChangeType = Object.freeze({+ TYPE_REMOVED: 'TYPE_REMOVED',+ TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND',+ TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION',+ VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM',+ REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED',+ IMPLEMENTED_INTERFACE_REMOVED: 'IMPLEMENTED_INTERFACE_REMOVED',+ FIELD_REMOVED: 'FIELD_REMOVED',+ FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND',+ REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED',+ ARG_REMOVED: 'ARG_REMOVED',+ ARG_CHANGED_KIND: 'ARG_CHANGED_KIND',+ DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED',+ DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED',+ REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED',+ DIRECTIVE_REPEATABLE_REMOVED: 'DIRECTIVE_REPEATABLE_REMOVED',+ DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED'+});+var DangerousChangeType = Object.freeze({+ VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM',+ TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION',+ OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED',+ OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED',+ IMPLEMENTED_INTERFACE_ADDED: 'IMPLEMENTED_INTERFACE_ADDED',+ ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE'+});++/**+ * Given two schemas, returns an Array containing descriptions of all the types+ * of breaking changes covered by the other functions down below.+ */+function findBreakingChanges(oldSchema, newSchema) {+ var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {+ return change.type in BreakingChangeType;+ });+ return breakingChanges;+}+/**+ * Given two schemas, returns an Array containing descriptions of all the types+ * of potentially dangerous changes covered by the other functions down below.+ */++function findDangerousChanges(oldSchema, newSchema) {+ var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {+ return change.type in DangerousChangeType;+ });+ return dangerousChanges;+}++function findSchemaChanges(oldSchema, newSchema) {+ return [].concat(findTypeChanges(oldSchema, newSchema), findDirectiveChanges(oldSchema, newSchema));+}++function findDirectiveChanges(oldSchema, newSchema) {+ var schemaChanges = [];+ var directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives());++ for (var _i2 = 0, _directivesDiff$remov2 = directivesDiff.removed; _i2 < _directivesDiff$remov2.length; _i2++) {+ var oldDirective = _directivesDiff$remov2[_i2];+ schemaChanges.push({+ type: BreakingChangeType.DIRECTIVE_REMOVED,+ description: "".concat(oldDirective.name, " was removed.")+ });+ }++ for (var _i4 = 0, _directivesDiff$persi2 = directivesDiff.persisted; _i4 < _directivesDiff$persi2.length; _i4++) {+ var _ref2 = _directivesDiff$persi2[_i4];+ var _oldDirective = _ref2[0];+ var newDirective = _ref2[1];+ var argsDiff = diff(_oldDirective.args, newDirective.args);++ for (var _i6 = 0, _argsDiff$added2 = argsDiff.added; _i6 < _argsDiff$added2.length; _i6++) {+ var newArg = _argsDiff$added2[_i6];++ if (isRequiredArgument(newArg)) {+ schemaChanges.push({+ type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED,+ description: "A required arg ".concat(newArg.name, " on directive ").concat(_oldDirective.name, " was added.")+ });+ }+ }++ for (var _i8 = 0, _argsDiff$removed2 = argsDiff.removed; _i8 < _argsDiff$removed2.length; _i8++) {+ var oldArg = _argsDiff$removed2[_i8];+ schemaChanges.push({+ type: BreakingChangeType.DIRECTIVE_ARG_REMOVED,+ description: "".concat(oldArg.name, " was removed from ").concat(_oldDirective.name, ".")+ });+ }++ if (_oldDirective.isRepeatable && !newDirective.isRepeatable) {+ schemaChanges.push({+ type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED,+ description: "Repeatable flag was removed from ".concat(_oldDirective.name, ".")+ });+ }++ for (var _i10 = 0, _oldDirective$locatio2 = _oldDirective.locations; _i10 < _oldDirective$locatio2.length; _i10++) {+ var location = _oldDirective$locatio2[_i10];++ if (newDirective.locations.indexOf(location) === -1) {+ schemaChanges.push({+ type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED,+ description: "".concat(location, " was removed from ").concat(_oldDirective.name, ".")+ });+ }+ }+ }++ return schemaChanges;+}++function findTypeChanges(oldSchema, newSchema) {+ var schemaChanges = [];+ var typesDiff = diff(objectValues(oldSchema.getTypeMap()), objectValues(newSchema.getTypeMap()));++ for (var _i12 = 0, _typesDiff$removed2 = typesDiff.removed; _i12 < _typesDiff$removed2.length; _i12++) {+ var oldType = _typesDiff$removed2[_i12];+ schemaChanges.push({+ type: BreakingChangeType.TYPE_REMOVED,+ description: isSpecifiedScalarType(oldType) ? "Standard scalar ".concat(oldType.name, " was removed because it is not referenced anymore.") : "".concat(oldType.name, " was removed.")+ });+ }++ for (var _i14 = 0, _typesDiff$persisted2 = typesDiff.persisted; _i14 < _typesDiff$persisted2.length; _i14++) {+ var _ref4 = _typesDiff$persisted2[_i14];+ var _oldType = _ref4[0];+ var newType = _ref4[1];++ if (isEnumType(_oldType) && isEnumType(newType)) {+ schemaChanges.push.apply(schemaChanges, findEnumTypeChanges(_oldType, newType));+ } else if (isUnionType(_oldType) && isUnionType(newType)) {+ schemaChanges.push.apply(schemaChanges, findUnionTypeChanges(_oldType, newType));+ } else if (isInputObjectType(_oldType) && isInputObjectType(newType)) {+ schemaChanges.push.apply(schemaChanges, findInputObjectTypeChanges(_oldType, newType));+ } else if (isObjectType(_oldType) && isObjectType(newType)) {+ schemaChanges.push.apply(schemaChanges, findFieldChanges(_oldType, newType).concat(findImplementedInterfacesChanges(_oldType, newType)));+ } else if (isInterfaceType(_oldType) && isInterfaceType(newType)) {+ schemaChanges.push.apply(schemaChanges, findFieldChanges(_oldType, newType).concat(findImplementedInterfacesChanges(_oldType, newType)));+ } else if (_oldType.constructor !== newType.constructor) {+ schemaChanges.push({+ type: BreakingChangeType.TYPE_CHANGED_KIND,+ description: "".concat(_oldType.name, " changed from ") + "".concat(typeKindName(_oldType), " to ").concat(typeKindName(newType), ".")+ });+ }+ }++ return schemaChanges;+}++function findInputObjectTypeChanges(oldType, newType) {+ var schemaChanges = [];+ var fieldsDiff = diff(objectValues(oldType.getFields()), objectValues(newType.getFields()));++ for (var _i16 = 0, _fieldsDiff$added2 = fieldsDiff.added; _i16 < _fieldsDiff$added2.length; _i16++) {+ var newField = _fieldsDiff$added2[_i16];++ if (isRequiredInputField(newField)) {+ schemaChanges.push({+ type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED,+ description: "A required field ".concat(newField.name, " on input type ").concat(oldType.name, " was added.")+ });+ } else {+ schemaChanges.push({+ type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED,+ description: "An optional field ".concat(newField.name, " on input type ").concat(oldType.name, " was added.")+ });+ }+ }++ for (var _i18 = 0, _fieldsDiff$removed2 = fieldsDiff.removed; _i18 < _fieldsDiff$removed2.length; _i18++) {+ var oldField = _fieldsDiff$removed2[_i18];+ schemaChanges.push({+ type: BreakingChangeType.FIELD_REMOVED,+ description: "".concat(oldType.name, ".").concat(oldField.name, " was removed.")+ });+ }++ for (var _i20 = 0, _fieldsDiff$persisted2 = fieldsDiff.persisted; _i20 < _fieldsDiff$persisted2.length; _i20++) {+ var _ref6 = _fieldsDiff$persisted2[_i20];+ var _oldField = _ref6[0];+ var _newField = _ref6[1];+ var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(_oldField.type, _newField.type);++ if (!isSafe) {+ schemaChanges.push({+ type: BreakingChangeType.FIELD_CHANGED_KIND,+ description: "".concat(oldType.name, ".").concat(_oldField.name, " changed type from ") + "".concat(String(_oldField.type), " to ").concat(String(_newField.type), ".")+ });+ }+ }++ return schemaChanges;+}++function findUnionTypeChanges(oldType, newType) {+ var schemaChanges = [];+ var possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes());++ for (var _i22 = 0, _possibleTypesDiff$ad2 = possibleTypesDiff.added; _i22 < _possibleTypesDiff$ad2.length; _i22++) {+ var newPossibleType = _possibleTypesDiff$ad2[_i22];+ schemaChanges.push({+ type: DangerousChangeType.TYPE_ADDED_TO_UNION,+ description: "".concat(newPossibleType.name, " was added to union type ").concat(oldType.name, ".")+ });+ }++ for (var _i24 = 0, _possibleTypesDiff$re2 = possibleTypesDiff.removed; _i24 < _possibleTypesDiff$re2.length; _i24++) {+ var oldPossibleType = _possibleTypesDiff$re2[_i24];+ schemaChanges.push({+ type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,+ description: "".concat(oldPossibleType.name, " was removed from union type ").concat(oldType.name, ".")+ });+ }++ return schemaChanges;+}++function findEnumTypeChanges(oldType, newType) {+ var schemaChanges = [];+ var valuesDiff = diff(oldType.getValues(), newType.getValues());++ for (var _i26 = 0, _valuesDiff$added2 = valuesDiff.added; _i26 < _valuesDiff$added2.length; _i26++) {+ var newValue = _valuesDiff$added2[_i26];+ schemaChanges.push({+ type: DangerousChangeType.VALUE_ADDED_TO_ENUM,+ description: "".concat(newValue.name, " was added to enum type ").concat(oldType.name, ".")+ });+ }++ for (var _i28 = 0, _valuesDiff$removed2 = valuesDiff.removed; _i28 < _valuesDiff$removed2.length; _i28++) {+ var oldValue = _valuesDiff$removed2[_i28];+ schemaChanges.push({+ type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,+ description: "".concat(oldValue.name, " was removed from enum type ").concat(oldType.name, ".")+ });+ }++ return schemaChanges;+}++function findImplementedInterfacesChanges(oldType, newType) {+ var schemaChanges = [];+ var interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces());++ for (var _i30 = 0, _interfacesDiff$added2 = interfacesDiff.added; _i30 < _interfacesDiff$added2.length; _i30++) {+ var newInterface = _interfacesDiff$added2[_i30];+ schemaChanges.push({+ type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED,+ description: "".concat(newInterface.name, " added to interfaces implemented by ").concat(oldType.name, ".")+ });+ }++ for (var _i32 = 0, _interfacesDiff$remov2 = interfacesDiff.removed; _i32 < _interfacesDiff$remov2.length; _i32++) {+ var oldInterface = _interfacesDiff$remov2[_i32];+ schemaChanges.push({+ type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED,+ description: "".concat(oldType.name, " no longer implements interface ").concat(oldInterface.name, ".")+ });+ }++ return schemaChanges;+}++function findFieldChanges(oldType, newType) {+ var schemaChanges = [];+ var fieldsDiff = diff(objectValues(oldType.getFields()), objectValues(newType.getFields()));++ for (var _i34 = 0, _fieldsDiff$removed4 = fieldsDiff.removed; _i34 < _fieldsDiff$removed4.length; _i34++) {+ var oldField = _fieldsDiff$removed4[_i34];+ schemaChanges.push({+ type: BreakingChangeType.FIELD_REMOVED,+ description: "".concat(oldType.name, ".").concat(oldField.name, " was removed.")+ });+ }++ for (var _i36 = 0, _fieldsDiff$persisted4 = fieldsDiff.persisted; _i36 < _fieldsDiff$persisted4.length; _i36++) {+ var _ref8 = _fieldsDiff$persisted4[_i36];+ var _oldField2 = _ref8[0];+ var newField = _ref8[1];+ schemaChanges.push.apply(schemaChanges, findArgChanges(oldType, _oldField2, newField));+ var isSafe = isChangeSafeForObjectOrInterfaceField(_oldField2.type, newField.type);++ if (!isSafe) {+ schemaChanges.push({+ type: BreakingChangeType.FIELD_CHANGED_KIND,+ description: "".concat(oldType.name, ".").concat(_oldField2.name, " changed type from ") + "".concat(String(_oldField2.type), " to ").concat(String(newField.type), ".")+ });+ }+ }++ return schemaChanges;+}++function findArgChanges(oldType, oldField, newField) {+ var schemaChanges = [];+ var argsDiff = diff(oldField.args, newField.args);++ for (var _i38 = 0, _argsDiff$removed4 = argsDiff.removed; _i38 < _argsDiff$removed4.length; _i38++) {+ var oldArg = _argsDiff$removed4[_i38];+ schemaChanges.push({+ type: BreakingChangeType.ARG_REMOVED,+ description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(oldArg.name, " was removed.")+ });+ }++ for (var _i40 = 0, _argsDiff$persisted2 = argsDiff.persisted; _i40 < _argsDiff$persisted2.length; _i40++) {+ var _ref10 = _argsDiff$persisted2[_i40];+ var _oldArg = _ref10[0];+ var newArg = _ref10[1];+ var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(_oldArg.type, newArg.type);++ if (!isSafe) {+ schemaChanges.push({+ type: BreakingChangeType.ARG_CHANGED_KIND,+ description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " has changed type from ") + "".concat(String(_oldArg.type), " to ").concat(String(newArg.type), ".")+ });+ } else if (_oldArg.defaultValue !== undefined) {+ if (newArg.defaultValue === undefined) {+ schemaChanges.push({+ type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,+ description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " defaultValue was removed.")+ });+ } else {+ // Since we looking only for client's observable changes we should+ // compare default values in the same representation as they are+ // represented inside introspection.+ var oldValueStr = stringifyValue(_oldArg.defaultValue, _oldArg.type);+ var newValueStr = stringifyValue(newArg.defaultValue, newArg.type);++ if (oldValueStr !== newValueStr) {+ schemaChanges.push({+ type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,+ description: "".concat(oldType.name, ".").concat(oldField.name, " arg ").concat(_oldArg.name, " has changed defaultValue from ").concat(oldValueStr, " to ").concat(newValueStr, ".")+ });+ }+ }+ }+ }++ for (var _i42 = 0, _argsDiff$added4 = argsDiff.added; _i42 < _argsDiff$added4.length; _i42++) {+ var _newArg = _argsDiff$added4[_i42];++ if (isRequiredArgument(_newArg)) {+ schemaChanges.push({+ type: BreakingChangeType.REQUIRED_ARG_ADDED,+ description: "A required arg ".concat(_newArg.name, " on ").concat(oldType.name, ".").concat(oldField.name, " was added.")+ });+ } else {+ schemaChanges.push({+ type: DangerousChangeType.OPTIONAL_ARG_ADDED,+ description: "An optional arg ".concat(_newArg.name, " on ").concat(oldType.name, ".").concat(oldField.name, " was added.")+ });+ }+ }++ return schemaChanges;+}++function isChangeSafeForObjectOrInterfaceField(oldType, newType) {+ if (isListType(oldType)) {+ return (// if they're both lists, make sure the underlying types are compatible+ isListType(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || // moving from nullable to non-null of the same underlying type is safe+ isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)+ );+ }++ if (isNonNullType(oldType)) {+ // if they're both non-null, make sure the underlying types are compatible+ return isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType);+ }++ return (// if they're both named types, see if their names are equivalent+ isNamedType(newType) && oldType.name === newType.name || // moving from nullable to non-null of the same underlying type is safe+ isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)+ );+}++function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) {+ if (isListType(oldType)) {+ // if they're both lists, make sure the underlying types are compatible+ return isListType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType);+ }++ if (isNonNullType(oldType)) {+ return (// if they're both non-null, make sure the underlying types are+ // compatible+ isNonNullType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || // moving from non-null to nullable of the same underlying type is safe+ !isNonNullType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)+ );+ } // if they're both named types, see if their names are equivalent+++ return isNamedType(newType) && oldType.name === newType.name;+}++function typeKindName(type) {+ if (isScalarType(type)) {+ return 'a Scalar type';+ }++ if (isObjectType(type)) {+ return 'an Object type';+ }++ if (isInterfaceType(type)) {+ return 'an Interface type';+ }++ if (isUnionType(type)) {+ return 'a Union type';+ }++ if (isEnumType(type)) {+ return 'an Enum type';+ } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')+++ if (isInputObjectType(type)) {+ return 'an Input type';+ } // istanbul ignore next (Not reachable. All possible named types have been considered)+++ invariant(0, 'Unexpected type: ' + inspect(type));+}++function stringifyValue(value, type) {+ var ast = astFromValue(value, type);+ ast != null || invariant(0);+ var sortedAST = visit(ast, {+ ObjectValue: function ObjectValue(objectNode) {+ var fields = [].concat(objectNode.fields).sort(function (fieldA, fieldB) {+ return fieldA.name.value.localeCompare(fieldB.name.value);+ });+ return _objectSpread$6(_objectSpread$6({}, objectNode), {}, {+ fields: fields+ });+ }+ });+ return print(sortedAST);+}++function diff(oldArray, newArray) {+ var added = [];+ var removed = [];+ var persisted = [];+ var oldMap = keyMap(oldArray, function (_ref11) {+ var name = _ref11.name;+ return name;+ });+ var newMap = keyMap(newArray, function (_ref12) {+ var name = _ref12.name;+ return name;+ });++ for (var _i44 = 0; _i44 < oldArray.length; _i44++) {+ var oldItem = oldArray[_i44];+ var newItem = newMap[oldItem.name];++ if (newItem === undefined) {+ removed.push(oldItem);+ } else {+ persisted.push([oldItem, newItem]);+ }+ }++ for (var _i46 = 0; _i46 < newArray.length; _i46++) {+ var _newItem = newArray[_i46];++ if (oldMap[_newItem.name] === undefined) {+ added.push(_newItem);+ }+ }++ return {+ added: added,+ persisted: persisted,+ removed: removed+ };+}++/**+ * A validation rule which reports deprecated usages.+ *+ * Returns a list of GraphQLError instances describing each deprecated use.+ *+ * @deprecated Please use `validate` with `NoDeprecatedCustomRule` instead:+ *+ * ```+ * import { validate, NoDeprecatedCustomRule } from 'graphql'+ *+ * const errors = validate(schema, document, [NoDeprecatedCustomRule])+ * ```+ */++function findDeprecatedUsages(schema, ast) {+ return validate(schema, ast, [NoDeprecatedCustomRule]);+}++/**+ * GraphQL.js provides a reference implementation for the GraphQL specification+ * but is also a useful utility for operating on GraphQL files and building+ * sophisticated tools.+ *+ * This primary module exports a general purpose function for fulfilling all+ * steps of the GraphQL specification in a single operation, but also includes+ * utilities for every part of the GraphQL specification:+ *+ * - Parsing the GraphQL language.+ * - Building a GraphQL type schema.+ * - Validating a GraphQL request against a type schema.+ * - Executing a GraphQL request against a type schema.+ *+ * This also includes utility functions for operating on GraphQL types and+ * GraphQL documents to facilitate building tools.+ *+ * You may also import from each sub-directory directly. For example, the+ * following two import statements are equivalent:+ *+ * import { parse } from 'graphql';+ * import { parse } from 'graphql/language';+ */++var graphql$1 = /*#__PURE__*/Object.freeze({+ __proto__: null,+ version: version,+ versionInfo: versionInfo,+ graphql: graphql,+ graphqlSync: graphqlSync,+ GraphQLSchema: GraphQLSchema,+ GraphQLDirective: GraphQLDirective,+ GraphQLScalarType: GraphQLScalarType,+ GraphQLObjectType: GraphQLObjectType,+ GraphQLInterfaceType: GraphQLInterfaceType,+ GraphQLUnionType: GraphQLUnionType,+ GraphQLEnumType: GraphQLEnumType,+ GraphQLInputObjectType: GraphQLInputObjectType,+ GraphQLList: GraphQLList,+ GraphQLNonNull: GraphQLNonNull,+ specifiedScalarTypes: specifiedScalarTypes,+ GraphQLInt: GraphQLInt,+ GraphQLFloat: GraphQLFloat,+ GraphQLString: GraphQLString,+ GraphQLBoolean: GraphQLBoolean,+ GraphQLID: GraphQLID,+ specifiedDirectives: specifiedDirectives,+ GraphQLIncludeDirective: GraphQLIncludeDirective,+ GraphQLSkipDirective: GraphQLSkipDirective,+ GraphQLDeprecatedDirective: GraphQLDeprecatedDirective,+ GraphQLSpecifiedByDirective: GraphQLSpecifiedByDirective,+ TypeKind: TypeKind,+ DEFAULT_DEPRECATION_REASON: DEFAULT_DEPRECATION_REASON,+ introspectionTypes: introspectionTypes,+ __Schema: __Schema,+ __Directive: __Directive,+ __DirectiveLocation: __DirectiveLocation,+ __Type: __Type,+ __Field: __Field,+ __InputValue: __InputValue,+ __EnumValue: __EnumValue,+ __TypeKind: __TypeKind,+ SchemaMetaFieldDef: SchemaMetaFieldDef,+ TypeMetaFieldDef: TypeMetaFieldDef,+ TypeNameMetaFieldDef: TypeNameMetaFieldDef,+ isSchema: isSchema,+ isDirective: isDirective,+ isType: isType,+ isScalarType: isScalarType,+ isObjectType: isObjectType,+ isInterfaceType: isInterfaceType,+ isUnionType: isUnionType,+ isEnumType: isEnumType,+ isInputObjectType: isInputObjectType,+ isListType: isListType,+ isNonNullType: isNonNullType,+ isInputType: isInputType,+ isOutputType: isOutputType,+ isLeafType: isLeafType,+ isCompositeType: isCompositeType,+ isAbstractType: isAbstractType,+ isWrappingType: isWrappingType,+ isNullableType: isNullableType,+ isNamedType: isNamedType,+ isRequiredArgument: isRequiredArgument,+ isRequiredInputField: isRequiredInputField,+ isSpecifiedScalarType: isSpecifiedScalarType,+ isIntrospectionType: isIntrospectionType,+ isSpecifiedDirective: isSpecifiedDirective,+ assertSchema: assertSchema,+ assertDirective: assertDirective,+ assertType: assertType,+ assertScalarType: assertScalarType,+ assertObjectType: assertObjectType,+ assertInterfaceType: assertInterfaceType,+ assertUnionType: assertUnionType,+ assertEnumType: assertEnumType,+ assertInputObjectType: assertInputObjectType,+ assertListType: assertListType,+ assertNonNullType: assertNonNullType,+ assertInputType: assertInputType,+ assertOutputType: assertOutputType,+ assertLeafType: assertLeafType,+ assertCompositeType: assertCompositeType,+ assertAbstractType: assertAbstractType,+ assertWrappingType: assertWrappingType,+ assertNullableType: assertNullableType,+ assertNamedType: assertNamedType,+ getNullableType: getNullableType,+ getNamedType: getNamedType,+ validateSchema: validateSchema,+ assertValidSchema: assertValidSchema,+ Token: Token,+ Source: Source,+ Location: Location,+ getLocation: getLocation,+ printLocation: printLocation,+ printSourceLocation: printSourceLocation,+ Lexer: Lexer,+ TokenKind: TokenKind,+ parse: parse,+ parseValue: parseValue,+ parseType: parseType,+ print: print,+ visit: visit,+ visitInParallel: visitInParallel,+ getVisitFn: getVisitFn,+ BREAK: BREAK,+ Kind: Kind,+ DirectiveLocation: DirectiveLocation,+ isDefinitionNode: isDefinitionNode,+ isExecutableDefinitionNode: isExecutableDefinitionNode,+ isSelectionNode: isSelectionNode,+ isValueNode: isValueNode,+ isTypeNode: isTypeNode,+ isTypeSystemDefinitionNode: isTypeSystemDefinitionNode,+ isTypeDefinitionNode: isTypeDefinitionNode,+ isTypeSystemExtensionNode: isTypeSystemExtensionNode,+ isTypeExtensionNode: isTypeExtensionNode,+ execute: execute,+ executeSync: executeSync,+ defaultFieldResolver: defaultFieldResolver,+ defaultTypeResolver: defaultTypeResolver,+ responsePathAsArray: pathToArray,+ getDirectiveValues: getDirectiveValues,+ subscribe: subscribe,+ createSourceEventStream: createSourceEventStream,+ validate: validate,+ ValidationContext: ValidationContext,+ specifiedRules: specifiedRules,+ ExecutableDefinitionsRule: ExecutableDefinitionsRule,+ FieldsOnCorrectTypeRule: FieldsOnCorrectTypeRule,+ FragmentsOnCompositeTypesRule: FragmentsOnCompositeTypesRule,+ KnownArgumentNamesRule: KnownArgumentNamesRule,+ KnownDirectivesRule: KnownDirectivesRule,+ KnownFragmentNamesRule: KnownFragmentNamesRule,+ KnownTypeNamesRule: KnownTypeNamesRule,+ LoneAnonymousOperationRule: LoneAnonymousOperationRule,+ NoFragmentCyclesRule: NoFragmentCyclesRule,+ NoUndefinedVariablesRule: NoUndefinedVariablesRule,+ NoUnusedFragmentsRule: NoUnusedFragmentsRule,+ NoUnusedVariablesRule: NoUnusedVariablesRule,+ OverlappingFieldsCanBeMergedRule: OverlappingFieldsCanBeMergedRule,+ PossibleFragmentSpreadsRule: PossibleFragmentSpreadsRule,+ ProvidedRequiredArgumentsRule: ProvidedRequiredArgumentsRule,+ ScalarLeafsRule: ScalarLeafsRule,+ SingleFieldSubscriptionsRule: SingleFieldSubscriptionsRule,+ UniqueArgumentNamesRule: UniqueArgumentNamesRule,+ UniqueDirectivesPerLocationRule: UniqueDirectivesPerLocationRule,+ UniqueFragmentNamesRule: UniqueFragmentNamesRule,+ UniqueInputFieldNamesRule: UniqueInputFieldNamesRule,+ UniqueOperationNamesRule: UniqueOperationNamesRule,+ UniqueVariableNamesRule: UniqueVariableNamesRule,+ ValuesOfCorrectTypeRule: ValuesOfCorrectTypeRule,+ VariablesAreInputTypesRule: VariablesAreInputTypesRule,+ VariablesInAllowedPositionRule: VariablesInAllowedPositionRule,+ LoneSchemaDefinitionRule: LoneSchemaDefinitionRule,+ UniqueOperationTypesRule: UniqueOperationTypesRule,+ UniqueTypeNamesRule: UniqueTypeNamesRule,+ UniqueEnumValueNamesRule: UniqueEnumValueNamesRule,+ UniqueFieldDefinitionNamesRule: UniqueFieldDefinitionNamesRule,+ UniqueDirectiveNamesRule: UniqueDirectiveNamesRule,+ PossibleTypeExtensionsRule: PossibleTypeExtensionsRule,+ NoDeprecatedCustomRule: NoDeprecatedCustomRule,+ NoSchemaIntrospectionCustomRule: NoSchemaIntrospectionCustomRule,+ GraphQLError: GraphQLError,+ syntaxError: syntaxError,+ locatedError: locatedError,+ printError: printError,+ formatError: formatError,+ getIntrospectionQuery: getIntrospectionQuery,+ getOperationAST: getOperationAST,+ getOperationRootType: getOperationRootType,+ introspectionFromSchema: introspectionFromSchema,+ buildClientSchema: buildClientSchema,+ buildASTSchema: buildASTSchema,+ buildSchema: buildSchema,+ getDescription: getDescription,+ extendSchema: extendSchema,+ lexicographicSortSchema: lexicographicSortSchema,+ printSchema: printSchema,+ printType: printType,+ printIntrospectionSchema: printIntrospectionSchema,+ typeFromAST: typeFromAST,+ valueFromAST: valueFromAST,+ valueFromASTUntyped: valueFromASTUntyped,+ astFromValue: astFromValue,+ TypeInfo: TypeInfo,+ visitWithTypeInfo: visitWithTypeInfo,+ coerceInputValue: coerceInputValue,+ concatAST: concatAST,+ separateOperations: separateOperations,+ stripIgnoredCharacters: stripIgnoredCharacters,+ isEqualType: isEqualType,+ isTypeSubTypeOf: isTypeSubTypeOf,+ doTypesOverlap: doTypesOverlap,+ assertValidName: assertValidName,+ isValidNameError: isValidNameError,+ BreakingChangeType: BreakingChangeType,+ DangerousChangeType: DangerousChangeType,+ findBreakingChanges: findBreakingChanges,+ findDangerousChanges: findDangerousChanges,+ findDeprecatedUsages: findDeprecatedUsages+});++var cleanInternalStack = function (stack) { return stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); };++/** +Escape RegExp special characters. +You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class. +@example +``` +import escapeStringRegexp = require('escape-string-regexp'); +const escapedString = escapeStringRegexp('How much $ for a 🦄?'); +//=> 'How much \\$ for a 🦄\\?' +new RegExp(escapedString); +``` +*/ +var escapeStringRegexp = function (string) { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + return string + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + .replace(/-/g, '\\x2d'); +};++var extractPathRegex = /\s+at.*[(\s](.*)\)?/; +var pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; +/** +Clean up error stack traces. Removes the mostly unhelpful internal Node.js entries. +@param stack - The `stack` property of an `Error`. +@example +``` +import cleanStack = require('clean-stack'); +const error = new Error('Missing unicorn'); +console.log(error.stack); +// Error: Missing unicorn +// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15) +// at Module._compile (module.js:409:26) +// at Object.Module._extensions..js (module.js:416:10) +// at Module.load (module.js:343:32) +// at Function.Module._load (module.js:300:12) +// at Function.Module.runMain (module.js:441:10) +// at startup (node.js:139:18) +console.log(cleanStack(error.stack)); +// Error: Missing unicorn +// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15) +``` +*/ +var cleanStack = function (stack, basePath) { + var basePathRegex = basePath && new RegExp("(at | \\()" + escapeStringRegexp(basePath), 'g'); + return stack.replace(/\\/g, '/') + .split('\n') + .filter(function (line) { + var pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } + var match = pathMatches[1]; + // Electron + if (match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar')) { + return false; + } + return !pathRegex.test(match); + }) + .filter(function (line) { return line.trim() !== ''; }) + .map(function (line) { + if (basePathRegex) { + line = line.replace(basePathRegex, '$1'); + } + return line; + }) + .join('\n'); +};++/** +Indent each line in a string. +@param string - The string to indent. +@param count - How many times you want `options.indent` repeated. Default: `1`. +@example +``` +import indentString = require('indent-string'); +indentString('Unicorns\nRainbows', 4); +//=> ' Unicorns\n Rainbows' +indentString('Unicorns\nRainbows', 4, {indent: '♥'}); +//=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows' +``` +*/ +var indentString = function (string, count, options) { + if (count === void 0) { count = 1; } + options = Object.assign({ + indent: ' ', + includeEmptyLines: false, + }, options); + if (typeof string !== 'string') { + throw new TypeError("Expected `input` to be a `string`, got `" + typeof string + "`"); + } + if (typeof count !== 'number') { + throw new TypeError("Expected `count` to be a `number`, got `" + typeof count + "`"); + } + if (count < 0) { + throw new RangeError("Expected `count` to be at least 0, got `" + count + "`"); + } + if (typeof options.indent !== 'string') { + throw new TypeError("Expected `options.indent` to be a `string`, got `" + typeof options.indent + "`"); + } + if (count === 0) { + return string; + } + var regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + return string.replace(regex, options.indent.repeat(count)); +};++var AggregateError = /** @class */ (function (_super) { + __extends(AggregateError, _super); + function AggregateError(errors) { + var _this = this; + if (!Array.isArray(errors)) { + throw new TypeError("Expected input to be an Array, got " + typeof errors); + } + var normalizedErrors = errors.map(function (error) { + if (error instanceof Error) { + return error; + } + if (error !== null && typeof error === 'object') { + // Handle plain error objects with message property and/or possibly other metadata + return Object.assign(new Error(error.message), error); + } + return new Error(error); + }); + var message = normalizedErrors + .map(function (error) { + // The `stack` property is not standardized, so we can't assume it exists + return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); + }) + .join('\n'); + message = '\n' + indentString(message, 4); + _this = _super.call(this, message) || this; + _this.name = 'AggregateError'; + Object.defineProperty(_this, Symbol.iterator, { + get: function () { return function () { return normalizedErrors[Symbol.iterator](); }; }, + }); + return _this; + } + return AggregateError; +}(Error));++const asArray = (fns) => (Array.isArray(fns) ? fns : fns ? [fns] : []);+function isEqual(a, b) {+ if (Array.isArray(a) && Array.isArray(b)) {+ if (a.length !== b.length) {+ return false;+ }+ for (let index = 0; index < a.length; index++) {+ if (a[index] !== b[index]) {+ return false;+ }+ }+ return true;+ }+ return a === b || (!a && !b);+}+function isNotEqual(a, b) {+ return !isEqual(a, b);+}+function isDocumentString(str) {+ // XXX: is-valid-path or is-glob treat SDL as a valid path+ // (`scalar Date` for example)+ // this why checking the extension is fast enough+ // and prevent from parsing the string in order to find out+ // if the string is a SDL+ if (/\.[a-z0-9]+$/i.test(str)) {+ return false;+ }+ try {+ parse(str);+ return true;+ }+ catch (e) { }+ return false;+}+const invalidPathRegex = /[‘“!$%&^<=>`]/;+function isValidPath(str) {+ return typeof str === 'string' && !invalidPathRegex.test(str);+}+function compareStrings(a, b) {+ if (a.toString() < b.toString()) {+ return -1;+ }+ if (a.toString() > b.toString()) {+ return 1;+ }+ return 0;+}+function nodeToString(a) {+ if ('alias' in a) {+ return a.alias.value;+ }+ if ('name' in a) {+ return a.name.value;+ }+ return a.kind;+}+function compareNodes(a, b, customFn) {+ const aStr = nodeToString(a);+ const bStr = nodeToString(b);+ if (typeof customFn === 'function') {+ return customFn(aStr, bStr);+ }+ return compareStrings(aStr, bStr);+}++function debugLog(...args) {+ if (process && process.env && process.env.DEBUG && !process.env.GQL_tools_NODEBUG) {+ // tslint:disable-next-line: no-console+ console.log(...args);+ }+}++const MAX_ARRAY_LENGTH$1 = 10;+const MAX_RECURSIVE_DEPTH$1 = 2;+/**+ * Used to print values in error messages.+ */+function inspect$1(value) {+ return formatValue$1(value, []);+}+function formatValue$1(value, seenValues) {+ switch (typeof value) {+ case 'string':+ return JSON.stringify(value);+ case 'function':+ return value.name ? `[function ${value.name}]` : '[function]';+ case 'object':+ if (value === null) {+ return 'null';+ }+ return formatObjectValue$1(value, seenValues);+ default:+ return String(value);+ }+}+function formatObjectValue$1(value, previouslySeenValues) {+ if (previouslySeenValues.indexOf(value) !== -1) {+ return '[Circular]';+ }+ const seenValues = [...previouslySeenValues, value];+ const customInspectFn = getCustomFn$1(value);+ if (customInspectFn !== undefined) {+ const customValue = customInspectFn.call(value);+ // check for infinite recursion+ if (customValue !== value) {+ return typeof customValue === 'string' ? customValue : formatValue$1(customValue, seenValues);+ }+ }+ else if (Array.isArray(value)) {+ return formatArray$1(value, seenValues);+ }+ return formatObject$1(value, seenValues);+}+function formatObject$1(object, seenValues) {+ const keys = Object.keys(object);+ if (keys.length === 0) {+ return '{}';+ }+ if (seenValues.length > MAX_RECURSIVE_DEPTH$1) {+ return '[' + getObjectTag$1(object) + ']';+ }+ const properties = keys.map(key => {+ const value = formatValue$1(object[key], seenValues);+ return key + ': ' + value;+ });+ return '{ ' + properties.join(', ') + ' }';+}+function formatArray$1(array, seenValues) {+ if (array.length === 0) {+ return '[]';+ }+ if (seenValues.length > MAX_RECURSIVE_DEPTH$1) {+ return '[Array]';+ }+ const len = Math.min(MAX_ARRAY_LENGTH$1, array.length);+ const remaining = array.length - len;+ const items = [];+ for (let i = 0; i < len; ++i) {+ items.push(formatValue$1(array[i], seenValues));+ }+ if (remaining === 1) {+ items.push('... 1 more item');+ }+ else if (remaining > 1) {+ items.push(`... ${remaining.toString(10)} more items`);+ }+ return '[' + items.join(', ') + ']';+}+function getCustomFn$1(obj) {+ if (typeof obj.inspect === 'function') {+ return obj.inspect;+ }+}+function getObjectTag$1(obj) {+ const tag = Object.prototype.toString+ .call(obj)+ .replace(/^\[object /, '')+ .replace(/]$/, '');+ if (tag === 'Object' && typeof obj.constructor === 'function') {+ const name = obj.constructor.name;+ if (typeof name === 'string' && name !== '') {+ return name;+ }+ }+ return tag;+}++/**+ * Prepares an object map of argument values given a list of argument+ * definitions and list of argument AST nodes.+ *+ * Note: The returned value is a plain Object with a prototype, since it is+ * exposed to user code. Care should be taken to not pull values from the+ * Object prototype.+ */+function getArgumentValues$1(def, node, variableValues = {}) {+ var _a;+ const variableMap = Object.entries(variableValues).reduce((prev, [key, value]) => ({+ ...prev,+ [key]: value,+ }), {});+ const coercedValues = {};+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ const argumentNodes = (_a = node.arguments) !== null && _a !== void 0 ? _a : [];+ const argNodeMap = argumentNodes.reduce((prev, arg) => ({+ ...prev,+ [arg.name.value]: arg,+ }), {});+ for (const argDef of def.args) {+ const name = argDef.name;+ const argType = argDef.type;+ const argumentNode = argNodeMap[name];+ if (!argumentNode) {+ if (argDef.defaultValue !== undefined) {+ coercedValues[name] = argDef.defaultValue;+ }+ else if (isNonNullType(argType)) {+ throw new GraphQLError(`Argument "${name}" of required type "${inspect$1(argType)}" ` + 'was not provided.', node);+ }+ continue;+ }+ const valueNode = argumentNode.value;+ let isNull = valueNode.kind === Kind.NULL;+ if (valueNode.kind === Kind.VARIABLE) {+ const variableName = valueNode.name.value;+ if (variableValues == null || !(variableName in variableMap)) {+ if (argDef.defaultValue !== undefined) {+ coercedValues[name] = argDef.defaultValue;+ }+ else if (isNonNullType(argType)) {+ throw new GraphQLError(`Argument "${name}" of required type "${inspect$1(argType)}" ` ++ `was provided the variable "$${variableName}" which was not provided a runtime value.`, valueNode);+ }+ continue;+ }+ isNull = variableValues[variableName] == null;+ }+ if (isNull && isNonNullType(argType)) {+ throw new GraphQLError(`Argument "${name}" of non-null type "${inspect$1(argType)}" ` + 'must not be null.', valueNode);+ }+ const coercedValue = valueFromAST(valueNode, argType, variableValues);+ if (coercedValue === undefined) {+ // Note: ValuesOfCorrectTypeRule validation should catch this before+ // execution. This is a runtime check to ensure execution does not+ // continue with an invalid argument value.+ throw new GraphQLError(`Argument "${name}" has invalid value ${print(valueNode)}.`, valueNode);+ }+ coercedValues[name] = coercedValue;+ }+ return coercedValues;+}++function createSchemaDefinition(def, config) {+ const schemaRoot = {};+ if (def.query) {+ schemaRoot.query = def.query.toString();+ }+ if (def.mutation) {+ schemaRoot.mutation = def.mutation.toString();+ }+ if (def.subscription) {+ schemaRoot.subscription = def.subscription.toString();+ }+ const fields = Object.keys(schemaRoot)+ .map(rootType => (schemaRoot[rootType] ? `${rootType}: ${schemaRoot[rootType]}` : null))+ .filter(a => a);+ if (fields.length) {+ return `schema { ${fields.join('\n')} }`;+ }+ if (config && config.force) {+ return ` schema { query: Query } `;+ }+ return undefined;+}++function printSchemaWithDirectives(schema, _options = {}) {+ var _a;+ const typesMap = schema.getTypeMap();+ const result = [getSchemaDefinition(schema)];+ for (const typeName in typesMap) {+ const type = typesMap[typeName];+ const isPredefinedScalar = isScalarType(type) && isSpecifiedScalarType(type);+ const isIntrospection = isIntrospectionType(type);+ if (isPredefinedScalar || isIntrospection) {+ continue;+ }+ // KAMIL: we might want to turn on descriptions in future+ result.push(print((_a = correctType(typeName, typesMap)) === null || _a === void 0 ? void 0 : _a.astNode));+ }+ const directives = schema.getDirectives();+ for (const directive of directives) {+ if (directive.astNode) {+ result.push(print(directive.astNode));+ }+ }+ return result.join('\n');+}+function extendDefinition(type) {+ switch (type.astNode.kind) {+ case Kind.OBJECT_TYPE_DEFINITION:+ return {+ ...type.astNode,+ fields: type.astNode.fields.concat(type.extensionASTNodes.reduce((fields, node) => fields.concat(node.fields), [])),+ };+ case Kind.INPUT_OBJECT_TYPE_DEFINITION:+ return {+ ...type.astNode,+ fields: type.astNode.fields.concat(type.extensionASTNodes.reduce((fields, node) => fields.concat(node.fields), [])),+ };+ default:+ return type.astNode;+ }+}+function correctType(typeName, typesMap) {+ var _a;+ const type = typesMap[typeName];+ type.name = typeName.toString();+ if (type.astNode && type.extensionASTNodes) {+ type.astNode = type.extensionASTNodes ? extendDefinition(type) : type.astNode;+ }+ const doc = parse(printType(type));+ const fixedAstNode = doc.definitions[0];+ const originalAstNode = type === null || type === void 0 ? void 0 : type.astNode;+ if (originalAstNode) {+ fixedAstNode.directives = originalAstNode === null || originalAstNode === void 0 ? void 0 : originalAstNode.directives;+ if (fixedAstNode && 'fields' in fixedAstNode && originalAstNode && 'fields' in originalAstNode) {+ for (const fieldDefinitionNode of fixedAstNode.fields) {+ const originalFieldDefinitionNode = originalAstNode.fields.find(field => field.name.value === fieldDefinitionNode.name.value);+ fieldDefinitionNode.directives = originalFieldDefinitionNode === null || originalFieldDefinitionNode === void 0 ? void 0 : originalFieldDefinitionNode.directives;+ if (fieldDefinitionNode &&+ 'arguments' in fieldDefinitionNode &&+ originalFieldDefinitionNode &&+ 'arguments' in originalFieldDefinitionNode) {+ for (const argument of fieldDefinitionNode.arguments) {+ const originalArgumentNode = (_a = originalFieldDefinitionNode.arguments) === null || _a === void 0 ? void 0 : _a.find(arg => arg.name.value === argument.name.value);+ argument.directives = originalArgumentNode.directives;+ }+ }+ }+ }+ else if (fixedAstNode && 'values' in fixedAstNode && originalAstNode && 'values' in originalAstNode) {+ for (const valueDefinitionNode of fixedAstNode.values) {+ const originalValueDefinitionNode = originalAstNode.values.find(valueNode => valueNode.name.value === valueDefinitionNode.name.value);+ valueDefinitionNode.directives = originalValueDefinitionNode === null || originalValueDefinitionNode === void 0 ? void 0 : originalValueDefinitionNode.directives;+ }+ }+ }+ type.astNode = fixedAstNode;+ return type;+}+function getSchemaDefinition(schema) {+ if (!Object.getOwnPropertyDescriptor(schema, 'astNode').get && schema.astNode) {+ return print(schema.astNode);+ }+ else {+ return createSchemaDefinition({+ query: schema.getQueryType(),+ mutation: schema.getMutationType(),+ subscription: schema.getSubscriptionType(),+ });+ }+}++function buildFixedSchema(schema, options) {+ return buildSchema(printSchemaWithDirectives(schema, options), {+ noLocation: true,+ ...(options || {}),+ });+}+function fixSchemaAst(schema, options) {+ let schemaWithValidAst;+ if (!schema.astNode) {+ Object.defineProperty(schema, 'astNode', {+ get() {+ if (!schemaWithValidAst) {+ schemaWithValidAst = buildFixedSchema(schema, options);+ }+ return schemaWithValidAst.astNode;+ },+ });+ }+ if (!schema.extensionASTNodes) {+ Object.defineProperty(schema, 'extensionASTNodes', {+ get() {+ if (!schemaWithValidAst) {+ schemaWithValidAst = buildFixedSchema(schema, options);+ }+ return schemaWithValidAst.extensionASTNodes;+ },+ });+ }+ return schema;+}++/**+ * Produces the value of a block string from its parsed raw value, similar to+ * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.+ *+ * This implements the GraphQL spec's BlockStringValue() static algorithm.+ *+ * @internal+ */+function dedentBlockStringValue$1(rawString) {+ // Expand a block string's raw value into independent lines.+ var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first.++ var commonIndent = getBlockStringIndentation$1(lines);++ if (commonIndent !== 0) {+ for (var i = 1; i < lines.length; i++) {+ lines[i] = lines[i].slice(commonIndent);+ }+ } // Remove leading and trailing blank lines.+++ while (lines.length > 0 && isBlank$1(lines[0])) {+ lines.shift();+ }++ while (lines.length > 0 && isBlank$1(lines[lines.length - 1])) {+ lines.pop();+ } // Return a string of the lines joined with U+000A.+++ return lines.join('\n');+}+/**+ * @internal+ */++function getBlockStringIndentation$1(lines) {+ var commonIndent = null;++ for (var i = 1; i < lines.length; i++) {+ var line = lines[i];+ var indent = leadingWhitespace$1(line);++ if (indent === line.length) {+ continue; // skip empty lines+ }++ if (commonIndent === null || indent < commonIndent) {+ commonIndent = indent;++ if (commonIndent === 0) {+ break;+ }+ }+ }++ return commonIndent === null ? 0 : commonIndent;+}++function leadingWhitespace$1(str) {+ var i = 0;++ while (i < str.length && (str[i] === ' ' || str[i] === '\t')) {+ i++;+ }++ return i;+}++function isBlank$1(str) {+ return leadingWhitespace$1(str) === str.length;+}++function parseGraphQLSDL(location, rawSDL, options = {}) {+ let document;+ const sdl = rawSDL;+ let sdlModified = false;+ try {+ if (options.commentDescriptions && sdl.includes('#')) {+ sdlModified = true;+ document = transformCommentsToDescriptions(rawSDL, options);+ // If noLocation=true, we need to make sure to print and parse it again, to remove locations,+ // since `transformCommentsToDescriptions` must have locations set in order to transform the comments+ // into descriptions.+ if (options.noLocation) {+ document = parse(print(document), options);+ }+ }+ else {+ document = parse(new Source(sdl, location), options);+ }+ }+ catch (e) {+ if (e.message.includes('EOF')) {+ document = {+ kind: Kind.DOCUMENT,+ definitions: [],+ };+ }+ else {+ throw e;+ }+ }+ return {+ location,+ document,+ rawSDL: sdlModified ? print(document) : sdl,+ };+}+function getLeadingCommentBlock$1(node) {+ const loc = node.loc;+ if (!loc) {+ return;+ }+ const comments = [];+ let token = loc.startToken.prev;+ while (token != null &&+ token.kind === TokenKind.COMMENT &&+ token.next &&+ token.prev &&+ token.line + 1 === token.next.line &&+ token.line !== token.prev.line) {+ const value = String(token.value);+ comments.push(value);+ token = token.prev;+ }+ return comments.length > 0 ? comments.reverse().join('\n') : undefined;+}+function transformCommentsToDescriptions(sourceSdl, options = {}) {+ const parsedDoc = parse(sourceSdl, {+ ...options,+ noLocation: false,+ });+ const modifiedDoc = visit(parsedDoc, {+ leave: (node) => {+ if (isDescribable(node)) {+ const rawValue = getLeadingCommentBlock$1(node);+ if (rawValue !== undefined) {+ const commentsBlock = dedentBlockStringValue$1('\n' + rawValue);+ const isBlock = commentsBlock.includes('\n');+ if (!node.description) {+ return {+ ...node,+ description: {+ kind: Kind.STRING,+ value: commentsBlock,+ block: isBlock,+ },+ };+ }+ else {+ return {+ ...node,+ description: {+ ...node.description,+ value: node.description.value + '\n' + commentsBlock,+ block: true,+ },+ };+ }+ }+ }+ },+ });+ return modifiedDoc;+}+function isDescribable(node) {+ return (isTypeSystemDefinitionNode(node) ||+ node.kind === Kind.FIELD_DEFINITION ||+ node.kind === Kind.INPUT_VALUE_DEFINITION ||+ node.kind === Kind.ENUM_VALUE_DEFINITION);+}++function stripBOM(content) {+ content = content.toString();+ // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)+ // because the buffer-to-string conversion in `fs.readFileSync()`+ // translates it to FEFF, the UTF-16 BOM.+ if (content.charCodeAt(0) === 0xfeff) {+ content = content.slice(1);+ }+ return content;+}+function parseBOM(content) {+ return JSON.parse(stripBOM(content));+}+function parseGraphQLJSON(location, jsonContent, options) {+ let parsedJson = parseBOM(jsonContent);+ if (parsedJson.data) {+ parsedJson = parsedJson.data;+ }+ if (parsedJson.kind === 'Document') {+ const document = parsedJson;+ return {+ location,+ document,+ };+ }+ else if (parsedJson.__schema) {+ const schema = buildClientSchema(parsedJson, options);+ const rawSDL = printSchemaWithDirectives(schema, options);+ return {+ location,+ document: parseGraphQLSDL(location, rawSDL, options).document,+ rawSDL,+ schema,+ };+ }+ throw new Error(`Not valid JSON content`);+}++var VisitSchemaKind;+(function (VisitSchemaKind) {+ VisitSchemaKind["TYPE"] = "VisitSchemaKind.TYPE";+ VisitSchemaKind["SCALAR_TYPE"] = "VisitSchemaKind.SCALAR_TYPE";+ VisitSchemaKind["ENUM_TYPE"] = "VisitSchemaKind.ENUM_TYPE";+ VisitSchemaKind["COMPOSITE_TYPE"] = "VisitSchemaKind.COMPOSITE_TYPE";+ VisitSchemaKind["OBJECT_TYPE"] = "VisitSchemaKind.OBJECT_TYPE";+ VisitSchemaKind["INPUT_OBJECT_TYPE"] = "VisitSchemaKind.INPUT_OBJECT_TYPE";+ VisitSchemaKind["ABSTRACT_TYPE"] = "VisitSchemaKind.ABSTRACT_TYPE";+ VisitSchemaKind["UNION_TYPE"] = "VisitSchemaKind.UNION_TYPE";+ VisitSchemaKind["INTERFACE_TYPE"] = "VisitSchemaKind.INTERFACE_TYPE";+ VisitSchemaKind["ROOT_OBJECT"] = "VisitSchemaKind.ROOT_OBJECT";+ VisitSchemaKind["QUERY"] = "VisitSchemaKind.QUERY";+ VisitSchemaKind["MUTATION"] = "VisitSchemaKind.MUTATION";+ VisitSchemaKind["SUBSCRIPTION"] = "VisitSchemaKind.SUBSCRIPTION";+})(VisitSchemaKind || (VisitSchemaKind = {}));+var MapperKind;+(function (MapperKind) {+ MapperKind["TYPE"] = "MapperKind.TYPE";+ MapperKind["SCALAR_TYPE"] = "MapperKind.SCALAR_TYPE";+ MapperKind["ENUM_TYPE"] = "MapperKind.ENUM_TYPE";+ MapperKind["COMPOSITE_TYPE"] = "MapperKind.COMPOSITE_TYPE";+ MapperKind["OBJECT_TYPE"] = "MapperKind.OBJECT_TYPE";+ MapperKind["INPUT_OBJECT_TYPE"] = "MapperKind.INPUT_OBJECT_TYPE";+ MapperKind["ABSTRACT_TYPE"] = "MapperKind.ABSTRACT_TYPE";+ MapperKind["UNION_TYPE"] = "MapperKind.UNION_TYPE";+ MapperKind["INTERFACE_TYPE"] = "MapperKind.INTERFACE_TYPE";+ MapperKind["ROOT_OBJECT"] = "MapperKind.ROOT_OBJECT";+ MapperKind["QUERY"] = "MapperKind.QUERY";+ MapperKind["MUTATION"] = "MapperKind.MUTATION";+ MapperKind["SUBSCRIPTION"] = "MapperKind.SUBSCRIPTION";+ MapperKind["DIRECTIVE"] = "MapperKind.DIRECTIVE";+ MapperKind["FIELD"] = "MapperKind.FIELD";+ MapperKind["COMPOSITE_FIELD"] = "MapperKind.COMPOSITE_FIELD";+ MapperKind["OBJECT_FIELD"] = "MapperKind.OBJECT_FIELD";+ MapperKind["ROOT_FIELD"] = "MapperKind.ROOT_FIELD";+ MapperKind["QUERY_ROOT_FIELD"] = "MapperKind.QUERY_ROOT_FIELD";+ MapperKind["MUTATION_ROOT_FIELD"] = "MapperKind.MUTATION_ROOT_FIELD";+ MapperKind["SUBSCRIPTION_ROOT_FIELD"] = "MapperKind.SUBSCRIPTION_ROOT_FIELD";+ MapperKind["INTERFACE_FIELD"] = "MapperKind.INTERFACE_FIELD";+ MapperKind["INPUT_OBJECT_FIELD"] = "MapperKind.INPUT_OBJECT_FIELD";+ MapperKind["ARGUMENT"] = "MapperKind.ARGUMENT";+ MapperKind["ENUM_VALUE"] = "MapperKind.ENUM_VALUE";+})(MapperKind || (MapperKind = {}));+function isNamedStub(type) {+ if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {+ const fields = type.getFields();+ const fieldNames = Object.keys(fields);+ return fieldNames.length === 1 && fields[fieldNames[0]].name === '__fake';+ }+ return false;+}+function getBuiltInForStub(type) {+ switch (type.name) {+ case GraphQLInt.name:+ return GraphQLInt;+ case GraphQLFloat.name:+ return GraphQLFloat;+ case GraphQLString.name:+ return GraphQLString;+ case GraphQLBoolean.name:+ return GraphQLBoolean;+ case GraphQLID.name:+ return GraphQLID;+ default:+ return type;+ }+}++function rewireTypes(originalTypeMap, directives, options = {+ skipPruning: false,+}) {+ const referenceTypeMap = Object.create(null);+ Object.keys(originalTypeMap).forEach(typeName => {+ referenceTypeMap[typeName] = originalTypeMap[typeName];+ });+ const newTypeMap = Object.create(null);+ Object.keys(referenceTypeMap).forEach(typeName => {+ const namedType = referenceTypeMap[typeName];+ if (namedType == null || typeName.startsWith('__')) {+ return;+ }+ const newName = namedType.name;+ if (newName.startsWith('__')) {+ return;+ }+ if (newTypeMap[newName] != null) {+ throw new Error(`Duplicate schema type name ${newName}`);+ }+ newTypeMap[newName] = namedType;+ });+ Object.keys(newTypeMap).forEach(typeName => {+ newTypeMap[typeName] = rewireNamedType(newTypeMap[typeName]);+ });+ const newDirectives = directives.map(directive => rewireDirective(directive));+ // TODO:+ // consider removing the default level of pruning in v7,+ // see comments below on the pruneTypes function.+ return options.skipPruning+ ? {+ typeMap: newTypeMap,+ directives: newDirectives,+ }+ : pruneTypes(newTypeMap, newDirectives);+ function rewireDirective(directive) {+ if (isSpecifiedDirective(directive)) {+ return directive;+ }+ const directiveConfig = directive.toConfig();+ directiveConfig.args = rewireArgs(directiveConfig.args);+ return new GraphQLDirective(directiveConfig);+ }+ function rewireArgs(args) {+ const rewiredArgs = {};+ Object.keys(args).forEach(argName => {+ const arg = args[argName];+ const rewiredArgType = rewireType(arg.type);+ if (rewiredArgType != null) {+ arg.type = rewiredArgType;+ rewiredArgs[argName] = arg;+ }+ });+ return rewiredArgs;+ }+ function rewireNamedType(type) {+ if (isObjectType(type)) {+ const config = type.toConfig();+ const newConfig = {+ ...config,+ fields: () => rewireFields(config.fields),+ interfaces: () => rewireNamedTypes(config.interfaces),+ };+ return new GraphQLObjectType(newConfig);+ }+ else if (isInterfaceType(type)) {+ const config = type.toConfig();+ const newConfig = {+ ...config,+ fields: () => rewireFields(config.fields),+ };+ if ('interfaces' in newConfig) {+ newConfig.interfaces = () => rewireNamedTypes(config.interfaces);+ }+ return new GraphQLInterfaceType(newConfig);+ }+ else if (isUnionType(type)) {+ const config = type.toConfig();+ const newConfig = {+ ...config,+ types: () => rewireNamedTypes(config.types),+ };+ return new GraphQLUnionType(newConfig);+ }+ else if (isInputObjectType(type)) {+ const config = type.toConfig();+ const newConfig = {+ ...config,+ fields: () => rewireInputFields(config.fields),+ };+ return new GraphQLInputObjectType(newConfig);+ }+ else if (isEnumType(type)) {+ const enumConfig = type.toConfig();+ return new GraphQLEnumType(enumConfig);+ }+ else if (isScalarType(type)) {+ if (isSpecifiedScalarType(type)) {+ return type;+ }+ const scalarConfig = type.toConfig();+ return new GraphQLScalarType(scalarConfig);+ }+ throw new Error(`Unexpected schema type: ${type}`);+ }+ function rewireFields(fields) {+ const rewiredFields = {};+ Object.keys(fields).forEach(fieldName => {+ const field = fields[fieldName];+ const rewiredFieldType = rewireType(field.type);+ if (rewiredFieldType != null) {+ field.type = rewiredFieldType;+ field.args = rewireArgs(field.args);+ rewiredFields[fieldName] = field;+ }+ });+ return rewiredFields;+ }+ function rewireInputFields(fields) {+ const rewiredFields = {};+ Object.keys(fields).forEach(fieldName => {+ const field = fields[fieldName];+ const rewiredFieldType = rewireType(field.type);+ if (rewiredFieldType != null) {+ field.type = rewiredFieldType;+ rewiredFields[fieldName] = field;+ }+ });+ return rewiredFields;+ }+ function rewireNamedTypes(namedTypes) {+ const rewiredTypes = [];+ namedTypes.forEach(namedType => {+ const rewiredType = rewireType(namedType);+ if (rewiredType != null) {+ rewiredTypes.push(rewiredType);+ }+ });+ return rewiredTypes;+ }+ function rewireType(type) {+ if (isListType(type)) {+ const rewiredType = rewireType(type.ofType);+ return rewiredType != null ? new GraphQLList(rewiredType) : null;+ }+ else if (isNonNullType(type)) {+ const rewiredType = rewireType(type.ofType);+ return rewiredType != null ? new GraphQLNonNull(rewiredType) : null;+ }+ else if (isNamedType(type)) {+ let rewiredType = referenceTypeMap[type.name];+ if (rewiredType === undefined) {+ rewiredType = isNamedStub(type) ? getBuiltInForStub(type) : rewireNamedType(type);+ newTypeMap[rewiredType.name] = referenceTypeMap[type.name] = rewiredType;+ }+ return rewiredType != null ? newTypeMap[rewiredType.name] : null;+ }+ return null;+ }+}+// TODO:+// consider removing the default level of pruning in v7+//+// Pruning during mapSchema limits the ability to create an unpruned schema, which may be of use+// to some library users. pruning is now recommended via the dedicated pruneSchema function+// which does not force pruning on library users and gives granular control in terms of pruning+// types.+function pruneTypes(typeMap, directives) {+ const newTypeMap = {};+ const implementedInterfaces = {};+ Object.keys(typeMap).forEach(typeName => {+ const namedType = typeMap[typeName];+ if ('getInterfaces' in namedType) {+ namedType.getInterfaces().forEach(iface => {+ implementedInterfaces[iface.name] = true;+ });+ }+ });+ let prunedTypeMap = false;+ const typeNames = Object.keys(typeMap);+ for (let i = 0; i < typeNames.length; i++) {+ const typeName = typeNames[i];+ const type = typeMap[typeName];+ if (isObjectType(type) || isInputObjectType(type)) {+ // prune types with no fields+ if (Object.keys(type.getFields()).length) {+ newTypeMap[typeName] = type;+ }+ else {+ prunedTypeMap = true;+ }+ }+ else if (isUnionType(type)) {+ // prune unions without underlying types+ if (type.getTypes().length) {+ newTypeMap[typeName] = type;+ }+ else {+ prunedTypeMap = true;+ }+ }+ else if (isInterfaceType(type)) {+ // prune interfaces without fields or without implementations+ if (Object.keys(type.getFields()).length && implementedInterfaces[type.name]) {+ newTypeMap[typeName] = type;+ }+ else {+ prunedTypeMap = true;+ }+ }+ else {+ newTypeMap[typeName] = type;+ }+ }+ // every prune requires another round of healing+ return prunedTypeMap ? rewireTypes(newTypeMap, directives) : { typeMap, directives };+}++function transformInputValue(type, value, transformer) {+ if (value == null) {+ return value;+ }+ const nullableType = getNullableType(type);+ if (isLeafType(nullableType)) {+ return transformer(nullableType, value);+ }+ else if (isListType(nullableType)) {+ return value.map((listMember) => transformInputValue(nullableType.ofType, listMember, transformer));+ }+ else if (isInputObjectType(nullableType)) {+ const fields = nullableType.getFields();+ const newValue = {};+ Object.keys(value).forEach(key => {+ newValue[key] = transformInputValue(fields[key].type, value[key], transformer);+ });+ return newValue;+ }+ // unreachable, no other possible return value+}+function serializeInputValue(type, value) {+ return transformInputValue(type, value, (t, v) => t.serialize(v));+}+function parseInputValue(type, value) {+ return transformInputValue(type, value, (t, v) => t.parseValue(v));+}++function mapSchema(schema, schemaMapper = {}) {+ const originalTypeMap = schema.getTypeMap();+ let newTypeMap = mapDefaultValues(originalTypeMap, schema, serializeInputValue);+ newTypeMap = mapTypes(newTypeMap, schema, schemaMapper, type => isLeafType(type));+ newTypeMap = mapEnumValues(newTypeMap, schema, schemaMapper);+ newTypeMap = mapDefaultValues(newTypeMap, schema, parseInputValue);+ newTypeMap = mapTypes(newTypeMap, schema, schemaMapper, type => !isLeafType(type));+ newTypeMap = mapFields(newTypeMap, schema, schemaMapper);+ newTypeMap = mapArguments(newTypeMap, schema, schemaMapper);+ const originalDirectives = schema.getDirectives();+ const newDirectives = mapDirectives(originalDirectives, schema, schemaMapper);+ const queryType = schema.getQueryType();+ const mutationType = schema.getMutationType();+ const subscriptionType = schema.getSubscriptionType();+ const newQueryTypeName = queryType != null ? (newTypeMap[queryType.name] != null ? newTypeMap[queryType.name].name : undefined) : undefined;+ const newMutationTypeName = mutationType != null+ ? newTypeMap[mutationType.name] != null+ ? newTypeMap[mutationType.name].name+ : undefined+ : undefined;+ const newSubscriptionTypeName = subscriptionType != null+ ? newTypeMap[subscriptionType.name] != null+ ? newTypeMap[subscriptionType.name].name+ : undefined+ : undefined;+ const { typeMap, directives } = rewireTypes(newTypeMap, newDirectives);+ return new GraphQLSchema({+ ...schema.toConfig(),+ query: newQueryTypeName ? typeMap[newQueryTypeName] : undefined,+ mutation: newMutationTypeName ? typeMap[newMutationTypeName] : undefined,+ subscription: newSubscriptionTypeName != null ? typeMap[newSubscriptionTypeName] : undefined,+ types: Object.keys(typeMap).map(typeName => typeMap[typeName]),+ directives,+ });+}+function mapTypes(originalTypeMap, schema, schemaMapper, testFn = () => true) {+ const newTypeMap = {};+ Object.keys(originalTypeMap).forEach(typeName => {+ if (!typeName.startsWith('__')) {+ const originalType = originalTypeMap[typeName];+ if (originalType == null || !testFn(originalType)) {+ newTypeMap[typeName] = originalType;+ return;+ }+ const typeMapper = getTypeMapper(schema, schemaMapper, typeName);+ if (typeMapper == null) {+ newTypeMap[typeName] = originalType;+ return;+ }+ const maybeNewType = typeMapper(originalType, schema);+ if (maybeNewType === undefined) {+ newTypeMap[typeName] = originalType;+ return;+ }+ newTypeMap[typeName] = maybeNewType;+ }+ });+ return newTypeMap;+}+function mapEnumValues(originalTypeMap, schema, schemaMapper) {+ const enumValueMapper = getEnumValueMapper(schemaMapper);+ if (!enumValueMapper) {+ return originalTypeMap;+ }+ return mapTypes(originalTypeMap, schema, {+ [MapperKind.ENUM_TYPE]: type => {+ const config = type.toConfig();+ const originalEnumValueConfigMap = config.values;+ const newEnumValueConfigMap = {};+ Object.keys(originalEnumValueConfigMap).forEach(externalValue => {+ const originalEnumValueConfig = originalEnumValueConfigMap[externalValue];+ const mappedEnumValue = enumValueMapper(originalEnumValueConfig, type.name, schema, externalValue);+ if (mappedEnumValue === undefined) {+ newEnumValueConfigMap[externalValue] = originalEnumValueConfig;+ }+ else if (Array.isArray(mappedEnumValue)) {+ const [newExternalValue, newEnumValueConfig] = mappedEnumValue;+ newEnumValueConfigMap[newExternalValue] =+ newEnumValueConfig === undefined ? originalEnumValueConfig : newEnumValueConfig;+ }+ else if (mappedEnumValue !== null) {+ newEnumValueConfigMap[externalValue] = mappedEnumValue;+ }+ });+ return correctASTNodes(new GraphQLEnumType({+ ...config,+ values: newEnumValueConfigMap,+ }));+ },+ }, type => isEnumType(type));+}+function mapDefaultValues(originalTypeMap, schema, fn) {+ const newTypeMap = mapArguments(originalTypeMap, schema, {+ [MapperKind.ARGUMENT]: argumentConfig => {+ if (argumentConfig.defaultValue === undefined) {+ return argumentConfig;+ }+ const maybeNewType = getNewType(originalTypeMap, argumentConfig.type);+ if (maybeNewType != null) {+ return {+ ...argumentConfig,+ defaultValue: fn(maybeNewType, argumentConfig.defaultValue),+ };+ }+ },+ });+ return mapFields(newTypeMap, schema, {+ [MapperKind.INPUT_OBJECT_FIELD]: inputFieldConfig => {+ if (inputFieldConfig.defaultValue === undefined) {+ return inputFieldConfig;+ }+ const maybeNewType = getNewType(newTypeMap, inputFieldConfig.type);+ if (maybeNewType != null) {+ return {+ ...inputFieldConfig,+ defaultValue: fn(maybeNewType, inputFieldConfig.defaultValue),+ };+ }+ },+ });+}+function getNewType(newTypeMap, type) {+ if (isListType(type)) {+ const newType = getNewType(newTypeMap, type.ofType);+ return newType != null ? new GraphQLList(newType) : null;+ }+ else if (isNonNullType(type)) {+ const newType = getNewType(newTypeMap, type.ofType);+ return newType != null ? new GraphQLNonNull(newType) : null;+ }+ else if (isNamedType(type)) {+ const newType = newTypeMap[type.name];+ return newType != null ? newType : null;+ }+ return null;+}+function mapFields(originalTypeMap, schema, schemaMapper) {+ const newTypeMap = {};+ Object.keys(originalTypeMap).forEach(typeName => {+ if (!typeName.startsWith('__')) {+ const originalType = originalTypeMap[typeName];+ if (!isObjectType(originalType) && !isInterfaceType(originalType) && !isInputObjectType(originalType)) {+ newTypeMap[typeName] = originalType;+ return;+ }+ const fieldMapper = getFieldMapper(schema, schemaMapper, typeName);+ if (fieldMapper == null) {+ newTypeMap[typeName] = originalType;+ return;+ }+ const config = originalType.toConfig();+ const originalFieldConfigMap = config.fields;+ const newFieldConfigMap = {};+ Object.keys(originalFieldConfigMap).forEach(fieldName => {+ const originalFieldConfig = originalFieldConfigMap[fieldName];+ const mappedField = fieldMapper(originalFieldConfig, fieldName, typeName, schema);+ if (mappedField === undefined) {+ newFieldConfigMap[fieldName] = originalFieldConfig;+ }+ else if (Array.isArray(mappedField)) {+ const [newFieldName, newFieldConfig] = mappedField;+ if (newFieldConfig.astNode != null) {+ newFieldConfig.astNode = {+ ...newFieldConfig.astNode,+ name: {+ ...newFieldConfig.astNode.name,+ value: newFieldName,+ },+ };+ }+ newFieldConfigMap[newFieldName] = newFieldConfig === undefined ? originalFieldConfig : newFieldConfig;+ }+ else if (mappedField !== null) {+ newFieldConfigMap[fieldName] = mappedField;+ }+ });+ if (isObjectType(originalType)) {+ newTypeMap[typeName] = correctASTNodes(new GraphQLObjectType({+ ...config,+ fields: newFieldConfigMap,+ }));+ }+ else if (isInterfaceType(originalType)) {+ newTypeMap[typeName] = correctASTNodes(new GraphQLInterfaceType({+ ...config,+ fields: newFieldConfigMap,+ }));+ }+ else {+ newTypeMap[typeName] = correctASTNodes(new GraphQLInputObjectType({+ ...config,+ fields: newFieldConfigMap,+ }));+ }+ }+ });+ return newTypeMap;+}+function mapArguments(originalTypeMap, schema, schemaMapper) {+ const newTypeMap = {};+ Object.keys(originalTypeMap).forEach(typeName => {+ if (!typeName.startsWith('__')) {+ const originalType = originalTypeMap[typeName];+ if (!isObjectType(originalType) && !isInterfaceType(originalType)) {+ newTypeMap[typeName] = originalType;+ return;+ }+ const argumentMapper = getArgumentMapper(schemaMapper);+ if (argumentMapper == null) {+ newTypeMap[typeName] = originalType;+ return;+ }+ const config = originalType.toConfig();+ const originalFieldConfigMap = config.fields;+ const newFieldConfigMap = {};+ Object.keys(originalFieldConfigMap).forEach(fieldName => {+ const originalFieldConfig = originalFieldConfigMap[fieldName];+ const originalArgumentConfigMap = originalFieldConfig.args;+ if (originalArgumentConfigMap == null) {+ newFieldConfigMap[fieldName] = originalFieldConfig;+ return;+ }+ const argumentNames = Object.keys(originalArgumentConfigMap);+ if (!argumentNames.length) {+ newFieldConfigMap[fieldName] = originalFieldConfig;+ return;+ }+ const newArgumentConfigMap = {};+ argumentNames.forEach(argumentName => {+ const originalArgumentConfig = originalArgumentConfigMap[argumentName];+ const mappedArgument = argumentMapper(originalArgumentConfig, fieldName, typeName, schema);+ if (mappedArgument === undefined) {+ newArgumentConfigMap[argumentName] = originalArgumentConfig;+ }+ else if (Array.isArray(mappedArgument)) {+ const [newArgumentName, newArgumentConfig] = mappedArgument;+ newArgumentConfigMap[newArgumentName] = newArgumentConfig;+ }+ else if (mappedArgument !== null) {+ newArgumentConfigMap[argumentName] = mappedArgument;+ }+ });+ newFieldConfigMap[fieldName] = {+ ...originalFieldConfig,+ args: newArgumentConfigMap,+ };+ });+ if (isObjectType(originalType)) {+ newTypeMap[typeName] = new GraphQLObjectType({+ ...config,+ fields: newFieldConfigMap,+ });+ }+ else if (isInterfaceType(originalType)) {+ newTypeMap[typeName] = new GraphQLInterfaceType({+ ...config,+ fields: newFieldConfigMap,+ });+ }+ else {+ newTypeMap[typeName] = new GraphQLInputObjectType({+ ...config,+ fields: newFieldConfigMap,+ });+ }+ }+ });+ return newTypeMap;+}+function mapDirectives(originalDirectives, schema, schemaMapper) {+ const directiveMapper = getDirectiveMapper(schemaMapper);+ if (directiveMapper == null) {+ return originalDirectives.slice();+ }+ const newDirectives = [];+ originalDirectives.forEach(directive => {+ const mappedDirective = directiveMapper(directive, schema);+ if (mappedDirective === undefined) {+ newDirectives.push(directive);+ }+ else if (mappedDirective !== null) {+ newDirectives.push(mappedDirective);+ }+ });+ return newDirectives;+}+function getTypeSpecifiers(schema, typeName) {+ const type = schema.getType(typeName);+ const specifiers = [MapperKind.TYPE];+ if (isObjectType(type)) {+ specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.OBJECT_TYPE);+ const query = schema.getQueryType();+ const mutation = schema.getMutationType();+ const subscription = schema.getSubscriptionType();+ if (query != null && typeName === query.name) {+ specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.QUERY);+ }+ else if (mutation != null && typeName === mutation.name) {+ specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.MUTATION);+ }+ else if (subscription != null && typeName === subscription.name) {+ specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.SUBSCRIPTION);+ }+ }+ else if (isInputObjectType(type)) {+ specifiers.push(MapperKind.INPUT_OBJECT_TYPE);+ }+ else if (isInterfaceType(type)) {+ specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.ABSTRACT_TYPE, MapperKind.INTERFACE_TYPE);+ }+ else if (isUnionType(type)) {+ specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.ABSTRACT_TYPE, MapperKind.UNION_TYPE);+ }+ else if (isEnumType(type)) {+ specifiers.push(MapperKind.ENUM_TYPE);+ }+ else if (isScalarType(type)) {+ specifiers.push(MapperKind.SCALAR_TYPE);+ }+ return specifiers;+}+function getTypeMapper(schema, schemaMapper, typeName) {+ const specifiers = getTypeSpecifiers(schema, typeName);+ let typeMapper;+ const stack = [...specifiers];+ while (!typeMapper && stack.length > 0) {+ const next = stack.pop();+ typeMapper = schemaMapper[next];+ }+ return typeMapper != null ? typeMapper : null;+}+function getFieldSpecifiers(schema, typeName) {+ const type = schema.getType(typeName);+ const specifiers = [MapperKind.FIELD];+ if (isObjectType(type)) {+ specifiers.push(MapperKind.COMPOSITE_FIELD, MapperKind.OBJECT_FIELD);+ const query = schema.getQueryType();+ const mutation = schema.getMutationType();+ const subscription = schema.getSubscriptionType();+ if (query != null && typeName === query.name) {+ specifiers.push(MapperKind.ROOT_FIELD, MapperKind.QUERY_ROOT_FIELD);+ }+ else if (mutation != null && typeName === mutation.name) {+ specifiers.push(MapperKind.ROOT_FIELD, MapperKind.MUTATION_ROOT_FIELD);+ }+ else if (subscription != null && typeName === subscription.name) {+ specifiers.push(MapperKind.ROOT_FIELD, MapperKind.SUBSCRIPTION_ROOT_FIELD);+ }+ }+ else if (isInterfaceType(type)) {+ specifiers.push(MapperKind.COMPOSITE_FIELD, MapperKind.INTERFACE_FIELD);+ }+ else if (isInputObjectType(type)) {+ specifiers.push(MapperKind.INPUT_OBJECT_FIELD);+ }+ return specifiers;+}+function getFieldMapper(schema, schemaMapper, typeName) {+ const specifiers = getFieldSpecifiers(schema, typeName);+ let fieldMapper;+ const stack = [...specifiers];+ while (!fieldMapper && stack.length > 0) {+ const next = stack.pop();+ fieldMapper = schemaMapper[next];+ }+ return fieldMapper != null ? fieldMapper : null;+}+function getArgumentMapper(schemaMapper) {+ const argumentMapper = schemaMapper[MapperKind.ARGUMENT];+ return argumentMapper != null ? argumentMapper : null;+}+function getDirectiveMapper(schemaMapper) {+ const directiveMapper = schemaMapper[MapperKind.DIRECTIVE];+ return directiveMapper != null ? directiveMapper : null;+}+function getEnumValueMapper(schemaMapper) {+ const enumValueMapper = schemaMapper[MapperKind.ENUM_VALUE];+ return enumValueMapper != null ? enumValueMapper : null;+}+function correctASTNodes(type) {+ if (isObjectType(type)) {+ const config = type.toConfig();+ if (config.astNode != null) {+ const fields = [];+ Object.values(config.fields).forEach(fieldConfig => {+ if (fieldConfig.astNode != null) {+ fields.push(fieldConfig.astNode);+ }+ });+ config.astNode = {+ ...config.astNode,+ kind: Kind.OBJECT_TYPE_DEFINITION,+ fields,+ };+ }+ if (config.extensionASTNodes != null) {+ config.extensionASTNodes = config.extensionASTNodes.map(node => ({+ ...node,+ kind: Kind.OBJECT_TYPE_EXTENSION,+ fields: undefined,+ }));+ }+ return new GraphQLObjectType(config);+ }+ else if (isInterfaceType(type)) {+ const config = type.toConfig();+ if (config.astNode != null) {+ const fields = [];+ Object.values(config.fields).forEach(fieldConfig => {+ if (fieldConfig.astNode != null) {+ fields.push(fieldConfig.astNode);+ }+ });+ config.astNode = {+ ...config.astNode,+ kind: Kind.INTERFACE_TYPE_DEFINITION,+ fields,+ };+ }+ if (config.extensionASTNodes != null) {+ config.extensionASTNodes = config.extensionASTNodes.map(node => ({+ ...node,+ kind: Kind.INTERFACE_TYPE_EXTENSION,+ fields: undefined,+ }));+ }+ return new GraphQLInterfaceType(config);+ }+ else if (isInputObjectType(type)) {+ const config = type.toConfig();+ if (config.astNode != null) {+ const fields = [];+ Object.values(config.fields).forEach(fieldConfig => {+ if (fieldConfig.astNode != null) {+ fields.push(fieldConfig.astNode);+ }+ });+ config.astNode = {+ ...config.astNode,+ kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,+ fields,+ };+ }+ if (config.extensionASTNodes != null) {+ config.extensionASTNodes = config.extensionASTNodes.map(node => ({+ ...node,+ kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,+ fields: undefined,+ }));+ }+ return new GraphQLInputObjectType(config);+ }+ else if (isEnumType(type)) {+ const config = type.toConfig();+ if (config.astNode != null) {+ const values = [];+ Object.values(config.values).forEach(enumValueConfig => {+ if (enumValueConfig.astNode != null) {+ values.push(enumValueConfig.astNode);+ }+ });+ config.astNode = {+ ...config.astNode,+ values,+ };+ }+ if (config.extensionASTNodes != null) {+ config.extensionASTNodes = config.extensionASTNodes.map(node => ({+ ...node,+ values: undefined,+ }));+ }+ return new GraphQLEnumType(config);+ }+ else {+ return type;+ }+}+function cloneType(type) {+ if (isObjectType(type)) {+ const config = type.toConfig();+ return new GraphQLObjectType({+ ...config,+ interfaces: typeof config.interfaces === 'function' ? config.interfaces : config.interfaces.slice(),+ });+ }+ else if (isInterfaceType(type)) {+ const config = type.toConfig();+ const newConfig = {+ ...config,+ interfaces: [...((typeof config.interfaces === 'function' ? config.interfaces() : config.interfaces) || [])],+ };+ return new GraphQLInterfaceType(newConfig);+ }+ else if (isUnionType(type)) {+ const config = type.toConfig();+ return new GraphQLUnionType({+ ...config,+ types: config.types.slice(),+ });+ }+ else if (isInputObjectType(type)) {+ return new GraphQLInputObjectType(type.toConfig());+ }+ else if (isEnumType(type)) {+ return new GraphQLEnumType(type.toConfig());+ }+ else if (isScalarType(type)) {+ return isSpecifiedScalarType(type) ? type : new GraphQLScalarType(type.toConfig());+ }+ throw new Error(`Invalid type ${type}`);+}+function cloneSchema(schema) {+ return mapSchema(schema);+}++// Update any references to named schema types that disagree with the named+// types found in schema.getTypeMap().+//+// healSchema and its callers (visitSchema/visitSchemaDirectives) all modify the schema in place.+// Therefore, private variables (such as the stored implementation map and the proper root types)+// are not updated.+//+// If this causes issues, the schema could be more aggressively healed as follows:+//+// healSchema(schema);+// const config = schema.toConfig()+// const healedSchema = new GraphQLSchema({+// ...config,+// query: schema.getType('<desired new root query type name>'),+// mutation: schema.getType('<desired new root mutation type name>'),+// subscription: schema.getType('<desired new root subscription type name>'),+// });+//+// One can then also -- if necessary -- assign the correct private variables to the initial schema+// as follows:+// Object.assign(schema, healedSchema);+//+// These steps are not taken automatically to preserve backwards compatibility with graphql-tools v4.+// See https://github.com/ardatan/graphql-tools/issues/1462+//+// They were briefly taken in v5, but can now be phased out as they were only required when other+// areas of the codebase were using healSchema and visitSchema more extensively.+//+function healSchema(schema) {+ healTypes(schema.getTypeMap(), schema.getDirectives());+ return schema;+}+function healTypes(originalTypeMap, directives, config = {+ skipPruning: false,+}) {+ const actualNamedTypeMap = Object.create(null);+ // If any of the .name properties of the GraphQLNamedType objects in+ // schema.getTypeMap() have changed, the keys of the type map need to+ // be updated accordingly.+ Object.entries(originalTypeMap).forEach(([typeName, namedType]) => {+ if (namedType == null || typeName.startsWith('__')) {+ return;+ }+ const actualName = namedType.name;+ if (actualName.startsWith('__')) {+ return;+ }+ if (actualName in actualNamedTypeMap) {+ throw new Error(`Duplicate schema type name ${actualName}`);+ }+ actualNamedTypeMap[actualName] = namedType;+ // Note: we are deliberately leaving namedType in the schema by its+ // original name (which might be different from actualName), so that+ // references by that name can be healed.+ });+ // Now add back every named type by its actual name.+ Object.entries(actualNamedTypeMap).forEach(([typeName, namedType]) => {+ originalTypeMap[typeName] = namedType;+ });+ // Directive declaration argument types can refer to named types.+ directives.forEach((decl) => {+ decl.args = decl.args.filter(arg => {+ arg.type = healType(arg.type);+ return arg.type !== null;+ });+ });+ Object.entries(originalTypeMap).forEach(([typeName, namedType]) => {+ // Heal all named types, except for dangling references, kept only to redirect.+ if (!typeName.startsWith('__') && typeName in actualNamedTypeMap) {+ if (namedType != null) {+ healNamedType(namedType);+ }+ }+ });+ for (const typeName of Object.keys(originalTypeMap)) {+ if (!typeName.startsWith('__') && !(typeName in actualNamedTypeMap)) {+ delete originalTypeMap[typeName];+ }+ }+ if (!config.skipPruning) {+ // TODO:+ // consider removing the default level of pruning in v7,+ // see comments below on the pruneTypes function.+ pruneTypes$1(originalTypeMap, directives);+ }+ function healNamedType(type) {+ if (isObjectType(type)) {+ healFields(type);+ healInterfaces(type);+ return;+ }+ else if (isInterfaceType(type)) {+ healFields(type);+ if ('getInterfaces' in type) {+ healInterfaces(type);+ }+ return;+ }+ else if (isUnionType(type)) {+ healUnderlyingTypes(type);+ return;+ }+ else if (isInputObjectType(type)) {+ healInputFields(type);+ return;+ }+ else if (isLeafType(type)) {+ return;+ }+ throw new Error(`Unexpected schema type: ${type}`);+ }+ function healFields(type) {+ const fieldMap = type.getFields();+ for (const [key, field] of Object.entries(fieldMap)) {+ field.args+ .map(arg => {+ arg.type = healType(arg.type);+ return arg.type === null ? null : arg;+ })+ .filter(Boolean);+ field.type = healType(field.type);+ if (field.type === null) {+ delete fieldMap[key];+ }+ }+ }+ function healInterfaces(type) {+ if ('getInterfaces' in type) {+ const interfaces = type.getInterfaces();+ interfaces.push(...interfaces+ .splice(0)+ .map(iface => healType(iface))+ .filter(Boolean));+ }+ }+ function healInputFields(type) {+ const fieldMap = type.getFields();+ for (const [key, field] of Object.entries(fieldMap)) {+ field.type = healType(field.type);+ if (field.type === null) {+ delete fieldMap[key];+ }+ }+ }+ function healUnderlyingTypes(type) {+ const types = type.getTypes();+ types.push(...types+ .splice(0)+ .map(t => healType(t))+ .filter(Boolean));+ }+ function healType(type) {+ // Unwrap the two known wrapper types+ if (isListType(type)) {+ const healedType = healType(type.ofType);+ return healedType != null ? new GraphQLList(healedType) : null;+ }+ else if (isNonNullType(type)) {+ const healedType = healType(type.ofType);+ return healedType != null ? new GraphQLNonNull(healedType) : null;+ }+ else if (isNamedType(type)) {+ // If a type annotation on a field or an argument or a union member is+ // any `GraphQLNamedType` with a `name`, then it must end up identical+ // to `schema.getType(name)`, since `schema.getTypeMap()` is the source+ // of truth for all named schema types.+ // Note that new types can still be simply added by adding a field, as+ // the official type will be undefined, not null.+ const officialType = originalTypeMap[type.name];+ if (officialType && type !== officialType) {+ return officialType;+ }+ }+ return type;+ }+}+// TODO:+// consider removing the default level of pruning in v7+//+// Pruning was introduced into healSchema in v5, so legacy schema directives relying on pruning+// during healing are likely to be rare. pruning is now recommended via the dedicated pruneSchema+// function which does not force pruning on library users and gives granular control in terms of+// pruning types. pruneSchema does recreate the schema -- a parallel version that prunes in place+// could be considered.+function pruneTypes$1(typeMap, directives) {+ const implementedInterfaces = {};+ Object.values(typeMap).forEach(namedType => {+ if ('getInterfaces' in namedType) {+ namedType.getInterfaces().forEach(iface => {+ implementedInterfaces[iface.name] = true;+ });+ }+ });+ let prunedTypeMap = false;+ const typeNames = Object.keys(typeMap);+ for (let i = 0; i < typeNames.length; i++) {+ const typeName = typeNames[i];+ const type = typeMap[typeName];+ if (isObjectType(type) || isInputObjectType(type)) {+ // prune types with no fields+ if (!Object.keys(type.getFields()).length) {+ typeMap[typeName] = null;+ prunedTypeMap = true;+ }+ }+ else if (isUnionType(type)) {+ // prune unions without underlying types+ if (!type.getTypes().length) {+ typeMap[typeName] = null;+ prunedTypeMap = true;+ }+ }+ else if (isInterfaceType(type)) {+ // prune interfaces without fields or without implementations+ if (!Object.keys(type.getFields()).length || !(type.name in implementedInterfaces)) {+ typeMap[typeName] = null;+ prunedTypeMap = true;+ }+ }+ }+ // every prune requires another round of healing+ if (prunedTypeMap) {+ healTypes(typeMap, directives);+ }+}++// Abstract base class of any visitor implementation, defining the available+// visitor methods along with their parameter types, and providing a static+// helper function for determining whether a subclass implements a given+// visitor method, as opposed to inheriting one of the stubs defined here.+class SchemaVisitor {+ // Determine if this SchemaVisitor (sub)class implements a particular+ // visitor method.+ static implementsVisitorMethod(methodName) {+ if (!methodName.startsWith('visit')) {+ return false;+ }+ const method = this.prototype[methodName];+ if (typeof method !== 'function') {+ return false;+ }+ if (this.name === 'SchemaVisitor') {+ // The SchemaVisitor class implements every visitor method.+ return true;+ }+ const stub = SchemaVisitor.prototype[methodName];+ if (method === stub) {+ // If this.prototype[methodName] was just inherited from SchemaVisitor,+ // then this class does not really implement the method.+ return false;+ }+ return true;+ }+ // Concrete subclasses of SchemaVisitor should override one or more of these+ // visitor methods, in order to express their interest in handling certain+ // schema types/locations. Each method may return null to remove the given+ // type from the schema, a non-null value of the same type to update the+ // type in the schema, or nothing to leave the type as it was.+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ visitSchema(_schema) { }+ visitScalar(_scalar+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ ) { }+ visitObject(_object+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ ) { }+ visitFieldDefinition(_field, _details+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ ) { }+ visitArgumentDefinition(_argument, _details+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ ) { }+ visitInterface(_iface+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ ) { }+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ visitUnion(_union) { }+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ visitEnum(_type) { }+ visitEnumValue(_value, _details+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ ) { }+ visitInputObject(_object+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ ) { }+ visitInputFieldDefinition(_field, _details+ // eslint-disable-next-line @typescript-eslint/no-empty-function+ ) { }+}++function isSchemaVisitor(obj) {+ if ('schema' in obj && isSchema(obj.schema)) {+ if ('visitSchema' in obj && typeof obj.visitSchema === 'function') {+ return true;+ }+ }+ return false;+}+// Generic function for visiting GraphQLSchema objects.+function visitSchema(schema, +// To accommodate as many different visitor patterns as possible, the+// visitSchema function does not simply accept a single instance of the+// SchemaVisitor class, but instead accepts a function that takes the+// current VisitableSchemaType object and the name of a visitor method and+// returns an array of SchemaVisitor instances that implement the visitor+// method and have an interest in handling the given VisitableSchemaType+// object. In the simplest case, this function can always return an array+// containing a single visitor object, without even looking at the type or+// methodName parameters. In other cases, this function might sometimes+// return an empty array to indicate there are no visitors that should be+// applied to the given VisitableSchemaType object. For an example of a+// visitor pattern that benefits from this abstraction, see the+// SchemaDirectiveVisitor class below.+visitorOrVisitorSelector) {+ const visitorSelector = typeof visitorOrVisitorSelector === 'function' ? visitorOrVisitorSelector : () => visitorOrVisitorSelector;+ // Helper function that calls visitorSelector and applies the resulting+ // visitors to the given type, with arguments [type, ...args].+ function callMethod(methodName, type, ...args) {+ let visitors = visitorSelector(type, methodName);+ visitors = Array.isArray(visitors) ? visitors : [visitors];+ let finalType = type;+ visitors.every(visitorOrVisitorDef => {+ let newType;+ if (isSchemaVisitor(visitorOrVisitorDef)) {+ newType = visitorOrVisitorDef[methodName](finalType, ...args);+ }+ else if (isNamedType(finalType) &&+ (methodName === 'visitScalar' ||+ methodName === 'visitEnum' ||+ methodName === 'visitObject' ||+ methodName === 'visitInputObject' ||+ methodName === 'visitUnion' ||+ methodName === 'visitInterface')) {+ const specifiers = getTypeSpecifiers$1(finalType, schema);+ const typeVisitor = getVisitor(visitorOrVisitorDef, specifiers);+ newType = typeVisitor != null ? typeVisitor(finalType, schema) : undefined;+ }+ if (typeof newType === 'undefined') {+ // Keep going without modifying type.+ return true;+ }+ if (methodName === 'visitSchema' || isSchema(finalType)) {+ throw new Error(`Method ${methodName} cannot replace schema with ${newType}`);+ }+ if (newType === null) {+ // Stop the loop and return null form callMethod, which will cause+ // the type to be removed from the schema.+ finalType = null;+ return false;+ }+ // Update type to the new type returned by the visitor method, so that+ // later directives will see the new type, and callMethod will return+ // the final type.+ finalType = newType;+ return true;+ });+ // If there were no directives for this type object, or if all visitor+ // methods returned nothing, type will be returned unmodified.+ return finalType;+ }+ // Recursive helper function that calls any appropriate visitor methods for+ // each object in the schema, then traverses the object's children (if any).+ function visit(type) {+ if (isSchema(type)) {+ // Unlike the other types, the root GraphQLSchema object cannot be+ // replaced by visitor methods, because that would make life very hard+ // for SchemaVisitor subclasses that rely on the original schema object.+ callMethod('visitSchema', type);+ const typeMap = type.getTypeMap();+ Object.entries(typeMap).forEach(([typeName, namedType]) => {+ if (!typeName.startsWith('__') && namedType != null) {+ // Call visit recursively to let it determine which concrete+ // subclass of GraphQLNamedType we found in the type map.+ // We do not use updateEachKey because we want to preserve+ // deleted types in the typeMap so that other types that reference+ // the deleted types can be healed.+ typeMap[typeName] = visit(namedType);+ }+ });+ return type;+ }+ if (isObjectType(type)) {+ // Note that callMethod('visitObject', type) may not actually call any+ // methods, if there are no @directive annotations associated with this+ // type, or if this SchemaDirectiveVisitor subclass does not override+ // the visitObject method.+ const newObject = callMethod('visitObject', type);+ if (newObject != null) {+ visitFields(newObject);+ }+ return newObject;+ }+ if (isInterfaceType(type)) {+ const newInterface = callMethod('visitInterface', type);+ if (newInterface != null) {+ visitFields(newInterface);+ }+ return newInterface;+ }+ if (isInputObjectType(type)) {+ const newInputObject = callMethod('visitInputObject', type);+ if (newInputObject != null) {+ const fieldMap = newInputObject.getFields();+ for (const key of Object.keys(fieldMap)) {+ fieldMap[key] = callMethod('visitInputFieldDefinition', fieldMap[key], {+ // Since we call a different method for input object fields, we+ // can't reuse the visitFields function here.+ objectType: newInputObject,+ });+ if (!fieldMap[key]) {+ delete fieldMap[key];+ }+ }+ }+ return newInputObject;+ }+ if (isScalarType(type)) {+ return callMethod('visitScalar', type);+ }+ if (isUnionType(type)) {+ return callMethod('visitUnion', type);+ }+ if (isEnumType(type)) {+ let newEnum = callMethod('visitEnum', type);+ if (newEnum != null) {+ const newValues = newEnum+ .getValues()+ .map(value => callMethod('visitEnumValue', value, {+ enumType: newEnum,+ }))+ .filter(Boolean);+ // Recreate the enum type if any of the values changed+ const valuesUpdated = newValues.some((value, index) => value !== newEnum.getValues()[index]);+ if (valuesUpdated) {+ newEnum = new GraphQLEnumType({+ ...newEnum.toConfig(),+ values: newValues.reduce((prev, value) => ({+ ...prev,+ [value.name]: {+ value: value.value,+ deprecationReason: value.deprecationReason,+ description: value.description,+ astNode: value.astNode,+ },+ }), {}),+ });+ }+ }+ return newEnum;+ }+ throw new Error(`Unexpected schema type: ${type}`);+ }+ function visitFields(type) {+ const fieldMap = type.getFields();+ for (const [key, field] of Object.entries(fieldMap)) {+ // It would be nice if we could call visit(field) recursively here, but+ // GraphQLField is merely a type, not a value that can be detected using+ // an instanceof check, so we have to visit the fields in this lexical+ // context, so that TypeScript can validate the call to+ // visitFieldDefinition.+ const newField = callMethod('visitFieldDefinition', field, {+ // While any field visitor needs a reference to the field object, some+ // field visitors may also need to know the enclosing (parent) type,+ // perhaps to determine if the parent is a GraphQLObjectType or a+ // GraphQLInterfaceType. To obtain a reference to the parent, a+ // visitor method can have a second parameter, which will be an object+ // with an .objectType property referring to the parent.+ objectType: type,+ });+ if (newField.args != null) {+ newField.args = newField.args+ .map(arg => callMethod('visitArgumentDefinition', arg, {+ // Like visitFieldDefinition, visitArgumentDefinition takes a+ // second parameter that provides additional context, namely the+ // parent .field and grandparent .objectType. Remember that the+ // current GraphQLSchema is always available via this.schema.+ field: newField,+ objectType: type,+ }))+ .filter(Boolean);+ }+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ if (newField) {+ fieldMap[key] = newField;+ }+ else {+ delete fieldMap[key];+ }+ }+ }+ visit(schema);+ // Automatically update any references to named schema types replaced+ // during the traversal, so implementors don't have to worry about that.+ healSchema(schema);+ // Return schema for convenience, even though schema parameter has all updated types.+ return schema;+}+function getTypeSpecifiers$1(type, schema) {+ const specifiers = [VisitSchemaKind.TYPE];+ if (isObjectType(type)) {+ specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.OBJECT_TYPE);+ const query = schema.getQueryType();+ const mutation = schema.getMutationType();+ const subscription = schema.getSubscriptionType();+ if (type === query) {+ specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.QUERY);+ }+ else if (type === mutation) {+ specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.MUTATION);+ }+ else if (type === subscription) {+ specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.SUBSCRIPTION);+ }+ }+ else if (isInputType(type)) {+ specifiers.push(VisitSchemaKind.INPUT_OBJECT_TYPE);+ }+ else if (isInterfaceType(type)) {+ specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.ABSTRACT_TYPE, VisitSchemaKind.INTERFACE_TYPE);+ }+ else if (isUnionType(type)) {+ specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.ABSTRACT_TYPE, VisitSchemaKind.UNION_TYPE);+ }+ else if (isEnumType(type)) {+ specifiers.push(VisitSchemaKind.ENUM_TYPE);+ }+ else if (isScalarType(type)) {+ specifiers.push(VisitSchemaKind.SCALAR_TYPE);+ }+ return specifiers;+}+function getVisitor(visitorDef, specifiers) {+ let typeVisitor;+ const stack = [...specifiers];+ while (!typeVisitor && stack.length > 0) {+ const next = stack.pop();+ typeVisitor = visitorDef[next];+ }+ return typeVisitor != null ? typeVisitor : null;+}++// This class represents a reusable implementation of a @directive that may+// appear in a GraphQL schema written in Schema Definition Language.+//+// By overriding one or more visit{Object,Union,...} methods, a subclass+// registers interest in certain schema types, such as GraphQLObjectType,+// GraphQLUnionType, etc. When SchemaDirectiveVisitor.visitSchemaDirectives is+// called with a GraphQLSchema object and a map of visitor subclasses, the+// overidden methods of those subclasses allow the visitors to obtain+// references to any type objects that have @directives attached to them,+// enabling visitors to inspect or modify the schema as appropriate.+//+// For example, if a directive called @rest(url: "...") appears after a field+// definition, a SchemaDirectiveVisitor subclass could provide meaning to that+// directive by overriding the visitFieldDefinition method (which receives a+// GraphQLField parameter), and then the body of that visitor method could+// manipulate the field's resolver function to fetch data from a REST endpoint+// described by the url argument passed to the @rest directive:+//+// const typeDefs = `+// type Query {+// people: [Person] @rest(url: "/api/v1/people")+// }`;+//+// const schema = makeExecutableSchema({ typeDefs });+//+// SchemaDirectiveVisitor.visitSchemaDirectives(schema, {+// rest: class extends SchemaDirectiveVisitor {+// public visitFieldDefinition(field: GraphQLField<any, any>) {+// const { url } = this.args;+// field.resolve = () => fetch(url);+// }+// }+// });+//+// The subclass in this example is defined as an anonymous class expression,+// for brevity. A truly reusable SchemaDirectiveVisitor would most likely be+// defined in a library using a named class declaration, and then exported for+// consumption by other modules and packages.+//+// See below for a complete list of overridable visitor methods, their+// parameter types, and more details about the properties exposed by instances+// of the SchemaDirectiveVisitor class.+class SchemaDirectiveVisitor extends SchemaVisitor {+ // Mark the constructor protected to enforce passing SchemaDirectiveVisitor+ // subclasses (not instances) to visitSchemaDirectives.+ constructor(config) {+ super();+ this.name = config.name;+ this.args = config.args;+ this.visitedType = config.visitedType;+ this.schema = config.schema;+ this.context = config.context;+ }+ // Override this method to return a custom GraphQLDirective (or modify one+ // already present in the schema) to enforce argument types, provide default+ // argument values, or specify schema locations where this @directive may+ // appear. By default, any declaration found in the schema will be returned.+ static getDirectiveDeclaration(directiveName, schema) {+ return schema.getDirective(directiveName);+ }+ // Call SchemaDirectiveVisitor.visitSchemaDirectives to visit every+ // @directive in the schema and create an appropriate SchemaDirectiveVisitor+ // instance to visit the object decorated by the @directive.+ static visitSchemaDirectives(schema, + // The keys of this object correspond to directive names as they appear+ // in the schema, and the values should be subclasses (not instances!)+ // of the SchemaDirectiveVisitor class. This distinction is important+ // because a new SchemaDirectiveVisitor instance will be created each+ // time a matching directive is found in the schema AST, with arguments+ // and other metadata specific to that occurrence. To help prevent the+ // mistake of passing instances, the SchemaDirectiveVisitor constructor+ // method is marked as protected.+ directiveVisitors, + // Optional context object that will be available to all visitor instances+ // via this.context. Defaults to an empty null-prototype object.+ context = Object.create(null)+ // The visitSchemaDirectives method returns a map from directive names to+ // lists of SchemaDirectiveVisitors created while visiting the schema.+ ) {+ // If the schema declares any directives for public consumption, record+ // them here so that we can properly coerce arguments when/if we encounter+ // an occurrence of the directive while walking the schema below.+ const declaredDirectives = this.getDeclaredDirectives(schema, directiveVisitors);+ // Map from directive names to lists of SchemaDirectiveVisitor instances+ // created while visiting the schema.+ const createdVisitors = Object.keys(directiveVisitors).reduce((prev, item) => ({+ ...prev,+ [item]: [],+ }), {});+ const directiveVisitorMap = Object.entries(directiveVisitors).reduce((prev, [key, value]) => ({+ ...prev,+ [key]: value,+ }), {});+ function visitorSelector(type, methodName) {+ var _a, _b;+ let directiveNodes = (_b = (_a = type === null || type === void 0 ? void 0 : type.astNode) === null || _a === void 0 ? void 0 : _a.directives) !== null && _b !== void 0 ? _b : [];+ const extensionASTNodes = type.extensionASTNodes;+ if (extensionASTNodes != null) {+ extensionASTNodes.forEach(extensionASTNode => {+ if (extensionASTNode.directives != null) {+ directiveNodes = directiveNodes.concat(extensionASTNode.directives);+ }+ });+ }+ const visitors = [];+ directiveNodes.forEach(directiveNode => {+ const directiveName = directiveNode.name.value;+ if (!(directiveName in directiveVisitorMap)) {+ return;+ }+ const VisitorClass = directiveVisitorMap[directiveName];+ // Avoid creating visitor objects if visitorClass does not override+ // the visitor method named by methodName.+ if (!VisitorClass.implementsVisitorMethod(methodName)) {+ return;+ }+ const decl = declaredDirectives[directiveName];+ let args;+ if (decl != null) {+ // If this directive was explicitly declared, use the declared+ // argument types (and any default values) to check, coerce, and/or+ // supply default values for the given arguments.+ args = getArgumentValues$1(decl, directiveNode);+ }+ else {+ // If this directive was not explicitly declared, just convert the+ // argument nodes to their corresponding JavaScript values.+ args = Object.create(null);+ if (directiveNode.arguments != null) {+ directiveNode.arguments.forEach(arg => {+ args[arg.name.value] = valueFromASTUntyped(arg.value);+ });+ }+ }+ // As foretold in comments near the top of the visitSchemaDirectives+ // method, this is where instances of the SchemaDirectiveVisitor class+ // get created and assigned names. While subclasses could override the+ // constructor method, the constructor is marked as protected, so+ // these are the only arguments that will ever be passed.+ visitors.push(new VisitorClass({+ name: directiveName,+ args,+ visitedType: type,+ schema,+ context,+ }));+ });+ if (visitors.length > 0) {+ visitors.forEach(visitor => {+ createdVisitors[visitor.name].push(visitor);+ });+ }+ return visitors;+ }+ visitSchema(schema, visitorSelector);+ return createdVisitors;+ }+ static getDeclaredDirectives(schema, directiveVisitors) {+ const declaredDirectives = schema.getDirectives().reduce((prev, curr) => ({+ ...prev,+ [curr.name]: curr,+ }), {});+ // If the visitor subclass overrides getDirectiveDeclaration, and it+ // returns a non-null GraphQLDirective, use that instead of any directive+ // declared in the schema itself. Reasoning: if a SchemaDirectiveVisitor+ // goes to the trouble of implementing getDirectiveDeclaration, it should+ // be able to rely on that implementation.+ Object.entries(directiveVisitors).forEach(([directiveName, visitorClass]) => {+ const decl = visitorClass.getDirectiveDeclaration(directiveName, schema);+ if (decl != null) {+ declaredDirectives[directiveName] = decl;+ }+ });+ Object.entries(declaredDirectives).forEach(([name, decl]) => {+ if (!(name in directiveVisitors)) {+ // SchemaDirectiveVisitors.visitSchemaDirectives might be called+ // multiple times with partial directiveVisitors maps, so it's not+ // necessarily an error for directiveVisitors to be missing an+ // implementation of a directive that was declared in the schema.+ return;+ }+ const visitorClass = directiveVisitors[name];+ decl.locations.forEach(loc => {+ const visitorMethodName = directiveLocationToVisitorMethodName(loc);+ if (SchemaVisitor.implementsVisitorMethod(visitorMethodName) &&+ !visitorClass.implementsVisitorMethod(visitorMethodName)) {+ // While visitor subclasses may implement extra visitor methods,+ // it's definitely a mistake if the GraphQLDirective declares itself+ // applicable to certain schema locations, and the visitor subclass+ // does not implement all the corresponding methods.+ throw new Error(`SchemaDirectiveVisitor for @${name} must implement ${visitorMethodName} method`);+ }+ });+ });+ return declaredDirectives;+ }+}+// Convert a string like "FIELD_DEFINITION" to "visitFieldDefinition".+function directiveLocationToVisitorMethodName(loc) {+ return ('visit' ++ loc.replace(/([^_]*)_?/g, (_wholeMatch, part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()));+}++function getResolversFromSchema(schema) {+ const resolvers = Object.create({});+ const typeMap = schema.getTypeMap();+ Object.keys(typeMap).forEach(typeName => {+ const type = typeMap[typeName];+ if (isScalarType(type)) {+ if (!isSpecifiedScalarType(type)) {+ resolvers[typeName] = cloneType(type);+ }+ }+ else if (isEnumType(type)) {+ resolvers[typeName] = {};+ const values = type.getValues();+ values.forEach(value => {+ resolvers[typeName][value.name] = value.value;+ });+ }+ else if (isInterfaceType(type)) {+ if (type.resolveType != null) {+ resolvers[typeName] = {+ __resolveType: type.resolveType,+ };+ }+ }+ else if (isUnionType(type)) {+ if (type.resolveType != null) {+ resolvers[typeName] = {+ __resolveType: type.resolveType,+ };+ }+ }+ else if (isObjectType(type)) {+ resolvers[typeName] = {};+ if (type.isTypeOf != null) {+ resolvers[typeName].__isTypeOf = type.isTypeOf;+ }+ const fields = type.getFields();+ Object.keys(fields).forEach(fieldName => {+ const field = fields[fieldName];+ resolvers[typeName][fieldName] = {+ resolve: field.resolve,+ subscribe: field.subscribe,+ };+ });+ }+ });+ return resolvers;+}++function forEachField(schema, fn) {+ const typeMap = schema.getTypeMap();+ Object.keys(typeMap).forEach(typeName => {+ const type = typeMap[typeName];+ // TODO: maybe have an option to include these?+ if (!getNamedType(type).name.startsWith('__') && isObjectType(type)) {+ const fields = type.getFields();+ Object.keys(fields).forEach(fieldName => {+ const field = fields[fieldName];+ fn(field, typeName, fieldName);+ });+ }+ });+}++function forEachDefaultValue(schema, fn) {+ const typeMap = schema.getTypeMap();+ Object.keys(typeMap).forEach(typeName => {+ const type = typeMap[typeName];+ if (!getNamedType(type).name.startsWith('__')) {+ if (isObjectType(type)) {+ const fields = type.getFields();+ Object.keys(fields).forEach(fieldName => {+ const field = fields[fieldName];+ field.args.forEach(arg => {+ arg.defaultValue = fn(arg.type, arg.defaultValue);+ });+ });+ }+ else if (isInputObjectType(type)) {+ const fields = type.getFields();+ Object.keys(fields).forEach(fieldName => {+ const field = fields[fieldName];+ field.defaultValue = fn(field.type, field.defaultValue);+ });+ }+ }+ });+}++/* eslint-disable @typescript-eslint/explicit-module-boundary-types */+function mergeDeep(target, ...sources) {+ if (isScalarType(target)) {+ return target;+ }+ const output = {+ ...target,+ };+ for (const source of sources) {+ if (isObject(target) && isObject(source)) {+ for (const key in source) {+ if (isObject(source[key])) {+ if (!(key in target)) {+ Object.assign(output, { [key]: source[key] });+ }+ else {+ output[key] = mergeDeep(target[key], source[key]);+ }+ }+ else {+ Object.assign(output, { [key]: source[key] });+ }+ }+ }+ }+ return output;+}+function isObject(item) {+ return item && typeof item === 'object' && !Array.isArray(item);+}+function typesContainSelectionSet(types, selectionSet) {+ const fieldMaps = types.map(type => type.getFields());+ for (const selection of selectionSet.selections) {+ if (selection.kind === Kind.FIELD) {+ const fields = fieldMaps.map(fieldMap => fieldMap[selection.name.value]).filter(field => field != null);+ if (!fields.length) {+ return false;+ }+ if (selection.selectionSet != null) {+ return typesContainSelectionSet(fields.map(field => getNamedType(field.type)), selection.selectionSet);+ }+ }+ else if (selection.kind === Kind.INLINE_FRAGMENT && selection.typeCondition.name.value === types[0].name) {+ return typesContainSelectionSet(types, selection.selectionSet);+ }+ }+ return true;+}++/**+ * Get the key under which the result of this resolver will be placed in the response JSON. Basically, just+ * resolves aliases.+ * @param info The info argument to the resolver.+ */+function getResponseKeyFromInfo(info) {+ return info.fieldNodes[0].alias != null ? info.fieldNodes[0].alias.value : info.fieldName;+}++function applySchemaTransforms(originalSchema, transforms) {+ return transforms.reduce((schema, transform) => transform.transformSchema != null ? transform.transformSchema(cloneSchema(schema)) : schema, originalSchema);+}++/**+ * Given a selectionSet, adds all of the fields in that selection to+ * the passed in map of fields, and returns it at the end.+ *+ * CollectFields requires the "runtime type" of an object. For a field which+ * returns an Interface or Union type, the "runtime type" will be the actual+ * Object type returned by that field.+ *+ * @internal+ */+function collectFields$1(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {+ for (const selection of selectionSet.selections) {+ switch (selection.kind) {+ case Kind.FIELD: {+ if (!shouldIncludeNode$1(exeContext, selection)) {+ continue;+ }+ const name = getFieldEntryKey$1(selection);+ if (!(name in fields)) {+ fields[name] = [];+ }+ fields[name].push(selection);+ break;+ }+ case Kind.INLINE_FRAGMENT: {+ if (!shouldIncludeNode$1(exeContext, selection) ||+ !doesFragmentConditionMatch$1(exeContext, selection, runtimeType)) {+ continue;+ }+ collectFields$1(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);+ break;+ }+ case Kind.FRAGMENT_SPREAD: {+ const fragName = selection.name.value;+ if (visitedFragmentNames[fragName] || !shouldIncludeNode$1(exeContext, selection)) {+ continue;+ }+ visitedFragmentNames[fragName] = true;+ const fragment = exeContext.fragments[fragName];+ if (!fragment || !doesFragmentConditionMatch$1(exeContext, fragment, runtimeType)) {+ continue;+ }+ collectFields$1(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);+ break;+ }+ }+ }+ return fields;+}+/**+ * Determines if a field should be included based on the @include and @skip+ * directives, where @skip has higher precedence than @include.+ */+function shouldIncludeNode$1(exeContext, node) {+ const skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues);+ if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {+ return false;+ }+ const include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues);+ if ((include === null || include === void 0 ? void 0 : include.if) === false) {+ return false;+ }+ return true;+}+/**+ * Determines if a fragment is applicable to the given type.+ */+function doesFragmentConditionMatch$1(exeContext, fragment, type) {+ const typeConditionNode = fragment.typeCondition;+ if (!typeConditionNode) {+ return true;+ }+ const conditionalType = typeFromAST(exeContext.schema, typeConditionNode);+ if (conditionalType === type) {+ return true;+ }+ if (isAbstractType(conditionalType)) {+ return exeContext.schema.isPossibleType(conditionalType, type);+ }+ return false;+}+/**+ * Implements the logic to compute the key of a given field's entry+ */+function getFieldEntryKey$1(node) {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition+ return node.alias ? node.alias.value : node.name.value;+}++/**+ * Given an AsyncIterable and a callback function, return an AsyncIterator+ * which produces values mapped via calling the callback function.+ */+function mapAsyncIterator$1(iterator, callback, rejectCallback) {+ let $return;+ let abruptClose;+ if (typeof iterator.return === 'function') {+ $return = iterator.return;+ abruptClose = (error) => {+ const rethrow = () => Promise.reject(error);+ return $return.call(iterator).then(rethrow, rethrow);+ };+ }+ function mapResult(result) {+ return result.done ? result : asyncMapValue$1(result.value, callback).then(iteratorResult$1, abruptClose);+ }+ let mapReject;+ if (rejectCallback) {+ // Capture rejectCallback to ensure it cannot be null.+ const reject = rejectCallback;+ mapReject = (error) => asyncMapValue$1(error, reject).then(iteratorResult$1, abruptClose);+ }+ return {+ next() {+ return iterator.next().then(mapResult, mapReject);+ },+ return() {+ return $return+ ? $return.call(iterator).then(mapResult, mapReject)+ : Promise.resolve({ value: undefined, done: true });+ },+ throw(error) {+ if (typeof iterator.throw === 'function') {+ return iterator.throw(error).then(mapResult, mapReject);+ }+ return Promise.reject(error).catch(abruptClose);+ },+ [Symbol.asyncIterator]() {+ return this;+ },+ };+}+function asyncMapValue$1(value, callback) {+ return new Promise(resolve => resolve(callback(value)));+}+function iteratorResult$1(value) {+ return { value, done: false };+}++function astFromType(type) {+ if (isNonNullType(type)) {+ const innerType = astFromType(type.ofType);+ if (innerType.kind === Kind.NON_NULL_TYPE) {+ throw new Error(`Invalid type node ${JSON.stringify(type)}. Inner type of non-null type cannot be a non-null type.`);+ }+ return {+ kind: Kind.NON_NULL_TYPE,+ type: innerType,+ };+ }+ else if (isListType(type)) {+ return {+ kind: Kind.LIST_TYPE,+ type: astFromType(type.ofType),+ };+ }+ return {+ kind: Kind.NAMED_TYPE,+ name: {+ kind: Kind.NAME,+ value: type.name,+ },+ };+}++function updateArgument(argName, argType, argumentNodes, variableDefinitionsMap, variableValues, newArg) {+ let varName;+ let numGeneratedVariables = 0;+ do {+ varName = `_v${(numGeneratedVariables++).toString()}_${argName}`;+ } while (varName in variableDefinitionsMap);+ argumentNodes[argName] = {+ kind: Kind.ARGUMENT,+ name: {+ kind: Kind.NAME,+ value: argName,+ },+ value: {+ kind: Kind.VARIABLE,+ name: {+ kind: Kind.NAME,+ value: varName,+ },+ },+ };+ variableDefinitionsMap[varName] = {+ kind: Kind.VARIABLE_DEFINITION,+ variable: {+ kind: Kind.VARIABLE,+ name: {+ kind: Kind.NAME,+ value: varName,+ },+ },+ type: astFromType(argType),+ };+ if (newArg === undefined) {+ delete variableValues[varName];+ }+ else {+ variableValues[varName] = newArg;+ }+}++function implementsAbstractType(schema, typeA, typeB) {+ if (typeA === typeB) {+ return true;+ }+ else if (isCompositeType(typeA) && isCompositeType(typeB)) {+ return doTypesOverlap(schema, typeA, typeB);+ }+ return false;+}++const ERROR_SYMBOL = Symbol('subschemaErrors');+function relocatedError(originalError, path) {+ return new GraphQLError(originalError.message, originalError.nodes, originalError.source, originalError.positions, path === null ? undefined : path === undefined ? originalError.path : path, originalError.originalError, originalError.extensions);+}+function slicedError(originalError) {+ return relocatedError(originalError, originalError.path != null ? originalError.path.slice(1) : undefined);+}+function getErrorsByPathSegment(errors) {+ const record = Object.create(null);+ errors.forEach(error => {+ if (!error.path || error.path.length < 2) {+ return;+ }+ const pathSegment = error.path[1];+ const current = pathSegment in record ? record[pathSegment] : [];+ current.push(slicedError(error));+ record[pathSegment] = current;+ });+ return record;+}+function setErrors(result, errors) {+ result[ERROR_SYMBOL] = errors;+}+function getErrors(result, pathSegment) {+ const errors = result != null ? result[ERROR_SYMBOL] : result;+ if (!Array.isArray(errors)) {+ return null;+ }+ const fieldErrors = [];+ for (const error of errors) {+ if (!error.path || error.path[0] === pathSegment) {+ fieldErrors.push(error);+ }+ }+ return fieldErrors;+}++function observableToAsyncIterable(observable) {+ const pullQueue = [];+ const pushQueue = [];+ let listening = true;+ const pushValue = (value) => {+ if (pullQueue.length !== 0) {+ pullQueue.shift()({ value, done: false });+ }+ else {+ pushQueue.push({ value });+ }+ };+ const pushError = (error) => {+ if (pullQueue.length !== 0) {+ pullQueue.shift()({ value: { errors: [error] }, done: false });+ }+ else {+ pushQueue.push({ value: { errors: [error] } });+ }+ };+ const pullValue = () => new Promise(resolve => {+ if (pushQueue.length !== 0) {+ const element = pushQueue.shift();+ // either {value: {errors: [...]}} or {value: ...}+ resolve({+ ...element,+ done: false,+ });+ }+ else {+ pullQueue.push(resolve);+ }+ });+ const subscription = observable.subscribe({+ next(value) {+ pushValue(value);+ },+ error(err) {+ pushError(err);+ },+ });+ const emptyQueue = () => {+ if (listening) {+ listening = false;+ subscription.unsubscribe();+ pullQueue.forEach(resolve => resolve({ value: undefined, done: true }));+ pullQueue.length = 0;+ pushQueue.length = 0;+ }+ };+ return {+ next() {+ return listening ? pullValue() : this.return();+ },+ return() {+ emptyQueue();+ return Promise.resolve({ value: undefined, done: true });+ },+ throw(error) {+ emptyQueue();+ return Promise.reject(error);+ },+ [Symbol.asyncIterator]() {+ return this;+ },+ };+}++var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};++function createCommonjsModule(fn, basedir, module) {+ return module = {+ path: basedir,+ exports: {},+ require: function (path, base) {+ return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);+ }+ }, fn(module, module.exports), module.exports;+}++function getAugmentedNamespace(n) {+ if (n.__esModule) return n;+ var a = Object.defineProperty({}, '__esModule', {value: true});+ Object.keys(n).forEach(function (k) {+ var d = Object.getOwnPropertyDescriptor(n, k);+ Object.defineProperty(a, k, d.get ? d : {+ enumerable: true,+ get: function () {+ return n[k];+ }+ });+ });+ return a;+}++function commonjsRequire () {+ throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');+}++var fromCallback = function (fn) {+ return Object.defineProperty(function (...args) {+ if (typeof args[args.length - 1] === 'function') fn.apply(this, args);+ else {+ return new Promise((resolve, reject) => {+ fn.apply(+ this,+ args.concat([(err, res) => err ? reject(err) : resolve(res)])+ );+ })+ }+ }, 'name', { value: fn.name })+};++var fromPromise = function (fn) {+ return Object.defineProperty(function (...args) {+ const cb = args[args.length - 1];+ if (typeof cb !== 'function') return fn.apply(this, args)+ else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb);+ }, 'name', { value: fn.name })+};++var universalify = {+ fromCallback: fromCallback,+ fromPromise: fromPromise+};++var origCwd = process.cwd;+var cwd = null;++var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;++process.cwd = function() {+ if (!cwd)+ cwd = origCwd.call(process);+ return cwd+};+try {+ process.cwd();+} catch (er) {}++var chdir = process.chdir;+process.chdir = function(d) {+ cwd = null;+ chdir.call(process, d);+};++var polyfills = patch;++function patch (fs) {+ // (re-)implement some things that are known busted or missing.++ // lchmod, broken prior to 0.6.2+ // back-port the fix here.+ if (constants__default['default'].hasOwnProperty('O_SYMLINK') &&+ process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {+ patchLchmod(fs);+ }++ // lutimes implementation, or no-op+ if (!fs.lutimes) {+ patchLutimes(fs);+ }++ // https://github.com/isaacs/node-graceful-fs/issues/4+ // Chown should not fail on einval or eperm if non-root.+ // It should not fail on enosys ever, as this just indicates+ // that a fs doesn't support the intended operation.++ fs.chown = chownFix(fs.chown);+ fs.fchown = chownFix(fs.fchown);+ fs.lchown = chownFix(fs.lchown);++ fs.chmod = chmodFix(fs.chmod);+ fs.fchmod = chmodFix(fs.fchmod);+ fs.lchmod = chmodFix(fs.lchmod);++ fs.chownSync = chownFixSync(fs.chownSync);+ fs.fchownSync = chownFixSync(fs.fchownSync);+ fs.lchownSync = chownFixSync(fs.lchownSync);++ fs.chmodSync = chmodFixSync(fs.chmodSync);+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);++ fs.stat = statFix(fs.stat);+ fs.fstat = statFix(fs.fstat);+ fs.lstat = statFix(fs.lstat);++ fs.statSync = statFixSync(fs.statSync);+ fs.fstatSync = statFixSync(fs.fstatSync);+ fs.lstatSync = statFixSync(fs.lstatSync);++ // if lchmod/lchown do not exist, then make them no-ops+ if (!fs.lchmod) {+ fs.lchmod = function (path, mode, cb) {+ if (cb) process.nextTick(cb);+ };+ fs.lchmodSync = function () {};+ }+ if (!fs.lchown) {+ fs.lchown = function (path, uid, gid, cb) {+ if (cb) process.nextTick(cb);+ };+ fs.lchownSync = function () {};+ }++ // on Windows, A/V software can lock the directory, causing this+ // to fail with an EACCES or EPERM if the directory contains newly+ // created files. Try again on failure, for up to 60 seconds.++ // Set the timeout this long because some Windows Anti-Virus, such as Parity+ // bit9, may lock files for up to a minute, causing npm package install+ // failures. Also, take care to yield the scheduler. Windows scheduling gives+ // CPU to a busy looping process, which can cause the program causing the lock+ // contention to be starved of CPU by node, so the contention doesn't resolve.+ if (platform === "win32") {+ fs.rename = (function (fs$rename) { return function (from, to, cb) {+ var start = Date.now();+ var backoff = 0;+ fs$rename(from, to, function CB (er) {+ if (er+ && (er.code === "EACCES" || er.code === "EPERM")+ && Date.now() - start < 60000) {+ setTimeout(function() {+ fs.stat(to, function (stater, st) {+ if (stater && stater.code === "ENOENT")+ fs$rename(from, to, CB);+ else+ cb(er);+ });+ }, backoff);+ if (backoff < 100)+ backoff += 10;+ return;+ }+ if (cb) cb(er);+ });+ }})(fs.rename);+ }++ // if read() returns EAGAIN, then just try it again.+ fs.read = (function (fs$read) {+ function read (fd, buffer, offset, length, position, callback_) {+ var callback;+ if (callback_ && typeof callback_ === 'function') {+ var eagCounter = 0;+ callback = function (er, _, __) {+ if (er && er.code === 'EAGAIN' && eagCounter < 10) {+ eagCounter ++;+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)+ }+ callback_.apply(this, arguments);+ };+ }+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)+ }++ // This ensures `util.promisify` works as it does for native `fs.read`.+ read.__proto__ = fs$read;+ return read+ })(fs.read);++ fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {+ var eagCounter = 0;+ while (true) {+ try {+ return fs$readSync.call(fs, fd, buffer, offset, length, position)+ } catch (er) {+ if (er.code === 'EAGAIN' && eagCounter < 10) {+ eagCounter ++;+ continue+ }+ throw er+ }+ }+ }})(fs.readSync);++ function patchLchmod (fs) {+ fs.lchmod = function (path, mode, callback) {+ fs.open( path+ , constants__default['default'].O_WRONLY | constants__default['default'].O_SYMLINK+ , mode+ , function (err, fd) {+ if (err) {+ if (callback) callback(err);+ return+ }+ // prefer to return the chmod error, if one occurs,+ // but still try to close, and report closing errors if they occur.+ fs.fchmod(fd, mode, function (err) {+ fs.close(fd, function(err2) {+ if (callback) callback(err || err2);+ });+ });+ });+ };++ fs.lchmodSync = function (path, mode) {+ var fd = fs.openSync(path, constants__default['default'].O_WRONLY | constants__default['default'].O_SYMLINK, mode);++ // prefer to return the chmod error, if one occurs,+ // but still try to close, and report closing errors if they occur.+ var threw = true;+ var ret;+ try {+ ret = fs.fchmodSync(fd, mode);+ threw = false;+ } finally {+ if (threw) {+ try {+ fs.closeSync(fd);+ } catch (er) {}+ } else {+ fs.closeSync(fd);+ }+ }+ return ret+ };+ }++ function patchLutimes (fs) {+ if (constants__default['default'].hasOwnProperty("O_SYMLINK")) {+ fs.lutimes = function (path, at, mt, cb) {+ fs.open(path, constants__default['default'].O_SYMLINK, function (er, fd) {+ if (er) {+ if (cb) cb(er);+ return+ }+ fs.futimes(fd, at, mt, function (er) {+ fs.close(fd, function (er2) {+ if (cb) cb(er || er2);+ });+ });+ });+ };++ fs.lutimesSync = function (path, at, mt) {+ var fd = fs.openSync(path, constants__default['default'].O_SYMLINK);+ var ret;+ var threw = true;+ try {+ ret = fs.futimesSync(fd, at, mt);+ threw = false;+ } finally {+ if (threw) {+ try {+ fs.closeSync(fd);+ } catch (er) {}+ } else {+ fs.closeSync(fd);+ }+ }+ return ret+ };++ } else {+ fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };+ fs.lutimesSync = function () {};+ }+ }++ function chmodFix (orig) {+ if (!orig) return orig+ return function (target, mode, cb) {+ return orig.call(fs, target, mode, function (er) {+ if (chownErOk(er)) er = null;+ if (cb) cb.apply(this, arguments);+ })+ }+ }++ function chmodFixSync (orig) {+ if (!orig) return orig+ return function (target, mode) {+ try {+ return orig.call(fs, target, mode)+ } catch (er) {+ if (!chownErOk(er)) throw er+ }+ }+ }+++ function chownFix (orig) {+ if (!orig) return orig+ return function (target, uid, gid, cb) {+ return orig.call(fs, target, uid, gid, function (er) {+ if (chownErOk(er)) er = null;+ if (cb) cb.apply(this, arguments);+ })+ }+ }++ function chownFixSync (orig) {+ if (!orig) return orig+ return function (target, uid, gid) {+ try {+ return orig.call(fs, target, uid, gid)+ } catch (er) {+ if (!chownErOk(er)) throw er+ }+ }+ }++ function statFix (orig) {+ if (!orig) return orig+ // Older versions of Node erroneously returned signed integers for+ // uid + gid.+ return function (target, options, cb) {+ if (typeof options === 'function') {+ cb = options;+ options = null;+ }+ function callback (er, stats) {+ if (stats) {+ if (stats.uid < 0) stats.uid += 0x100000000;+ if (stats.gid < 0) stats.gid += 0x100000000;+ }+ if (cb) cb.apply(this, arguments);+ }+ return options ? orig.call(fs, target, options, callback)+ : orig.call(fs, target, callback)+ }+ }++ function statFixSync (orig) {+ if (!orig) return orig+ // Older versions of Node erroneously returned signed integers for+ // uid + gid.+ return function (target, options) {+ var stats = options ? orig.call(fs, target, options)+ : orig.call(fs, target);+ if (stats.uid < 0) stats.uid += 0x100000000;+ if (stats.gid < 0) stats.gid += 0x100000000;+ return stats;+ }+ }++ // ENOSYS means that the fs doesn't support the op. Just ignore+ // that, because it doesn't matter.+ //+ // if there's no getuid, or if getuid() is something other+ // than 0, and the error is EINVAL or EPERM, then just ignore+ // it.+ //+ // This specific case is a silent failure in cp, install, tar,+ // and most other unix tools that manage permissions.+ //+ // When running as root, or if other types of errors are+ // encountered, then it's strict.+ function chownErOk (er) {+ if (!er)+ return true++ if (er.code === "ENOSYS")+ return true++ var nonroot = !process.getuid || process.getuid() !== 0;+ if (nonroot) {+ if (er.code === "EINVAL" || er.code === "EPERM")+ return true+ }++ return false+ }+}++var Stream = Stream__default['default'].Stream;++var legacyStreams = legacy;++function legacy (fs) {+ return {+ ReadStream: ReadStream,+ WriteStream: WriteStream+ }++ function ReadStream (path, options) {+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);++ Stream.call(this);++ var self = this;++ this.path = path;+ this.fd = null;+ this.readable = true;+ this.paused = false;++ this.flags = 'r';+ this.mode = 438; /*=0666*/+ this.bufferSize = 64 * 1024;++ options = options || {};++ // Mixin options into this+ var keys = Object.keys(options);+ for (var index = 0, length = keys.length; index < length; index++) {+ var key = keys[index];+ this[key] = options[key];+ }++ if (this.encoding) this.setEncoding(this.encoding);++ if (this.start !== undefined) {+ if ('number' !== typeof this.start) {+ throw TypeError('start must be a Number');+ }+ if (this.end === undefined) {+ this.end = Infinity;+ } else if ('number' !== typeof this.end) {+ throw TypeError('end must be a Number');+ }++ if (this.start > this.end) {+ throw new Error('start must be <= end');+ }++ this.pos = this.start;+ }++ if (this.fd !== null) {+ process.nextTick(function() {+ self._read();+ });+ return;+ }++ fs.open(this.path, this.flags, this.mode, function (err, fd) {+ if (err) {+ self.emit('error', err);+ self.readable = false;+ return;+ }++ self.fd = fd;+ self.emit('open', fd);+ self._read();+ });+ }++ function WriteStream (path, options) {+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);++ Stream.call(this);++ this.path = path;+ this.fd = null;+ this.writable = true;++ this.flags = 'w';+ this.encoding = 'binary';+ this.mode = 438; /*=0666*/+ this.bytesWritten = 0;++ options = options || {};++ // Mixin options into this+ var keys = Object.keys(options);+ for (var index = 0, length = keys.length; index < length; index++) {+ var key = keys[index];+ this[key] = options[key];+ }++ if (this.start !== undefined) {+ if ('number' !== typeof this.start) {+ throw TypeError('start must be a Number');+ }+ if (this.start < 0) {+ throw new Error('start must be >= zero');+ }++ this.pos = this.start;+ }++ this.busy = false;+ this._queue = [];++ if (this.fd === null) {+ this._open = fs.open;+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);+ this.flush();+ }+ }+}++var clone_1 = clone;++function clone (obj) {+ if (obj === null || typeof obj !== 'object')+ return obj++ if (obj instanceof Object)+ var copy = { __proto__: obj.__proto__ };+ else+ var copy = Object.create(null);++ Object.getOwnPropertyNames(obj).forEach(function (key) {+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));+ });++ return copy+}++var gracefulFs = createCommonjsModule(function (module) {+/* istanbul ignore next - node 0.x polyfill */+var gracefulQueue;+var previousSymbol;++/* istanbul ignore else - node 0.x polyfill */+if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {+ gracefulQueue = Symbol.for('graceful-fs.queue');+ // This is used in testing by future versions+ previousSymbol = Symbol.for('graceful-fs.previous');+} else {+ gracefulQueue = '___graceful-fs.queue';+ previousSymbol = '___graceful-fs.previous';+}++function noop () {}++function publishQueue(context, queue) {+ Object.defineProperty(context, gracefulQueue, {+ get: function() {+ return queue+ }+ });+}++var debug = noop;+if (util__default['default'].debuglog)+ debug = util__default['default'].debuglog('gfs4');+else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))+ debug = function() {+ var m = util__default['default'].format.apply(util__default['default'], arguments);+ m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');+ console.error(m);+ };++// Once time initialization+if (!fs__default['default'][gracefulQueue]) {+ // This queue can be shared by multiple loaded instances+ var queue = commonjsGlobal[gracefulQueue] || [];+ publishQueue(fs__default['default'], queue);++ // Patch fs.close/closeSync to shared queue version, because we need+ // to retry() whenever a close happens *anywhere* in the program.+ // This is essential when multiple graceful-fs instances are+ // in play at the same time.+ fs__default['default'].close = (function (fs$close) {+ function close (fd, cb) {+ return fs$close.call(fs__default['default'], fd, function (err) {+ // This function uses the graceful-fs shared queue+ if (!err) {+ retry();+ }++ if (typeof cb === 'function')+ cb.apply(this, arguments);+ })+ }++ Object.defineProperty(close, previousSymbol, {+ value: fs$close+ });+ return close+ })(fs__default['default'].close);++ fs__default['default'].closeSync = (function (fs$closeSync) {+ function closeSync (fd) {+ // This function uses the graceful-fs shared queue+ fs$closeSync.apply(fs__default['default'], arguments);+ retry();+ }++ Object.defineProperty(closeSync, previousSymbol, {+ value: fs$closeSync+ });+ return closeSync+ })(fs__default['default'].closeSync);++ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {+ process.on('exit', function() {+ debug(fs__default['default'][gracefulQueue]);+ assert__default['default'].equal(fs__default['default'][gracefulQueue].length, 0);+ });+ }+}++if (!commonjsGlobal[gracefulQueue]) {+ publishQueue(commonjsGlobal, fs__default['default'][gracefulQueue]);+}++module.exports = patch(clone_1(fs__default['default']));+if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs__default['default'].__patched) {+ module.exports = patch(fs__default['default']);+ fs__default['default'].__patched = true;+}++function patch (fs) {+ // Everything that references the open() function needs to be in here+ polyfills(fs);+ fs.gracefulify = patch;++ fs.createReadStream = createReadStream;+ fs.createWriteStream = createWriteStream;+ var fs$readFile = fs.readFile;+ fs.readFile = readFile;+ function readFile (path, options, cb) {+ if (typeof options === 'function')+ cb = options, options = null;++ return go$readFile(path, options, cb)++ function go$readFile (path, options, cb) {+ return fs$readFile(path, options, function (err) {+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))+ enqueue([go$readFile, [path, options, cb]]);+ else {+ if (typeof cb === 'function')+ cb.apply(this, arguments);+ retry();+ }+ })+ }+ }++ var fs$writeFile = fs.writeFile;+ fs.writeFile = writeFile;+ function writeFile (path, data, options, cb) {+ if (typeof options === 'function')+ cb = options, options = null;++ return go$writeFile(path, data, options, cb)++ function go$writeFile (path, data, options, cb) {+ return fs$writeFile(path, data, options, function (err) {+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))+ enqueue([go$writeFile, [path, data, options, cb]]);+ else {+ if (typeof cb === 'function')+ cb.apply(this, arguments);+ retry();+ }+ })+ }+ }++ var fs$appendFile = fs.appendFile;+ if (fs$appendFile)+ fs.appendFile = appendFile;+ function appendFile (path, data, options, cb) {+ if (typeof options === 'function')+ cb = options, options = null;++ return go$appendFile(path, data, options, cb)++ function go$appendFile (path, data, options, cb) {+ return fs$appendFile(path, data, options, function (err) {+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))+ enqueue([go$appendFile, [path, data, options, cb]]);+ else {+ if (typeof cb === 'function')+ cb.apply(this, arguments);+ retry();+ }+ })+ }+ }++ var fs$readdir = fs.readdir;+ fs.readdir = readdir;+ function readdir (path, options, cb) {+ var args = [path];+ if (typeof options !== 'function') {+ args.push(options);+ } else {+ cb = options;+ }+ args.push(go$readdir$cb);++ return go$readdir(args)++ function go$readdir$cb (err, files) {+ if (files && files.sort)+ files.sort();++ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))+ enqueue([go$readdir, [args]]);++ else {+ if (typeof cb === 'function')+ cb.apply(this, arguments);+ retry();+ }+ }+ }++ function go$readdir (args) {+ return fs$readdir.apply(fs, args)+ }++ if (process.version.substr(0, 4) === 'v0.8') {+ var legStreams = legacyStreams(fs);+ ReadStream = legStreams.ReadStream;+ WriteStream = legStreams.WriteStream;+ }++ var fs$ReadStream = fs.ReadStream;+ if (fs$ReadStream) {+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);+ ReadStream.prototype.open = ReadStream$open;+ }++ var fs$WriteStream = fs.WriteStream;+ if (fs$WriteStream) {+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);+ WriteStream.prototype.open = WriteStream$open;+ }++ Object.defineProperty(fs, 'ReadStream', {+ get: function () {+ return ReadStream+ },+ set: function (val) {+ ReadStream = val;+ },+ enumerable: true,+ configurable: true+ });+ Object.defineProperty(fs, 'WriteStream', {+ get: function () {+ return WriteStream+ },+ set: function (val) {+ WriteStream = val;+ },+ enumerable: true,+ configurable: true+ });++ // legacy names+ var FileReadStream = ReadStream;+ Object.defineProperty(fs, 'FileReadStream', {+ get: function () {+ return FileReadStream+ },+ set: function (val) {+ FileReadStream = val;+ },+ enumerable: true,+ configurable: true+ });+ var FileWriteStream = WriteStream;+ Object.defineProperty(fs, 'FileWriteStream', {+ get: function () {+ return FileWriteStream+ },+ set: function (val) {+ FileWriteStream = val;+ },+ enumerable: true,+ configurable: true+ });++ function ReadStream (path, options) {+ if (this instanceof ReadStream)+ return fs$ReadStream.apply(this, arguments), this+ else+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments)+ }++ function ReadStream$open () {+ var that = this;+ open(that.path, that.flags, that.mode, function (err, fd) {+ if (err) {+ if (that.autoClose)+ that.destroy();++ that.emit('error', err);+ } else {+ that.fd = fd;+ that.emit('open', fd);+ that.read();+ }+ });+ }++ function WriteStream (path, options) {+ if (this instanceof WriteStream)+ return fs$WriteStream.apply(this, arguments), this+ else+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments)+ }++ function WriteStream$open () {+ var that = this;+ open(that.path, that.flags, that.mode, function (err, fd) {+ if (err) {+ that.destroy();+ that.emit('error', err);+ } else {+ that.fd = fd;+ that.emit('open', fd);+ }+ });+ }++ function createReadStream (path, options) {+ return new fs.ReadStream(path, options)+ }++ function createWriteStream (path, options) {+ return new fs.WriteStream(path, options)+ }++ var fs$open = fs.open;+ fs.open = open;+ function open (path, flags, mode, cb) {+ if (typeof mode === 'function')+ cb = mode, mode = null;++ return go$open(path, flags, mode, cb)++ function go$open (path, flags, mode, cb) {+ return fs$open(path, flags, mode, function (err, fd) {+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))+ enqueue([go$open, [path, flags, mode, cb]]);+ else {+ if (typeof cb === 'function')+ cb.apply(this, arguments);+ retry();+ }+ })+ }+ }++ return fs+}++function enqueue (elem) {+ debug('ENQUEUE', elem[0].name, elem[1]);+ fs__default['default'][gracefulQueue].push(elem);+}++function retry () {+ var elem = fs__default['default'][gracefulQueue].shift();+ if (elem) {+ debug('RETRY', elem[0].name, elem[1]);+ elem[0].apply(null, elem[1]);+ }+}+});++var fs_1 = createCommonjsModule(function (module, exports) {+// This is adapted from https://github.com/normalize/mz+// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors+const u = universalify.fromCallback;+++const api = [+ 'access',+ 'appendFile',+ 'chmod',+ 'chown',+ 'close',+ 'copyFile',+ 'fchmod',+ 'fchown',+ 'fdatasync',+ 'fstat',+ 'fsync',+ 'ftruncate',+ 'futimes',+ 'lchmod',+ 'lchown',+ 'link',+ 'lstat',+ 'mkdir',+ 'mkdtemp',+ 'open',+ 'opendir',+ 'readdir',+ 'readFile',+ 'readlink',+ 'realpath',+ 'rename',+ 'rmdir',+ 'stat',+ 'symlink',+ 'truncate',+ 'unlink',+ 'utimes',+ 'writeFile'+].filter(key => {+ // Some commands are not available on some systems. Ex:+ // fs.opendir was added in Node.js v12.12.0+ // fs.lchown is not available on at least some Linux+ return typeof gracefulFs[key] === 'function'+});++// Export all keys:+Object.keys(gracefulFs).forEach(key => {+ if (key === 'promises') {+ // fs.promises is a getter property that triggers ExperimentalWarning+ // Don't re-export it here, the getter is defined in "lib/index.js"+ return+ }+ exports[key] = gracefulFs[key];+});++// Universalify async methods:+api.forEach(method => {+ exports[method] = u(gracefulFs[method]);+});++// We differ from mz/fs in that we still ship the old, broken, fs.exists()+// since we are a drop-in replacement for the native module+exports.exists = function (filename, callback) {+ if (typeof callback === 'function') {+ return gracefulFs.exists(filename, callback)+ }+ return new Promise(resolve => {+ return gracefulFs.exists(filename, resolve)+ })+};++// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args++exports.read = function (fd, buffer, offset, length, position, callback) {+ if (typeof callback === 'function') {+ return gracefulFs.read(fd, buffer, offset, length, position, callback)+ }+ return new Promise((resolve, reject) => {+ gracefulFs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {+ if (err) return reject(err)+ resolve({ bytesRead, buffer });+ });+ })+};++// Function signature can be+// fs.write(fd, buffer[, offset[, length[, position]]], callback)+// OR+// fs.write(fd, string[, position[, encoding]], callback)+// We need to handle both cases, so we use ...args+exports.write = function (fd, buffer, ...args) {+ if (typeof args[args.length - 1] === 'function') {+ return gracefulFs.write(fd, buffer, ...args)+ }++ return new Promise((resolve, reject) => {+ gracefulFs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {+ if (err) return reject(err)+ resolve({ bytesWritten, buffer });+ });+ })+};++// fs.writev only available in Node v12.9.0++if (typeof gracefulFs.writev === 'function') {+ // Function signature is+ // s.writev(fd, buffers[, position], callback)+ // We need to handle the optional arg, so we use ...args+ exports.writev = function (fd, buffers, ...args) {+ if (typeof args[args.length - 1] === 'function') {+ return gracefulFs.writev(fd, buffers, ...args)+ }++ return new Promise((resolve, reject) => {+ gracefulFs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {+ if (err) return reject(err)+ resolve({ bytesWritten, buffers });+ });+ })+ };+}++// fs.realpath.native only available in Node v9.2++if (typeof gracefulFs.realpath.native === 'function') {+ exports.realpath.native = u(gracefulFs.realpath.native);+}+});++var atLeastNode = r => {+ const n = process.versions.node.split('.').map(x => parseInt(x, 10));+ r = r.split('.').map(x => parseInt(x, 10));+ return n[0] > r[0] || (n[0] === r[0] && (n[1] > r[1] || (n[1] === r[1] && n[2] >= r[2])))+};++const useNativeRecursiveOption = atLeastNode('10.12.0');++// https://github.com/nodejs/node/issues/8987+// https://github.com/libuv/libuv/pull/1088+const checkPath = pth => {+ if (process.platform === 'win32') {+ const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path__default['default'].parse(pth).root, ''));++ if (pathHasInvalidWinCharacters) {+ const error = new Error(`Path contains invalid characters: ${pth}`);+ error.code = 'EINVAL';+ throw error+ }+ }+};++const processOptions = options => {+ const defaults = { mode: 0o777 };+ if (typeof options === 'number') options = { mode: options };+ return { ...defaults, ...options }+};++const permissionError = pth => {+ // This replicates the exception of `fs.mkdir` with native the+ // `recusive` option when run on an invalid drive under Windows.+ const error = new Error(`operation not permitted, mkdir '${pth}'`);+ error.code = 'EPERM';+ error.errno = -4048;+ error.path = pth;+ error.syscall = 'mkdir';+ return error+};++var makeDir_1 = async (input, options) => {+ checkPath(input);+ options = processOptions(options);++ if (useNativeRecursiveOption) {+ const pth = path__default['default'].resolve(input);++ return fs_1.mkdir(pth, {+ mode: options.mode,+ recursive: true+ })+ }++ const make = async pth => {+ try {+ await fs_1.mkdir(pth, options.mode);+ } catch (error) {+ if (error.code === 'EPERM') {+ throw error+ }++ if (error.code === 'ENOENT') {+ if (path__default['default'].dirname(pth) === pth) {+ throw permissionError(pth)+ }++ if (error.message.includes('null bytes')) {+ throw error+ }++ await make(path__default['default'].dirname(pth));+ return make(pth)+ }++ try {+ const stats = await fs_1.stat(pth);+ if (!stats.isDirectory()) {+ // This error is never exposed to the user+ // it is caught below, and the original error is thrown+ throw new Error('The path is not a directory')+ }+ } catch {+ throw error+ }+ }+ };++ return make(path__default['default'].resolve(input))+};++var makeDirSync = (input, options) => {+ checkPath(input);+ options = processOptions(options);++ if (useNativeRecursiveOption) {+ const pth = path__default['default'].resolve(input);++ return fs_1.mkdirSync(pth, {+ mode: options.mode,+ recursive: true+ })+ }++ const make = pth => {+ try {+ fs_1.mkdirSync(pth, options.mode);+ } catch (error) {+ if (error.code === 'EPERM') {+ throw error+ }++ if (error.code === 'ENOENT') {+ if (path__default['default'].dirname(pth) === pth) {+ throw permissionError(pth)+ }++ if (error.message.includes('null bytes')) {+ throw error+ }++ make(path__default['default'].dirname(pth));+ return make(pth)+ }++ try {+ if (!fs_1.statSync(pth).isDirectory()) {+ // This error is never exposed to the user+ // it is caught below, and the original error is thrown+ throw new Error('The path is not a directory')+ }+ } catch {+ throw error+ }+ }+ };++ return make(path__default['default'].resolve(input))+};++var makeDir = {+ makeDir: makeDir_1,+ makeDirSync: makeDirSync+};++const u = universalify.fromPromise;+const { makeDir: _makeDir, makeDirSync: makeDirSync$1 } = makeDir;+const makeDir$1 = u(_makeDir);++var mkdirs = {+ mkdirs: makeDir$1,+ mkdirsSync: makeDirSync$1,+ // alias+ mkdirp: makeDir$1,+ mkdirpSync: makeDirSync$1,+ ensureDir: makeDir$1,+ ensureDirSync: makeDirSync$1+};++function utimesMillis (path, atime, mtime, callback) {+ // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)+ gracefulFs.open(path, 'r+', (err, fd) => {+ if (err) return callback(err)+ gracefulFs.futimes(fd, atime, mtime, futimesErr => {+ gracefulFs.close(fd, closeErr => {+ if (callback) callback(futimesErr || closeErr);+ });+ });+ });+}++function utimesMillisSync (path, atime, mtime) {+ const fd = gracefulFs.openSync(path, 'r+');+ gracefulFs.futimesSync(fd, atime, mtime);+ return gracefulFs.closeSync(fd)+}++var utimes = {+ utimesMillis,+ utimesMillisSync+};++const nodeSupportsBigInt = atLeastNode('10.5.0');+const stat = (file) => nodeSupportsBigInt ? fs_1.stat(file, { bigint: true }) : fs_1.stat(file);+const statSync = (file) => nodeSupportsBigInt ? fs_1.statSync(file, { bigint: true }) : fs_1.statSync(file);++function getStats (src, dest) {+ return Promise.all([+ stat(src),+ stat(dest).catch(err => {+ if (err.code === 'ENOENT') return null+ throw err+ })+ ]).then(([srcStat, destStat]) => ({ srcStat, destStat }))+}++function getStatsSync (src, dest) {+ let destStat;+ const srcStat = statSync(src);+ try {+ destStat = statSync(dest);+ } catch (err) {+ if (err.code === 'ENOENT') return { srcStat, destStat: null }+ throw err+ }+ return { srcStat, destStat }+}++function checkPaths (src, dest, funcName, cb) {+ util__default['default'].callbackify(getStats)(src, dest, (err, stats) => {+ if (err) return cb(err)+ const { srcStat, destStat } = stats;+ if (destStat && areIdentical(srcStat, destStat)) {+ return cb(new Error('Source and destination must not be the same.'))+ }+ if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {+ return cb(new Error(errMsg(src, dest, funcName)))+ }+ return cb(null, { srcStat, destStat })+ });+}++function checkPathsSync (src, dest, funcName) {+ const { srcStat, destStat } = getStatsSync(src, dest);+ if (destStat && areIdentical(srcStat, destStat)) {+ throw new Error('Source and destination must not be the same.')+ }+ if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {+ throw new Error(errMsg(src, dest, funcName))+ }+ return { srcStat, destStat }+}++// recursively check if dest parent is a subdirectory of src.+// It works for all file types including symlinks since it+// checks the src and dest inodes. It starts from the deepest+// parent and stops once it reaches the src parent or the root path.+function checkParentPaths (src, srcStat, dest, funcName, cb) {+ const srcParent = path__default['default'].resolve(path__default['default'].dirname(src));+ const destParent = path__default['default'].resolve(path__default['default'].dirname(dest));+ if (destParent === srcParent || destParent === path__default['default'].parse(destParent).root) return cb()+ const callback = (err, destStat) => {+ if (err) {+ if (err.code === 'ENOENT') return cb()+ return cb(err)+ }+ if (areIdentical(srcStat, destStat)) {+ return cb(new Error(errMsg(src, dest, funcName)))+ }+ return checkParentPaths(src, srcStat, destParent, funcName, cb)+ };+ if (nodeSupportsBigInt) fs_1.stat(destParent, { bigint: true }, callback);+ else fs_1.stat(destParent, callback);+}++function checkParentPathsSync (src, srcStat, dest, funcName) {+ const srcParent = path__default['default'].resolve(path__default['default'].dirname(src));+ const destParent = path__default['default'].resolve(path__default['default'].dirname(dest));+ if (destParent === srcParent || destParent === path__default['default'].parse(destParent).root) return+ let destStat;+ try {+ destStat = statSync(destParent);+ } catch (err) {+ if (err.code === 'ENOENT') return+ throw err+ }+ if (areIdentical(srcStat, destStat)) {+ throw new Error(errMsg(src, dest, funcName))+ }+ return checkParentPathsSync(src, srcStat, destParent, funcName)+}++function areIdentical (srcStat, destStat) {+ if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) {+ if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) {+ // definitive answer+ return true+ }+ // Use additional heuristics if we can't use 'bigint'.+ // Different 'ino' could be represented the same if they are >= Number.MAX_SAFE_INTEGER+ // See issue 657+ if (destStat.size === srcStat.size &&+ destStat.mode === srcStat.mode &&+ destStat.nlink === srcStat.nlink &&+ destStat.atimeMs === srcStat.atimeMs &&+ destStat.mtimeMs === srcStat.mtimeMs &&+ destStat.ctimeMs === srcStat.ctimeMs &&+ destStat.birthtimeMs === srcStat.birthtimeMs) {+ // heuristic answer+ return true+ }+ }+ return false+}++// return true if dest is a subdir of src, otherwise false.+// It only checks the path strings.+function isSrcSubdir (src, dest) {+ const srcArr = path__default['default'].resolve(src).split(path__default['default'].sep).filter(i => i);+ const destArr = path__default['default'].resolve(dest).split(path__default['default'].sep).filter(i => i);+ return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true)+}++function errMsg (src, dest, funcName) {+ return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`+}++var stat_1 = {+ checkPaths,+ checkPathsSync,+ checkParentPaths,+ checkParentPathsSync,+ isSrcSubdir+};++const mkdirsSync = mkdirs.mkdirsSync;+const utimesMillisSync$1 = utimes.utimesMillisSync;+++function copySync (src, dest, opts) {+ if (typeof opts === 'function') {+ opts = { filter: opts };+ }++ opts = opts || {};+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber++ // Warn about using preserveTimestamps on 32-bit node+ if (opts.preserveTimestamps && process.arch === 'ia32') {+ console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n+ see https://github.com/jprichardson/node-fs-extra/issues/269`);+ }++ const { srcStat, destStat } = stat_1.checkPathsSync(src, dest, 'copy');+ stat_1.checkParentPathsSync(src, srcStat, dest, 'copy');+ return handleFilterAndCopy(destStat, src, dest, opts)+}++function handleFilterAndCopy (destStat, src, dest, opts) {+ if (opts.filter && !opts.filter(src, dest)) return+ const destParent = path__default['default'].dirname(dest);+ if (!gracefulFs.existsSync(destParent)) mkdirsSync(destParent);+ return startCopy(destStat, src, dest, opts)+}++function startCopy (destStat, src, dest, opts) {+ if (opts.filter && !opts.filter(src, dest)) return+ return getStats$1(destStat, src, dest, opts)+}++function getStats$1 (destStat, src, dest, opts) {+ const statSync = opts.dereference ? gracefulFs.statSync : gracefulFs.lstatSync;+ const srcStat = statSync(src);++ if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)+ else if (srcStat.isFile() ||+ srcStat.isCharacterDevice() ||+ srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)+ else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)+}++function onFile (srcStat, destStat, src, dest, opts) {+ if (!destStat) return copyFile(srcStat, src, dest, opts)+ return mayCopyFile(srcStat, src, dest, opts)+}++function mayCopyFile (srcStat, src, dest, opts) {+ if (opts.overwrite) {+ gracefulFs.unlinkSync(dest);+ return copyFile(srcStat, src, dest, opts)+ } else if (opts.errorOnExist) {+ throw new Error(`'${dest}' already exists`)+ }+}++function copyFile (srcStat, src, dest, opts) {+ gracefulFs.copyFileSync(src, dest);+ if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest);+ return setDestMode(dest, srcStat.mode)+}++function handleTimestamps (srcMode, src, dest) {+ // Make sure the file is writable before setting the timestamp+ // otherwise open fails with EPERM when invoked with 'r+'+ // (through utimes call)+ if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode);+ return setDestTimestamps(src, dest)+}++function fileIsNotWritable (srcMode) {+ return (srcMode & 0o200) === 0+}++function makeFileWritable (dest, srcMode) {+ return setDestMode(dest, srcMode | 0o200)+}++function setDestMode (dest, srcMode) {+ return gracefulFs.chmodSync(dest, srcMode)+}++function setDestTimestamps (src, dest) {+ // The initial srcStat.atime cannot be trusted+ // because it is modified by the read(2) system call+ // (See https://nodejs.org/api/fs.html#fs_stat_time_values)+ const updatedSrcStat = gracefulFs.statSync(src);+ return utimesMillisSync$1(dest, updatedSrcStat.atime, updatedSrcStat.mtime)+}++function onDir (srcStat, destStat, src, dest, opts) {+ if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)+ if (destStat && !destStat.isDirectory()) {+ throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)+ }+ return copyDir(src, dest, opts)+}++function mkDirAndCopy (srcMode, src, dest, opts) {+ gracefulFs.mkdirSync(dest);+ copyDir(src, dest, opts);+ return setDestMode(dest, srcMode)+}++function copyDir (src, dest, opts) {+ gracefulFs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts));+}++function copyDirItem (item, src, dest, opts) {+ const srcItem = path__default['default'].join(src, item);+ const destItem = path__default['default'].join(dest, item);+ const { destStat } = stat_1.checkPathsSync(srcItem, destItem, 'copy');+ return startCopy(destStat, srcItem, destItem, opts)+}++function onLink (destStat, src, dest, opts) {+ let resolvedSrc = gracefulFs.readlinkSync(src);+ if (opts.dereference) {+ resolvedSrc = path__default['default'].resolve(process.cwd(), resolvedSrc);+ }++ if (!destStat) {+ return gracefulFs.symlinkSync(resolvedSrc, dest)+ } else {+ let resolvedDest;+ try {+ resolvedDest = gracefulFs.readlinkSync(dest);+ } catch (err) {+ // dest exists and is a regular file or directory,+ // Windows may throw UNKNOWN error. If dest already exists,+ // fs throws error anyway, so no need to guard against it here.+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return gracefulFs.symlinkSync(resolvedSrc, dest)+ throw err+ }+ if (opts.dereference) {+ resolvedDest = path__default['default'].resolve(process.cwd(), resolvedDest);+ }+ if (stat_1.isSrcSubdir(resolvedSrc, resolvedDest)) {+ throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)+ }++ // prevent copy if src is a subdir of dest since unlinking+ // dest in this case would result in removing src contents+ // and therefore a broken symlink would be created.+ if (gracefulFs.statSync(dest).isDirectory() && stat_1.isSrcSubdir(resolvedDest, resolvedSrc)) {+ throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)+ }+ return copyLink(resolvedSrc, dest)+ }+}++function copyLink (resolvedSrc, dest) {+ gracefulFs.unlinkSync(dest);+ return gracefulFs.symlinkSync(resolvedSrc, dest)+}++var copySync_1 = copySync;++var copySync$1 = {+ copySync: copySync_1+};++const u$1 = universalify.fromPromise;+++function pathExists (path) {+ return fs_1.access(path).then(() => true).catch(() => false)+}++var pathExists_1 = {+ pathExists: u$1(pathExists),+ pathExistsSync: fs_1.existsSync+};++const mkdirs$1 = mkdirs.mkdirs;+const pathExists$1 = pathExists_1.pathExists;+const utimesMillis$1 = utimes.utimesMillis;+++function copy (src, dest, opts, cb) {+ if (typeof opts === 'function' && !cb) {+ cb = opts;+ opts = {};+ } else if (typeof opts === 'function') {+ opts = { filter: opts };+ }++ cb = cb || function () {};+ opts = opts || {};++ opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber++ // Warn about using preserveTimestamps on 32-bit node+ if (opts.preserveTimestamps && process.arch === 'ia32') {+ console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n+ see https://github.com/jprichardson/node-fs-extra/issues/269`);+ }++ stat_1.checkPaths(src, dest, 'copy', (err, stats) => {+ if (err) return cb(err)+ const { srcStat, destStat } = stats;+ stat_1.checkParentPaths(src, srcStat, dest, 'copy', err => {+ if (err) return cb(err)+ if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb)+ return checkParentDir(destStat, src, dest, opts, cb)+ });+ });+}++function checkParentDir (destStat, src, dest, opts, cb) {+ const destParent = path__default['default'].dirname(dest);+ pathExists$1(destParent, (err, dirExists) => {+ if (err) return cb(err)+ if (dirExists) return startCopy$1(destStat, src, dest, opts, cb)+ mkdirs$1(destParent, err => {+ if (err) return cb(err)+ return startCopy$1(destStat, src, dest, opts, cb)+ });+ });+}++function handleFilter (onInclude, destStat, src, dest, opts, cb) {+ Promise.resolve(opts.filter(src, dest)).then(include => {+ if (include) return onInclude(destStat, src, dest, opts, cb)+ return cb()+ }, error => cb(error));+}++function startCopy$1 (destStat, src, dest, opts, cb) {+ if (opts.filter) return handleFilter(getStats$2, destStat, src, dest, opts, cb)+ return getStats$2(destStat, src, dest, opts, cb)+}++function getStats$2 (destStat, src, dest, opts, cb) {+ const stat = opts.dereference ? gracefulFs.stat : gracefulFs.lstat;+ stat(src, (err, srcStat) => {+ if (err) return cb(err)++ if (srcStat.isDirectory()) return onDir$1(srcStat, destStat, src, dest, opts, cb)+ else if (srcStat.isFile() ||+ srcStat.isCharacterDevice() ||+ srcStat.isBlockDevice()) return onFile$1(srcStat, destStat, src, dest, opts, cb)+ else if (srcStat.isSymbolicLink()) return onLink$1(destStat, src, dest, opts, cb)+ });+}++function onFile$1 (srcStat, destStat, src, dest, opts, cb) {+ if (!destStat) return copyFile$1(srcStat, src, dest, opts, cb)+ return mayCopyFile$1(srcStat, src, dest, opts, cb)+}++function mayCopyFile$1 (srcStat, src, dest, opts, cb) {+ if (opts.overwrite) {+ gracefulFs.unlink(dest, err => {+ if (err) return cb(err)+ return copyFile$1(srcStat, src, dest, opts, cb)+ });+ } else if (opts.errorOnExist) {+ return cb(new Error(`'${dest}' already exists`))+ } else return cb()+}++function copyFile$1 (srcStat, src, dest, opts, cb) {+ gracefulFs.copyFile(src, dest, err => {+ if (err) return cb(err)+ if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb)+ return setDestMode$1(dest, srcStat.mode, cb)+ });+}++function handleTimestampsAndMode (srcMode, src, dest, cb) {+ // Make sure the file is writable before setting the timestamp+ // otherwise open fails with EPERM when invoked with 'r+'+ // (through utimes call)+ if (fileIsNotWritable$1(srcMode)) {+ return makeFileWritable$1(dest, srcMode, err => {+ if (err) return cb(err)+ return setDestTimestampsAndMode(srcMode, src, dest, cb)+ })+ }+ return setDestTimestampsAndMode(srcMode, src, dest, cb)+}++function fileIsNotWritable$1 (srcMode) {+ return (srcMode & 0o200) === 0+}++function makeFileWritable$1 (dest, srcMode, cb) {+ return setDestMode$1(dest, srcMode | 0o200, cb)+}++function setDestTimestampsAndMode (srcMode, src, dest, cb) {+ setDestTimestamps$1(src, dest, err => {+ if (err) return cb(err)+ return setDestMode$1(dest, srcMode, cb)+ });+}++function setDestMode$1 (dest, srcMode, cb) {+ return gracefulFs.chmod(dest, srcMode, cb)+}++function setDestTimestamps$1 (src, dest, cb) {+ // The initial srcStat.atime cannot be trusted+ // because it is modified by the read(2) system call+ // (See https://nodejs.org/api/fs.html#fs_stat_time_values)+ gracefulFs.stat(src, (err, updatedSrcStat) => {+ if (err) return cb(err)+ return utimesMillis$1(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb)+ });+}++function onDir$1 (srcStat, destStat, src, dest, opts, cb) {+ if (!destStat) return mkDirAndCopy$1(srcStat.mode, src, dest, opts, cb)+ if (destStat && !destStat.isDirectory()) {+ return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))+ }+ return copyDir$1(src, dest, opts, cb)+}++function mkDirAndCopy$1 (srcMode, src, dest, opts, cb) {+ gracefulFs.mkdir(dest, err => {+ if (err) return cb(err)+ copyDir$1(src, dest, opts, err => {+ if (err) return cb(err)+ return setDestMode$1(dest, srcMode, cb)+ });+ });+}++function copyDir$1 (src, dest, opts, cb) {+ gracefulFs.readdir(src, (err, items) => {+ if (err) return cb(err)+ return copyDirItems(items, src, dest, opts, cb)+ });+}++function copyDirItems (items, src, dest, opts, cb) {+ const item = items.pop();+ if (!item) return cb()+ return copyDirItem$1(items, item, src, dest, opts, cb)+}++function copyDirItem$1 (items, item, src, dest, opts, cb) {+ const srcItem = path__default['default'].join(src, item);+ const destItem = path__default['default'].join(dest, item);+ stat_1.checkPaths(srcItem, destItem, 'copy', (err, stats) => {+ if (err) return cb(err)+ const { destStat } = stats;+ startCopy$1(destStat, srcItem, destItem, opts, err => {+ if (err) return cb(err)+ return copyDirItems(items, src, dest, opts, cb)+ });+ });+}++function onLink$1 (destStat, src, dest, opts, cb) {+ gracefulFs.readlink(src, (err, resolvedSrc) => {+ if (err) return cb(err)+ if (opts.dereference) {+ resolvedSrc = path__default['default'].resolve(process.cwd(), resolvedSrc);+ }++ if (!destStat) {+ return gracefulFs.symlink(resolvedSrc, dest, cb)+ } else {+ gracefulFs.readlink(dest, (err, resolvedDest) => {+ if (err) {+ // dest exists and is a regular file or directory,+ // Windows may throw UNKNOWN error. If dest already exists,+ // fs throws error anyway, so no need to guard against it here.+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return gracefulFs.symlink(resolvedSrc, dest, cb)+ return cb(err)+ }+ if (opts.dereference) {+ resolvedDest = path__default['default'].resolve(process.cwd(), resolvedDest);+ }+ if (stat_1.isSrcSubdir(resolvedSrc, resolvedDest)) {+ return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`))+ }++ // do not copy if src is a subdir of dest since unlinking+ // dest in this case would result in removing src contents+ // and therefore a broken symlink would be created.+ if (destStat.isDirectory() && stat_1.isSrcSubdir(resolvedDest, resolvedSrc)) {+ return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))+ }+ return copyLink$1(resolvedSrc, dest, cb)+ });+ }+ });+}++function copyLink$1 (resolvedSrc, dest, cb) {+ gracefulFs.unlink(dest, err => {+ if (err) return cb(err)+ return gracefulFs.symlink(resolvedSrc, dest, cb)+ });+}++var copy_1 = copy;++const u$2 = universalify.fromCallback;+var copy$1 = {+ copy: u$2(copy_1)+};++const isWindows = (process.platform === 'win32');++function defaults (options) {+ const methods = [+ 'unlink',+ 'chmod',+ 'stat',+ 'lstat',+ 'rmdir',+ 'readdir'+ ];+ methods.forEach(m => {+ options[m] = options[m] || gracefulFs[m];+ m = m + 'Sync';+ options[m] = options[m] || gracefulFs[m];+ });++ options.maxBusyTries = options.maxBusyTries || 3;+}++function rimraf (p, options, cb) {+ let busyTries = 0;++ if (typeof options === 'function') {+ cb = options;+ options = {};+ }++ assert__default['default'](p, 'rimraf: missing path');+ assert__default['default'].strictEqual(typeof p, 'string', 'rimraf: path should be a string');+ assert__default['default'].strictEqual(typeof cb, 'function', 'rimraf: callback function required');+ assert__default['default'](options, 'rimraf: invalid options argument provided');+ assert__default['default'].strictEqual(typeof options, 'object', 'rimraf: options should be object');++ defaults(options);++ rimraf_(p, options, function CB (er) {+ if (er) {+ if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') &&+ busyTries < options.maxBusyTries) {+ busyTries++;+ const time = busyTries * 100;+ // try again, with the same exact callback as this one.+ return setTimeout(() => rimraf_(p, options, CB), time)+ }++ // already gone+ if (er.code === 'ENOENT') er = null;+ }++ cb(er);+ });+}++// Two possible strategies.+// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR+// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR+//+// Both result in an extra syscall when you guess wrong. However, there+// are likely far more normal files in the world than directories. This+// is based on the assumption that a the average number of files per+// directory is >= 1.+//+// If anyone ever complains about this, then I guess the strategy could+// be made configurable somehow. But until then, YAGNI.+function rimraf_ (p, options, cb) {+ assert__default['default'](p);+ assert__default['default'](options);+ assert__default['default'](typeof cb === 'function');++ // sunos lets the root user unlink directories, which is... weird.+ // so we have to lstat here and make sure it's not a dir.+ options.lstat(p, (er, st) => {+ if (er && er.code === 'ENOENT') {+ return cb(null)+ }++ // Windows can EPERM on stat. Life is suffering.+ if (er && er.code === 'EPERM' && isWindows) {+ return fixWinEPERM(p, options, er, cb)+ }++ if (st && st.isDirectory()) {+ return rmdir(p, options, er, cb)+ }++ options.unlink(p, er => {+ if (er) {+ if (er.code === 'ENOENT') {+ return cb(null)+ }+ if (er.code === 'EPERM') {+ return (isWindows)+ ? fixWinEPERM(p, options, er, cb)+ : rmdir(p, options, er, cb)+ }+ if (er.code === 'EISDIR') {+ return rmdir(p, options, er, cb)+ }+ }+ return cb(er)+ });+ });+}++function fixWinEPERM (p, options, er, cb) {+ assert__default['default'](p);+ assert__default['default'](options);+ assert__default['default'](typeof cb === 'function');++ options.chmod(p, 0o666, er2 => {+ if (er2) {+ cb(er2.code === 'ENOENT' ? null : er);+ } else {+ options.stat(p, (er3, stats) => {+ if (er3) {+ cb(er3.code === 'ENOENT' ? null : er);+ } else if (stats.isDirectory()) {+ rmdir(p, options, er, cb);+ } else {+ options.unlink(p, cb);+ }+ });+ }+ });+}++function fixWinEPERMSync (p, options, er) {+ let stats;++ assert__default['default'](p);+ assert__default['default'](options);++ try {+ options.chmodSync(p, 0o666);+ } catch (er2) {+ if (er2.code === 'ENOENT') {+ return+ } else {+ throw er+ }+ }++ try {+ stats = options.statSync(p);+ } catch (er3) {+ if (er3.code === 'ENOENT') {+ return+ } else {+ throw er+ }+ }++ if (stats.isDirectory()) {+ rmdirSync(p, options, er);+ } else {+ options.unlinkSync(p);+ }+}++function rmdir (p, options, originalEr, cb) {+ assert__default['default'](p);+ assert__default['default'](options);+ assert__default['default'](typeof cb === 'function');++ // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)+ // if we guessed wrong, and it's not a directory, then+ // raise the original error.+ options.rmdir(p, er => {+ if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {+ rmkids(p, options, cb);+ } else if (er && er.code === 'ENOTDIR') {+ cb(originalEr);+ } else {+ cb(er);+ }+ });+}++function rmkids (p, options, cb) {+ assert__default['default'](p);+ assert__default['default'](options);+ assert__default['default'](typeof cb === 'function');++ options.readdir(p, (er, files) => {+ if (er) return cb(er)++ let n = files.length;+ let errState;++ if (n === 0) return options.rmdir(p, cb)++ files.forEach(f => {+ rimraf(path__default['default'].join(p, f), options, er => {+ if (errState) {+ return+ }+ if (er) return cb(errState = er)+ if (--n === 0) {+ options.rmdir(p, cb);+ }+ });+ });+ });+}++// this looks simpler, and is strictly *faster*, but will+// tie up the JavaScript thread and fail on excessively+// deep directory trees.+function rimrafSync (p, options) {+ let st;++ options = options || {};+ defaults(options);++ assert__default['default'](p, 'rimraf: missing path');+ assert__default['default'].strictEqual(typeof p, 'string', 'rimraf: path should be a string');+ assert__default['default'](options, 'rimraf: missing options');+ assert__default['default'].strictEqual(typeof options, 'object', 'rimraf: options should be object');++ try {+ st = options.lstatSync(p);+ } catch (er) {+ if (er.code === 'ENOENT') {+ return+ }++ // Windows can EPERM on stat. Life is suffering.+ if (er.code === 'EPERM' && isWindows) {+ fixWinEPERMSync(p, options, er);+ }+ }++ try {+ // sunos lets the root user unlink directories, which is... weird.+ if (st && st.isDirectory()) {+ rmdirSync(p, options, null);+ } else {+ options.unlinkSync(p);+ }+ } catch (er) {+ if (er.code === 'ENOENT') {+ return+ } else if (er.code === 'EPERM') {+ return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)+ } else if (er.code !== 'EISDIR') {+ throw er+ }+ rmdirSync(p, options, er);+ }+}++function rmdirSync (p, options, originalEr) {+ assert__default['default'](p);+ assert__default['default'](options);++ try {+ options.rmdirSync(p);+ } catch (er) {+ if (er.code === 'ENOTDIR') {+ throw originalEr+ } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') {+ rmkidsSync(p, options);+ } else if (er.code !== 'ENOENT') {+ throw er+ }+ }+}++function rmkidsSync (p, options) {+ assert__default['default'](p);+ assert__default['default'](options);+ options.readdirSync(p).forEach(f => rimrafSync(path__default['default'].join(p, f), options));++ if (isWindows) {+ // We only end up here once we got ENOTEMPTY at least once, and+ // at this point, we are guaranteed to have removed all the kids.+ // So, we know that it won't be ENOENT or ENOTDIR or anything else.+ // try really hard to delete stuff on windows, because it has a+ // PROFOUNDLY annoying habit of not closing handles promptly when+ // files are deleted, resulting in spurious ENOTEMPTY errors.+ const startTime = Date.now();+ do {+ try {+ const ret = options.rmdirSync(p, options);+ return ret+ } catch {}+ } while (Date.now() - startTime < 500) // give up after 500ms+ } else {+ const ret = options.rmdirSync(p, options);+ return ret+ }+}++var rimraf_1 = rimraf;+rimraf.sync = rimrafSync;++const u$3 = universalify.fromCallback;+++var remove = {+ remove: u$3(rimraf_1),+ removeSync: rimraf_1.sync+};++const u$4 = universalify.fromCallback;++++++const emptyDir = u$4(function emptyDir (dir, callback) {+ callback = callback || function () {};+ gracefulFs.readdir(dir, (err, items) => {+ if (err) return mkdirs.mkdirs(dir, callback)++ items = items.map(item => path__default['default'].join(dir, item));++ deleteItem();++ function deleteItem () {+ const item = items.pop();+ if (!item) return callback()+ remove.remove(item, err => {+ if (err) return callback(err)+ deleteItem();+ });+ }+ });+});++function emptyDirSync (dir) {+ let items;+ try {+ items = gracefulFs.readdirSync(dir);+ } catch {+ return mkdirs.mkdirsSync(dir)+ }++ items.forEach(item => {+ item = path__default['default'].join(dir, item);+ remove.removeSync(item);+ });+}++var empty = {+ emptyDirSync,+ emptydirSync: emptyDirSync,+ emptyDir,+ emptydir: emptyDir+};++const u$5 = universalify.fromCallback;+++++function createFile (file, callback) {+ function makeFile () {+ gracefulFs.writeFile(file, '', err => {+ if (err) return callback(err)+ callback();+ });+ }++ gracefulFs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err+ if (!err && stats.isFile()) return callback()+ const dir = path__default['default'].dirname(file);+ gracefulFs.stat(dir, (err, stats) => {+ if (err) {+ // if the directory doesn't exist, make it+ if (err.code === 'ENOENT') {+ return mkdirs.mkdirs(dir, err => {+ if (err) return callback(err)+ makeFile();+ })+ }+ return callback(err)+ }++ if (stats.isDirectory()) makeFile();+ else {+ // parent is not a directory+ // This is just to cause an internal ENOTDIR error to be thrown+ gracefulFs.readdir(dir, err => {+ if (err) return callback(err)+ });+ }+ });+ });+}++function createFileSync (file) {+ let stats;+ try {+ stats = gracefulFs.statSync(file);+ } catch {}+ if (stats && stats.isFile()) return++ const dir = path__default['default'].dirname(file);+ try {+ if (!gracefulFs.statSync(dir).isDirectory()) {+ // parent is not a directory+ // This is just to cause an internal ENOTDIR error to be thrown+ gracefulFs.readdirSync(dir);+ }+ } catch (err) {+ // If the stat call above failed because the directory doesn't exist, create it+ if (err && err.code === 'ENOENT') mkdirs.mkdirsSync(dir);+ else throw err+ }++ gracefulFs.writeFileSync(file, '');+}++var file = {+ createFile: u$5(createFile),+ createFileSync+};++const u$6 = universalify.fromCallback;++++const pathExists$2 = pathExists_1.pathExists;++function createLink (srcpath, dstpath, callback) {+ function makeLink (srcpath, dstpath) {+ gracefulFs.link(srcpath, dstpath, err => {+ if (err) return callback(err)+ callback(null);+ });+ }++ pathExists$2(dstpath, (err, destinationExists) => {+ if (err) return callback(err)+ if (destinationExists) return callback(null)+ gracefulFs.lstat(srcpath, (err) => {+ if (err) {+ err.message = err.message.replace('lstat', 'ensureLink');+ return callback(err)+ }++ const dir = path__default['default'].dirname(dstpath);+ pathExists$2(dir, (err, dirExists) => {+ if (err) return callback(err)+ if (dirExists) return makeLink(srcpath, dstpath)+ mkdirs.mkdirs(dir, err => {+ if (err) return callback(err)+ makeLink(srcpath, dstpath);+ });+ });+ });+ });+}++function createLinkSync (srcpath, dstpath) {+ const destinationExists = gracefulFs.existsSync(dstpath);+ if (destinationExists) return undefined++ try {+ gracefulFs.lstatSync(srcpath);+ } catch (err) {+ err.message = err.message.replace('lstat', 'ensureLink');+ throw err+ }++ const dir = path__default['default'].dirname(dstpath);+ const dirExists = gracefulFs.existsSync(dir);+ if (dirExists) return gracefulFs.linkSync(srcpath, dstpath)+ mkdirs.mkdirsSync(dir);++ return gracefulFs.linkSync(srcpath, dstpath)+}++var link = {+ createLink: u$6(createLink),+ createLinkSync+};++const pathExists$3 = pathExists_1.pathExists;++/**+ * Function that returns two types of paths, one relative to symlink, and one+ * relative to the current working directory. Checks if path is absolute or+ * relative. If the path is relative, this function checks if the path is+ * relative to symlink or relative to current working directory. This is an+ * initiative to find a smarter `srcpath` to supply when building symlinks.+ * This allows you to determine which path to use out of one of three possible+ * types of source paths. The first is an absolute path. This is detected by+ * `path.isAbsolute()`. When an absolute path is provided, it is checked to+ * see if it exists. If it does it's used, if not an error is returned+ * (callback)/ thrown (sync). The other two options for `srcpath` are a+ * relative url. By default Node's `fs.symlink` works by creating a symlink+ * using `dstpath` and expects the `srcpath` to be relative to the newly+ * created symlink. If you provide a `srcpath` that does not exist on the file+ * system it results in a broken symlink. To minimize this, the function+ * checks to see if the 'relative to symlink' source file exists, and if it+ * does it will use it. If it does not, it checks if there's a file that+ * exists that is relative to the current working directory, if does its used.+ * This preserves the expectations of the original fs.symlink spec and adds+ * the ability to pass in `relative to current working direcotry` paths.+ */++function symlinkPaths (srcpath, dstpath, callback) {+ if (path__default['default'].isAbsolute(srcpath)) {+ return gracefulFs.lstat(srcpath, (err) => {+ if (err) {+ err.message = err.message.replace('lstat', 'ensureSymlink');+ return callback(err)+ }+ return callback(null, {+ toCwd: srcpath,+ toDst: srcpath+ })+ })+ } else {+ const dstdir = path__default['default'].dirname(dstpath);+ const relativeToDst = path__default['default'].join(dstdir, srcpath);+ return pathExists$3(relativeToDst, (err, exists) => {+ if (err) return callback(err)+ if (exists) {+ return callback(null, {+ toCwd: relativeToDst,+ toDst: srcpath+ })+ } else {+ return gracefulFs.lstat(srcpath, (err) => {+ if (err) {+ err.message = err.message.replace('lstat', 'ensureSymlink');+ return callback(err)+ }+ return callback(null, {+ toCwd: srcpath,+ toDst: path__default['default'].relative(dstdir, srcpath)+ })+ })+ }+ })+ }+}++function symlinkPathsSync (srcpath, dstpath) {+ let exists;+ if (path__default['default'].isAbsolute(srcpath)) {+ exists = gracefulFs.existsSync(srcpath);+ if (!exists) throw new Error('absolute srcpath does not exist')+ return {+ toCwd: srcpath,+ toDst: srcpath+ }+ } else {+ const dstdir = path__default['default'].dirname(dstpath);+ const relativeToDst = path__default['default'].join(dstdir, srcpath);+ exists = gracefulFs.existsSync(relativeToDst);+ if (exists) {+ return {+ toCwd: relativeToDst,+ toDst: srcpath+ }+ } else {+ exists = gracefulFs.existsSync(srcpath);+ if (!exists) throw new Error('relative srcpath does not exist')+ return {+ toCwd: srcpath,+ toDst: path__default['default'].relative(dstdir, srcpath)+ }+ }+ }+}++var symlinkPaths_1 = {+ symlinkPaths,+ symlinkPathsSync+};++function symlinkType (srcpath, type, callback) {+ callback = (typeof type === 'function') ? type : callback;+ type = (typeof type === 'function') ? false : type;+ if (type) return callback(null, type)+ gracefulFs.lstat(srcpath, (err, stats) => {+ if (err) return callback(null, 'file')+ type = (stats && stats.isDirectory()) ? 'dir' : 'file';+ callback(null, type);+ });+}++function symlinkTypeSync (srcpath, type) {+ let stats;++ if (type) return type+ try {+ stats = gracefulFs.lstatSync(srcpath);+ } catch {+ return 'file'+ }+ return (stats && stats.isDirectory()) ? 'dir' : 'file'+}++var symlinkType_1 = {+ symlinkType,+ symlinkTypeSync+};++const u$7 = universalify.fromCallback;++++const mkdirs$2 = mkdirs.mkdirs;+const mkdirsSync$1 = mkdirs.mkdirsSync;+++const symlinkPaths$1 = symlinkPaths_1.symlinkPaths;+const symlinkPathsSync$1 = symlinkPaths_1.symlinkPathsSync;+++const symlinkType$1 = symlinkType_1.symlinkType;+const symlinkTypeSync$1 = symlinkType_1.symlinkTypeSync;++const pathExists$4 = pathExists_1.pathExists;++function createSymlink (srcpath, dstpath, type, callback) {+ callback = (typeof type === 'function') ? type : callback;+ type = (typeof type === 'function') ? false : type;++ pathExists$4(dstpath, (err, destinationExists) => {+ if (err) return callback(err)+ if (destinationExists) return callback(null)+ symlinkPaths$1(srcpath, dstpath, (err, relative) => {+ if (err) return callback(err)+ srcpath = relative.toDst;+ symlinkType$1(relative.toCwd, type, (err, type) => {+ if (err) return callback(err)+ const dir = path__default['default'].dirname(dstpath);+ pathExists$4(dir, (err, dirExists) => {+ if (err) return callback(err)+ if (dirExists) return gracefulFs.symlink(srcpath, dstpath, type, callback)+ mkdirs$2(dir, err => {+ if (err) return callback(err)+ gracefulFs.symlink(srcpath, dstpath, type, callback);+ });+ });+ });+ });+ });+}++function createSymlinkSync (srcpath, dstpath, type) {+ const destinationExists = gracefulFs.existsSync(dstpath);+ if (destinationExists) return undefined++ const relative = symlinkPathsSync$1(srcpath, dstpath);+ srcpath = relative.toDst;+ type = symlinkTypeSync$1(relative.toCwd, type);+ const dir = path__default['default'].dirname(dstpath);+ const exists = gracefulFs.existsSync(dir);+ if (exists) return gracefulFs.symlinkSync(srcpath, dstpath, type)+ mkdirsSync$1(dir);+ return gracefulFs.symlinkSync(srcpath, dstpath, type)+}++var symlink = {+ createSymlink: u$7(createSymlink),+ createSymlinkSync+};++var ensure = {+ // file+ createFile: file.createFile,+ createFileSync: file.createFileSync,+ ensureFile: file.createFile,+ ensureFileSync: file.createFileSync,+ // link+ createLink: link.createLink,+ createLinkSync: link.createLinkSync,+ ensureLink: link.createLink,+ ensureLinkSync: link.createLinkSync,+ // symlink+ createSymlink: symlink.createSymlink,+ createSymlinkSync: symlink.createSymlinkSync,+ ensureSymlink: symlink.createSymlink,+ ensureSymlinkSync: symlink.createSymlinkSync+};++function stringify (obj, options = {}) {+ const EOL = options.EOL || '\n';++ const str = JSON.stringify(obj, options ? options.replacer : null, options.spaces);++ return str.replace(/\n/g, EOL) + EOL+}++function stripBom (content) {+ // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified+ if (Buffer.isBuffer(content)) content = content.toString('utf8');+ return content.replace(/^\uFEFF/, '')+}++var utils = { stringify, stripBom };++let _fs;+try {+ _fs = gracefulFs;+} catch (_) {+ _fs = fs__default['default'];+}++const { stringify: stringify$1, stripBom: stripBom$1 } = utils;++async function _readFile (file, options = {}) {+ if (typeof options === 'string') {+ options = { encoding: options };+ }++ const fs = options.fs || _fs;++ const shouldThrow = 'throws' in options ? options.throws : true;++ let data = await universalify.fromCallback(fs.readFile)(file, options);++ data = stripBom$1(data);++ let obj;+ try {+ obj = JSON.parse(data, options ? options.reviver : null);+ } catch (err) {+ if (shouldThrow) {+ err.message = `${file}: ${err.message}`;+ throw err+ } else {+ return null+ }+ }++ return obj+}++const readFile = universalify.fromPromise(_readFile);++function readFileSync (file, options = {}) {+ if (typeof options === 'string') {+ options = { encoding: options };+ }++ const fs = options.fs || _fs;++ const shouldThrow = 'throws' in options ? options.throws : true;++ try {+ let content = fs.readFileSync(file, options);+ content = stripBom$1(content);+ return JSON.parse(content, options.reviver)+ } catch (err) {+ if (shouldThrow) {+ err.message = `${file}: ${err.message}`;+ throw err+ } else {+ return null+ }+ }+}++async function _writeFile (file, obj, options = {}) {+ const fs = options.fs || _fs;++ const str = stringify$1(obj, options);++ await universalify.fromCallback(fs.writeFile)(file, str, options);+}++const writeFile = universalify.fromPromise(_writeFile);++function writeFileSync (file, obj, options = {}) {+ const fs = options.fs || _fs;++ const str = stringify$1(obj, options);+ // not sure if fs.writeFileSync returns anything, but just in case+ return fs.writeFileSync(file, str, options)+}++const jsonfile = {+ readFile,+ readFileSync,+ writeFile,+ writeFileSync+};++var jsonfile_1 = jsonfile;++var jsonfile$1 = {+ // jsonfile exports+ readJson: jsonfile_1.readFile,+ readJsonSync: jsonfile_1.readFileSync,+ writeJson: jsonfile_1.writeFile,+ writeJsonSync: jsonfile_1.writeFileSync+};++const u$8 = universalify.fromCallback;++++const pathExists$5 = pathExists_1.pathExists;++function outputFile (file, data, encoding, callback) {+ if (typeof encoding === 'function') {+ callback = encoding;+ encoding = 'utf8';+ }++ const dir = path__default['default'].dirname(file);+ pathExists$5(dir, (err, itDoes) => {+ if (err) return callback(err)+ if (itDoes) return gracefulFs.writeFile(file, data, encoding, callback)++ mkdirs.mkdirs(dir, err => {+ if (err) return callback(err)++ gracefulFs.writeFile(file, data, encoding, callback);+ });+ });+}++function outputFileSync (file, ...args) {+ const dir = path__default['default'].dirname(file);+ if (gracefulFs.existsSync(dir)) {+ return gracefulFs.writeFileSync(file, ...args)+ }+ mkdirs.mkdirsSync(dir);+ gracefulFs.writeFileSync(file, ...args);+}++var output = {+ outputFile: u$8(outputFile),+ outputFileSync+};++const { stringify: stringify$2 } = utils;+const { outputFile: outputFile$1 } = output;++async function outputJson (file, data, options = {}) {+ const str = stringify$2(data, options);++ await outputFile$1(file, str, options);+}++var outputJson_1 = outputJson;++const { stringify: stringify$3 } = utils;+const { outputFileSync: outputFileSync$1 } = output;++function outputJsonSync (file, data, options) {+ const str = stringify$3(data, options);++ outputFileSync$1(file, str, options);+}++var outputJsonSync_1 = outputJsonSync;++const u$9 = universalify.fromPromise;+++jsonfile$1.outputJson = u$9(outputJson_1);+jsonfile$1.outputJsonSync = outputJsonSync_1;+// aliases+jsonfile$1.outputJSON = jsonfile$1.outputJson;+jsonfile$1.outputJSONSync = jsonfile$1.outputJsonSync;+jsonfile$1.writeJSON = jsonfile$1.writeJson;+jsonfile$1.writeJSONSync = jsonfile$1.writeJsonSync;+jsonfile$1.readJSON = jsonfile$1.readJson;+jsonfile$1.readJSONSync = jsonfile$1.readJsonSync;++var json = jsonfile$1;++const copySync$2 = copySync$1.copySync;+const removeSync = remove.removeSync;+const mkdirpSync = mkdirs.mkdirpSync;+++function moveSync (src, dest, opts) {+ opts = opts || {};+ const overwrite = opts.overwrite || opts.clobber || false;++ const { srcStat } = stat_1.checkPathsSync(src, dest, 'move');+ stat_1.checkParentPathsSync(src, srcStat, dest, 'move');+ mkdirpSync(path__default['default'].dirname(dest));+ return doRename(src, dest, overwrite)+}++function doRename (src, dest, overwrite) {+ if (overwrite) {+ removeSync(dest);+ return rename(src, dest, overwrite)+ }+ if (gracefulFs.existsSync(dest)) throw new Error('dest already exists.')+ return rename(src, dest, overwrite)+}++function rename (src, dest, overwrite) {+ try {+ gracefulFs.renameSync(src, dest);+ } catch (err) {+ if (err.code !== 'EXDEV') throw err+ return moveAcrossDevice(src, dest, overwrite)+ }+}++function moveAcrossDevice (src, dest, overwrite) {+ const opts = {+ overwrite,+ errorOnExist: true+ };+ copySync$2(src, dest, opts);+ return removeSync(src)+}++var moveSync_1 = moveSync;++var moveSync$1 = {+ moveSync: moveSync_1+};++const copy$2 = copy$1.copy;+const remove$1 = remove.remove;+const mkdirp = mkdirs.mkdirp;+const pathExists$6 = pathExists_1.pathExists;+++function move (src, dest, opts, cb) {+ if (typeof opts === 'function') {+ cb = opts;+ opts = {};+ }++ const overwrite = opts.overwrite || opts.clobber || false;++ stat_1.checkPaths(src, dest, 'move', (err, stats) => {+ if (err) return cb(err)+ const { srcStat } = stats;+ stat_1.checkParentPaths(src, srcStat, dest, 'move', err => {+ if (err) return cb(err)+ mkdirp(path__default['default'].dirname(dest), err => {+ if (err) return cb(err)+ return doRename$1(src, dest, overwrite, cb)+ });+ });+ });+}++function doRename$1 (src, dest, overwrite, cb) {+ if (overwrite) {+ return remove$1(dest, err => {+ if (err) return cb(err)+ return rename$1(src, dest, overwrite, cb)+ })+ }+ pathExists$6(dest, (err, destExists) => {+ if (err) return cb(err)+ if (destExists) return cb(new Error('dest already exists.'))+ return rename$1(src, dest, overwrite, cb)+ });+}++function rename$1 (src, dest, overwrite, cb) {+ gracefulFs.rename(src, dest, err => {+ if (!err) return cb()+ if (err.code !== 'EXDEV') return cb(err)+ return moveAcrossDevice$1(src, dest, overwrite, cb)+ });+}++function moveAcrossDevice$1 (src, dest, overwrite, cb) {+ const opts = {+ overwrite,+ errorOnExist: true+ };+ copy$2(src, dest, opts, err => {+ if (err) return cb(err)+ return remove$1(src, cb)+ });+}++var move_1 = move;++const u$a = universalify.fromCallback;+var move$1 = {+ move: u$a(move_1)+};++var lib = createCommonjsModule(function (module) {++module.exports = {+ // Export promiseified graceful-fs:+ ...fs_1,+ // Export extra methods:+ ...copySync$1,+ ...copy$1,+ ...empty,+ ...ensure,+ ...json,+ ...mkdirs,+ ...moveSync$1,+ ...move$1,+ ...output,+ ...pathExists_1,+ ...remove+};++// Export fs.promises as a getter property so that we don't trigger+// ExperimentalWarning before fs.promises is actually accessed.++if (Object.getOwnPropertyDescriptor(fs__default['default'], 'promises')) {+ Object.defineProperty(module.exports, 'promises', {+ get () { return fs__default['default'].promises }+ });+}+});++const resolveFrom = (fromDirectory, moduleId, silent) => {+ if (typeof fromDirectory !== 'string') {+ throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``);+ }++ if (typeof moduleId !== 'string') {+ throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);+ }++ try {+ fromDirectory = fs__default['default'].realpathSync(fromDirectory);+ } catch (error) {+ if (error.code === 'ENOENT') {+ fromDirectory = path__default['default'].resolve(fromDirectory);+ } else if (silent) {+ return;+ } else {+ throw error;+ }+ }++ const fromFile = path__default['default'].join(fromDirectory, 'noop.js');++ const resolveFileName = () => Module__default['default']._resolveFilename(moduleId, {+ id: fromFile,+ filename: fromFile,+ paths: Module__default['default']._nodeModulePaths(fromDirectory)+ });++ if (silent) {+ try {+ return resolveFileName();+ } catch (error) {+ return;+ }+ }++ return resolveFileName();+};++var resolveFrom_1 = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId);+var silent = (fromDirectory, moduleId) => resolveFrom(fromDirectory, moduleId, true);+resolveFrom_1.silent = silent;++/* eslint-disable no-unused-expressions */+const builtinTypes = ['String', 'Float', 'Int', 'Boolean', 'ID', 'Upload'];+const builtinDirectives = [+ 'deprecated',+ 'skip',+ 'include',+ 'cacheControl',+ 'key',+ 'external',+ 'requires',+ 'provides',+ 'connection',+ 'client',+];+const IMPORT_FROM_REGEX = /^import\s+(\*|(.*))\s+from\s+('|")(.*)('|");?$/;+const IMPORT_DEFAULT_REGEX = /^import\s+('|")(.*)('|");?$/;+function processImport(filePath, cwd = process.cwd(), predefinedImports = {}) {+ const visitedFiles = new Map();+ const set = visitFile(filePath, path.join(cwd + '/root.graphql'), visitedFiles, predefinedImports);+ const definitionSet = new Set();+ for (const defs of set.values()) {+ for (const def of defs) {+ definitionSet.add(def);+ }+ }+ return {+ kind: Kind.DOCUMENT,+ definitions: [...definitionSet],+ };+}+function visitFile(filePath, cwd, visitedFiles, predefinedImports) {+ if (!path.isAbsolute(filePath) && !(filePath in predefinedImports)) {+ filePath = resolveFilePath(cwd, filePath);+ }+ if (!visitedFiles.has(filePath)) {+ const fileContent = filePath in predefinedImports ? predefinedImports[filePath] : lib.readFileSync(filePath, 'utf8');+ const importLines = [];+ let otherLines = '';+ for (const line of fileContent.split('\n')) {+ const trimmedLine = line.trim();+ if (trimmedLine.startsWith('#import ') || trimmedLine.startsWith('# import ')) {+ importLines.push(trimmedLine);+ }+ else if (trimmedLine) {+ otherLines += line + '\n';+ }+ }+ const definitionsByName = new Map();+ const dependenciesByDefinitionName = new Map();+ if (otherLines) {+ const fileDefinitionMap = new Map();+ // To prevent circular dependency+ visitedFiles.set(filePath, fileDefinitionMap);+ const document = parse(new Source(otherLines, filePath), {+ noLocation: true,+ });+ for (const definition of document.definitions) {+ if ('name' in definition || definition.kind === Kind.SCHEMA_DEFINITION) {+ const definitionName = 'name' in definition ? definition.name.value : 'schema';+ if (!definitionsByName.has(definitionName)) {+ definitionsByName.set(definitionName, new Set());+ }+ const definitionsSet = definitionsByName.get(definitionName);+ definitionsSet.add(definition);+ if (!dependenciesByDefinitionName.has(definitionName)) {+ dependenciesByDefinitionName.set(definitionName, new Set());+ }+ const dependencySet = dependenciesByDefinitionName.get(definitionName);+ switch (definition.kind) {+ case Kind.OPERATION_DEFINITION:+ visitOperationDefinitionNode(definition, dependencySet);+ break;+ case Kind.FRAGMENT_DEFINITION:+ visitFragmentDefinitionNode(definition, dependencySet);+ break;+ case Kind.OBJECT_TYPE_DEFINITION:+ visitObjectTypeDefinitionNode(definition, dependencySet, dependenciesByDefinitionName);+ break;+ case Kind.INTERFACE_TYPE_DEFINITION:+ visitInterfaceTypeDefinitionNode(definition, dependencySet, dependenciesByDefinitionName);+ break;+ case Kind.UNION_TYPE_DEFINITION:+ visitUnionTypeDefinitionNode(definition, dependencySet);+ break;+ case Kind.ENUM_TYPE_DEFINITION:+ visitEnumTypeDefinitionNode(definition, dependencySet);+ break;+ case Kind.INPUT_OBJECT_TYPE_DEFINITION:+ visitInputObjectTypeDefinitionNode(definition, dependencySet);+ break;+ case Kind.DIRECTIVE_DEFINITION:+ visitDirectiveDefinitionNode(definition, dependencySet);+ break;+ case Kind.SCALAR_TYPE_DEFINITION:+ visitScalarDefinitionNode(definition, dependencySet);+ break;+ case Kind.SCHEMA_DEFINITION:+ visitSchemaDefinitionNode(definition, dependencySet);+ break;+ case Kind.OBJECT_TYPE_EXTENSION:+ visitObjectTypeExtensionNode(definition, dependencySet, dependenciesByDefinitionName);+ break;+ case Kind.INTERFACE_TYPE_EXTENSION:+ visitInterfaceTypeExtensionNode(definition, dependencySet, dependenciesByDefinitionName);+ break;+ case Kind.UNION_TYPE_EXTENSION:+ visitUnionTypeExtensionNode(definition, dependencySet);+ break;+ case Kind.ENUM_TYPE_EXTENSION:+ visitEnumTypeExtensionNode(definition, dependencySet);+ break;+ case Kind.INPUT_OBJECT_TYPE_EXTENSION:+ visitInputObjectTypeExtensionNode(definition, dependencySet);+ break;+ case Kind.SCALAR_TYPE_EXTENSION:+ visitScalarExtensionNode(definition, dependencySet);+ break;+ }+ if ('fields' in definition) {+ for (const field of definition.fields) {+ const definitionName = definition.name.value + '.' + field.name.value;+ if (!definitionsByName.has(definitionName)) {+ definitionsByName.set(definitionName, new Set());+ }+ const definitionsSet = definitionsByName.get(definitionName);+ definitionsSet.add({+ ...definition,+ fields: [field],+ });+ if (!dependenciesByDefinitionName.has(definitionName)) {+ dependenciesByDefinitionName.set(definitionName, new Set());+ }+ const dependencySet = dependenciesByDefinitionName.get(definitionName);+ switch (field.kind) {+ case Kind.FIELD_DEFINITION:+ visitFieldDefinitionNode(field, dependencySet);+ break;+ case Kind.INPUT_VALUE_DEFINITION:+ visitInputValueDefinitionNode(field, dependencySet);+ break;+ }+ }+ }+ }+ }+ for (const [definitionName, definitions] of definitionsByName) {+ if (!fileDefinitionMap.has(definitionName)) {+ fileDefinitionMap.set(definitionName, new Set());+ }+ const definitionsWithDependencies = fileDefinitionMap.get(definitionName);+ for (const definition of definitions) {+ definitionsWithDependencies.add(definition);+ }+ const dependenciesOfDefinition = dependenciesByDefinitionName.get(definitionName);+ for (const dependencyName of dependenciesOfDefinition) {+ const dependencyDefinitions = definitionsByName.get(dependencyName);+ dependencyDefinitions === null || dependencyDefinitions === void 0 ? void 0 : dependencyDefinitions.forEach(dependencyDefinition => {+ definitionsWithDependencies.add(dependencyDefinition);+ });+ }+ }+ }+ const allImportedDefinitionsMap = new Map();+ for (const line of importLines) {+ const { imports, from } = parseImportLine(line.replace('#', '').trim());+ const importFileDefinitionMap = visitFile(from, filePath, visitedFiles, predefinedImports);+ if (imports.includes('*')) {+ for (const [importedDefinitionName, importedDefinitions] of importFileDefinitionMap) {+ const [importedDefinitionTypeName] = importedDefinitionName.split('.');+ if (!allImportedDefinitionsMap.has(importedDefinitionTypeName)) {+ allImportedDefinitionsMap.set(importedDefinitionTypeName, new Set());+ }+ const allImportedDefinitions = allImportedDefinitionsMap.get(importedDefinitionTypeName);+ for (const importedDefinition of importedDefinitions) {+ allImportedDefinitions.add(importedDefinition);+ }+ }+ }+ else {+ for (let importedDefinitionName of imports) {+ if (importedDefinitionName.endsWith('.*')) {+ // Adding whole type means the same thing with adding every single field+ importedDefinitionName = importedDefinitionName.replace('.*', '');+ }+ const [importedDefinitionTypeName] = importedDefinitionName.split('.');+ if (!allImportedDefinitionsMap.has(importedDefinitionTypeName)) {+ allImportedDefinitionsMap.set(importedDefinitionTypeName, new Set());+ }+ const allImportedDefinitions = allImportedDefinitionsMap.get(importedDefinitionTypeName);+ const importedDefinitions = importFileDefinitionMap.get(importedDefinitionName);+ if (!importedDefinitions) {+ throw new Error(`${importedDefinitionName} is not exported by ${from} imported by ${filePath}`);+ }+ for (const importedDefinition of importedDefinitions) {+ allImportedDefinitions.add(importedDefinition);+ }+ }+ }+ }+ if (!otherLines) {+ visitedFiles.set(filePath, allImportedDefinitionsMap);+ }+ else {+ const fileDefinitionMap = visitedFiles.get(filePath);+ for (const [definitionName] of definitionsByName) {+ const addDefinition = (definition) => {+ definitionsWithDependencies.add(definition);+ // Regenerate field exports if some fields are imported after visitor+ if ('fields' in definition) {+ for (const field of definition.fields) {+ const fieldName = field.name.value;+ const fieldDefinitionName = definition.name.value + '.' + fieldName;+ const allImportedDefinitions = allImportedDefinitionsMap.get(definitionName);+ allImportedDefinitions === null || allImportedDefinitions === void 0 ? void 0 : allImportedDefinitions.forEach(importedDefinition => {+ if (!fileDefinitionMap.has(fieldDefinitionName)) {+ fileDefinitionMap.set(fieldDefinitionName, new Set());+ }+ const definitionsWithDeps = fileDefinitionMap.get(fieldDefinitionName);+ definitionsWithDeps.add(importedDefinition);+ });+ }+ }+ };+ const definitionsWithDependencies = fileDefinitionMap.get(definitionName);+ const allImportedDefinitions = allImportedDefinitionsMap.get(definitionName);+ allImportedDefinitions === null || allImportedDefinitions === void 0 ? void 0 : allImportedDefinitions.forEach(importedDefinition => {+ addDefinition(importedDefinition);+ });+ const dependenciesOfDefinition = dependenciesByDefinitionName.get(definitionName);+ for (const dependencyName of dependenciesOfDefinition) {+ // If that dependency cannot be found both in imports and this file, throw an error+ if (!allImportedDefinitionsMap.has(dependencyName) && !definitionsByName.has(dependencyName)) {+ throw new Error(`Couldn't find type ${dependencyName} in any of the schemas.`);+ }+ const dependencyDefinitionsFromImports = allImportedDefinitionsMap.get(dependencyName);+ dependencyDefinitionsFromImports === null || dependencyDefinitionsFromImports === void 0 ? void 0 : dependencyDefinitionsFromImports.forEach(dependencyDefinition => {+ addDefinition(dependencyDefinition);+ });+ }+ }+ }+ }+ return visitedFiles.get(filePath);+}+function parseImportLine(importLine) {+ if (IMPORT_FROM_REGEX.test(importLine)) {+ // Apply regex to import line+ // Extract matches into named variables+ const [, wildcard, importsString, , from] = importLine.match(IMPORT_FROM_REGEX);+ if (from) {+ // Extract imported types+ const imports = wildcard === '*' ? ['*'] : importsString.split(',').map(d => d.trim());+ // Return information about the import line+ return { imports, from };+ }+ }+ else if (IMPORT_DEFAULT_REGEX.test(importLine)) {+ const [, , from] = importLine.match(IMPORT_DEFAULT_REGEX);+ if (from) {+ return { imports: ['*'], from };+ }+ }+ throw new Error(`+ Import statement is not valid:+ > ${importLine}+ If you want to have comments starting with '# import', please use ''' instead!+ You can only have 'import' statements in the following pattern;+ # import [Type].[Field] from [File]+ `);+}+function resolveFilePath(filePath, importFrom) {+ const dirName = path.dirname(filePath);+ try {+ const fullPath = path.join(dirName, importFrom);+ return lib.realpathSync(fullPath);+ }+ catch (e) {+ if (e.code === 'ENOENT') {+ return resolveFrom_1(dirName, importFrom);+ }+ }+}+function visitOperationDefinitionNode(node, dependencySet) {+ dependencySet.add(node.name.value);+ node.selectionSet.selections.forEach(selectionNode => visitSelectionNode(selectionNode, dependencySet));+}+function visitSelectionNode(node, dependencySet) {+ switch (node.kind) {+ case Kind.FIELD:+ visitFieldNode(node, dependencySet);+ break;+ case Kind.FRAGMENT_SPREAD:+ visitFragmentSpreadNode(node, dependencySet);+ break;+ case Kind.INLINE_FRAGMENT:+ visitInlineFragmentNode(node, dependencySet);+ break;+ }+}+function visitFieldNode(node, dependencySet) {+ var _a;+ (_a = node.selectionSet) === null || _a === void 0 ? void 0 : _a.selections.forEach(selectionNode => visitSelectionNode(selectionNode, dependencySet));+}+function visitFragmentSpreadNode(node, dependencySet) {+ dependencySet.add(node.name.value);+}+function visitInlineFragmentNode(node, dependencySet) {+ node.selectionSet.selections.forEach(selectionNode => visitSelectionNode(selectionNode, dependencySet));+}+function visitFragmentDefinitionNode(node, dependencySet) {+ dependencySet.add(node.name.value);+ node.selectionSet.selections.forEach(selectionNode => visitSelectionNode(selectionNode, dependencySet));+}+function visitObjectTypeDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a, _b, _c;+ const typeName = node.name.value;+ dependencySet.add(typeName);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(fieldDefinitionNode => visitFieldDefinitionNode(fieldDefinitionNode, dependencySet));+ (_c = node.interfaces) === null || _c === void 0 ? void 0 : _c.forEach(namedTypeNode => {+ visitNamedTypeNode(namedTypeNode, dependencySet);+ const interfaceName = namedTypeNode.name.value;+ // interface should be dependent to the type as well+ if (!dependenciesByDefinitionName.has(interfaceName)) {+ dependenciesByDefinitionName.set(interfaceName, new Set());+ }+ dependenciesByDefinitionName.get(interfaceName).add(typeName);+ });+}+function visitDirectiveNode(node, dependencySet) {+ const directiveName = node.name.value;+ if (!builtinDirectives.includes(directiveName)) {+ dependencySet.add(node.name.value);+ }+}+function visitFieldDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a, _b;+ (_a = node.arguments) === null || _a === void 0 ? void 0 : _a.forEach(inputValueDefinitionNode => visitInputValueDefinitionNode(inputValueDefinitionNode, dependencySet));+ (_b = node.directives) === null || _b === void 0 ? void 0 : _b.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ visitTypeNode(node.type, dependencySet);+}+function visitTypeNode(node, dependencySet, dependenciesByDefinitionName) {+ switch (node.kind) {+ case Kind.LIST_TYPE:+ visitListTypeNode(node, dependencySet);+ break;+ case Kind.NON_NULL_TYPE:+ visitNonNullTypeNode(node, dependencySet);+ break;+ case Kind.NAMED_TYPE:+ visitNamedTypeNode(node, dependencySet);+ break;+ }+}+function visitListTypeNode(node, dependencySet, dependenciesByDefinitionName) {+ visitTypeNode(node.type, dependencySet);+}+function visitNonNullTypeNode(node, dependencySet, dependenciesByDefinitionName) {+ visitTypeNode(node.type, dependencySet);+}+function visitNamedTypeNode(node, dependencySet) {+ const namedTypeName = node.name.value;+ if (!builtinTypes.includes(namedTypeName)) {+ dependencySet.add(node.name.value);+ }+}+function visitInputValueDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a;+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ visitTypeNode(node.type, dependencySet);+}+function visitInterfaceTypeDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a, _b, _c;+ const typeName = node.name.value;+ dependencySet.add(typeName);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(fieldDefinitionNode => visitFieldDefinitionNode(fieldDefinitionNode, dependencySet));+ (_c = node.interfaces) === null || _c === void 0 ? void 0 : _c.forEach((namedTypeNode) => {+ visitNamedTypeNode(namedTypeNode, dependencySet);+ const interfaceName = namedTypeNode.name.value;+ // interface should be dependent to the type as well+ if (!dependenciesByDefinitionName.has(interfaceName)) {+ dependenciesByDefinitionName.set(interfaceName, new Set());+ }+ dependenciesByDefinitionName.get(interfaceName).add(typeName);+ });+}+function visitUnionTypeDefinitionNode(node, dependencySet) {+ var _a;+ dependencySet.add(node.name.value);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ node.types.forEach(namedTypeNode => visitNamedTypeNode(namedTypeNode, dependencySet));+}+function visitEnumTypeDefinitionNode(node, dependencySet) {+ var _a;+ dependencySet.add(node.name.value);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+}+function visitInputObjectTypeDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a, _b;+ dependencySet.add(node.name.value);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(inputValueDefinitionNode => visitInputValueDefinitionNode(inputValueDefinitionNode, dependencySet));+}+function visitDirectiveDefinitionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a;+ dependencySet.add(node.name.value);+ (_a = node.arguments) === null || _a === void 0 ? void 0 : _a.forEach(inputValueDefinitionNode => visitInputValueDefinitionNode(inputValueDefinitionNode, dependencySet));+}+function visitObjectTypeExtensionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a, _b, _c;+ const typeName = node.name.value;+ dependencySet.add(typeName);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(fieldDefinitionNode => visitFieldDefinitionNode(fieldDefinitionNode, dependencySet));+ (_c = node.interfaces) === null || _c === void 0 ? void 0 : _c.forEach(namedTypeNode => {+ visitNamedTypeNode(namedTypeNode, dependencySet);+ const interfaceName = namedTypeNode.name.value;+ // interface should be dependent to the type as well+ if (!dependenciesByDefinitionName.has(interfaceName)) {+ dependenciesByDefinitionName.set(interfaceName, new Set());+ }+ dependenciesByDefinitionName.get(interfaceName).add(typeName);+ });+}+function visitInterfaceTypeExtensionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a, _b, _c;+ const typeName = node.name.value;+ dependencySet.add(typeName);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(fieldDefinitionNode => visitFieldDefinitionNode(fieldDefinitionNode, dependencySet));+ (_c = node.interfaces) === null || _c === void 0 ? void 0 : _c.forEach((namedTypeNode) => {+ visitNamedTypeNode(namedTypeNode, dependencySet);+ const interfaceName = namedTypeNode.name.value;+ // interface should be dependent to the type as well+ if (!dependenciesByDefinitionName.has(interfaceName)) {+ dependenciesByDefinitionName.set(interfaceName, new Set());+ }+ dependenciesByDefinitionName.get(interfaceName).add(typeName);+ });+}+function visitUnionTypeExtensionNode(node, dependencySet) {+ var _a;+ dependencySet.add(node.name.value);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ node.types.forEach(namedTypeNode => visitNamedTypeNode(namedTypeNode, dependencySet));+}+function visitEnumTypeExtensionNode(node, dependencySet) {+ var _a;+ dependencySet.add(node.name.value);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+}+function visitInputObjectTypeExtensionNode(node, dependencySet, dependenciesByDefinitionName) {+ var _a, _b;+ dependencySet.add(node.name.value);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ (_b = node.fields) === null || _b === void 0 ? void 0 : _b.forEach(inputValueDefinitionNode => visitInputValueDefinitionNode(inputValueDefinitionNode, dependencySet));+}+function visitSchemaDefinitionNode(node, dependencySet) {+ var _a;+ dependencySet.add('schema');+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+ node.operationTypes.forEach(operationTypeDefinitionNode => visitOperationTypeDefinitionNode(operationTypeDefinitionNode, dependencySet));+}+function visitScalarDefinitionNode(node, dependencySet) {+ var _a;+ dependencySet.add(node.name.value);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+}+function visitScalarExtensionNode(node, dependencySet) {+ var _a;+ dependencySet.add(node.name.value);+ (_a = node.directives) === null || _a === void 0 ? void 0 : _a.forEach(directiveNode => visitDirectiveNode(directiveNode, dependencySet));+}+function visitOperationTypeDefinitionNode(node, dependencySet) {+ visitNamedTypeNode(node.type, dependencySet);+}++function mergeArguments(args1, args2, config) {+ const result = deduplicateArguments([].concat(args2, args1).filter(a => a));+ if (config && config.sort) {+ result.sort(compareNodes);+ }+ return result;+}+function deduplicateArguments(args) {+ return args.reduce((acc, current) => {+ const dup = acc.find(arg => arg.name.value === current.name.value);+ if (!dup) {+ return acc.concat([current]);+ }+ return acc;+ }, []);+}++let commentsRegistry = {};+function resetComments() {+ commentsRegistry = {};+}+function collectComment(node) {+ const entityName = node.name.value;+ pushComment(node, entityName);+ switch (node.kind) {+ case 'EnumTypeDefinition':+ node.values.forEach(value => {+ pushComment(value, entityName, value.name.value);+ });+ break;+ case 'ObjectTypeDefinition':+ case 'InputObjectTypeDefinition':+ case 'InterfaceTypeDefinition':+ if (node.fields) {+ node.fields.forEach((field) => {+ pushComment(field, entityName, field.name.value);+ if (isFieldDefinitionNode(field) && field.arguments) {+ field.arguments.forEach(arg => {+ pushComment(arg, entityName, field.name.value, arg.name.value);+ });+ }+ });+ }+ break;+ }+}+function pushComment(node, entity, field, argument) {+ const comment = getDescription(node, { commentDescriptions: true });+ if (typeof comment !== 'string' || comment.length === 0) {+ return;+ }+ const keys = [entity];+ if (field) {+ keys.push(field);+ if (argument) {+ keys.push(argument);+ }+ }+ const path = keys.join('.');+ if (!commentsRegistry[path]) {+ commentsRegistry[path] = [];+ }+ commentsRegistry[path].push(comment);+}+function printComment(comment) {+ return '\n# ' + comment.replace(/\n/g, '\n# ');+}+/**+ * 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.+ */+/**+ * NOTE: ==> This file has been modified just to add comments to the printed AST+ * This is a temp measure, we will move to using the original non modified printer.js ASAP.+ */+// import { visit, VisitFn } from 'graphql/language/visitor';+/**+ * Given maybeArray, print an empty string if it is null or empty, otherwise+ * print all items together separated by separator if provided+ */+function join$1(maybeArray, separator) {+ return maybeArray ? maybeArray.filter(x => x).join(separator || '') : '';+}+function addDescription$1(cb) {+ return (node, _key, _parent, path, ancestors) => {+ const keys = [];+ const parent = path.reduce((prev, key) => {+ if (['fields', 'arguments', 'values'].includes(key)) {+ keys.push(prev.name.value);+ }+ return prev[key];+ }, ancestors[0]);+ const key = [...keys, parent.name.value].join('.');+ const items = [];+ if (commentsRegistry[key]) {+ items.push(...commentsRegistry[key]);+ }+ return join$1([...items.map(printComment), node.description, cb(node)], '\n');+ };+}+function indent$1(maybeString) {+ return maybeString && ` ${maybeString.replace(/\n/g, '\n ')}`;+}+/**+ * Given array, print each item on its own line, wrapped in an+ * indented "{ }" block.+ */+function block$1(array) {+ return array && array.length !== 0 ? `{\n${indent$1(join$1(array, '\n'))}\n}` : '';+}+/**+ * If maybeString is not null or empty, then wrap with start and end, otherwise+ * print an empty string.+ */+function wrap$1(start, maybeString, end) {+ return maybeString ? start + maybeString + (end || '') : '';+}+/**+ * 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$1(value, isDescription) {+ const escaped = value.replace(/"""/g, '\\"""');+ return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1+ ? `"""${escaped.replace(/"$/, '"\n')}"""`+ : `"""\n${isDescription ? escaped : indent$1(escaped)}\n"""`;+}+/**+ * Converts an AST into a string, using one set of reasonable+ * formatting rules.+ */+function printWithComments(ast) {+ return visit(ast, {+ leave: {+ Name: node => node.value,+ Variable: node => `$${node.name}`,+ // Document+ Document: node => `${node.definitions+ .map(defNode => `${defNode}\n${defNode[0] === '#' ? '' : '\n'}`)+ .join('')+ .trim()}\n`,+ OperationTypeDefinition: node => `${node.operation}: ${node.type}`,+ VariableDefinition: ({ variable, type, defaultValue }) => `${variable}: ${type}${wrap$1(' = ', defaultValue)}`,+ SelectionSet: ({ selections }) => block$1(selections),+ Field: ({ alias, name, arguments: args, directives, selectionSet }) => join$1([wrap$1('', alias, ': ') + name + wrap$1('(', join$1(args, ', '), ')'), join$1(directives, ' '), selectionSet], ' '),+ Argument: addDescription$1(({ name, value }) => `${name}: ${value}`),+ // Value+ IntValue: ({ value }) => value,+ FloatValue: ({ value }) => value,+ StringValue: ({ value, block: isBlockString }, key) => isBlockString ? printBlockString$1(value, key === 'description') : JSON.stringify(value),+ BooleanValue: ({ value }) => (value ? 'true' : 'false'),+ NullValue: () => 'null',+ EnumValue: ({ value }) => value,+ ListValue: ({ values }) => `[${join$1(values, ', ')}]`,+ ObjectValue: ({ fields }) => `{${join$1(fields, ', ')}}`,+ ObjectField: ({ name, value }) => `${name}: ${value}`,+ // Directive+ Directive: ({ name, arguments: args }) => `@${name}${wrap$1('(', join$1(args, ', '), ')')}`,+ // Type+ NamedType: ({ name }) => name,+ ListType: ({ type }) => `[${type}]`,+ NonNullType: ({ type }) => `${type}!`,+ // Type System Definitions+ SchemaDefinition: ({ directives, operationTypes }) => join$1(['schema', join$1(directives, ' '), block$1(operationTypes)], ' '),+ ScalarTypeDefinition: addDescription$1(({ name, directives }) => join$1(['scalar', name, join$1(directives, ' ')], ' ')),+ ObjectTypeDefinition: addDescription$1(({ name, interfaces, directives, fields }) => join$1(['type', name, wrap$1('implements ', join$1(interfaces, ' & ')), join$1(directives, ' '), block$1(fields)], ' ')),+ FieldDefinition: addDescription$1(({ name, arguments: args, type, directives }) => `${name + wrap$1('(', join$1(args, ', '), ')')}: ${type}${wrap$1(' ', join$1(directives, ' '))}`),+ InputValueDefinition: addDescription$1(({ name, type, defaultValue, directives }) => join$1([`${name}: ${type}`, wrap$1('= ', defaultValue), join$1(directives, ' ')], ' ')),+ InterfaceTypeDefinition: addDescription$1(({ name, directives, fields }) => join$1(['interface', name, join$1(directives, ' '), block$1(fields)], ' ')),+ UnionTypeDefinition: addDescription$1(({ name, directives, types }) => join$1(['union', name, join$1(directives, ' '), types && types.length !== 0 ? `= ${join$1(types, ' | ')}` : ''], ' ')),+ EnumTypeDefinition: addDescription$1(({ name, directives, values }) => join$1(['enum', name, join$1(directives, ' '), block$1(values)], ' ')),+ EnumValueDefinition: addDescription$1(({ name, directives }) => join$1([name, join$1(directives, ' ')], ' ')),+ InputObjectTypeDefinition: addDescription$1(({ name, directives, fields }) => join$1(['input', name, join$1(directives, ' '), block$1(fields)], ' ')),+ ScalarTypeExtension: ({ name, directives }) => join$1(['extend scalar', name, join$1(directives, ' ')], ' '),+ ObjectTypeExtension: ({ name, interfaces, directives, fields }) => join$1(['extend type', name, wrap$1('implements ', join$1(interfaces, ' & ')), join$1(directives, ' '), block$1(fields)], ' '),+ InterfaceTypeExtension: ({ name, directives, fields }) => join$1(['extend interface', name, join$1(directives, ' '), block$1(fields)], ' '),+ UnionTypeExtension: ({ name, directives, types }) => join$1(['extend union', name, join$1(directives, ' '), types && types.length !== 0 ? `= ${join$1(types, ' | ')}` : ''], ' '),+ EnumTypeExtension: ({ name, directives, values }) => join$1(['extend enum', name, join$1(directives, ' '), block$1(values)], ' '),+ InputObjectTypeExtension: ({ name, directives, fields }) => join$1(['extend input', name, join$1(directives, ' '), block$1(fields)], ' '),+ DirectiveDefinition: addDescription$1(({ name, arguments: args, locations }) => `directive @${name}${wrap$1('(', join$1(args, ', '), ')')} on ${join$1(locations, ' | ')}`),+ },+ });+}+function isFieldDefinitionNode(node) {+ return node.kind === 'FieldDefinition';+}++function directiveAlreadyExists(directivesArr, otherDirective) {+ return !!directivesArr.find(directive => directive.name.value === otherDirective.name.value);+}+function nameAlreadyExists(name, namesArr) {+ return namesArr.some(({ value }) => value === name.value);+}+function mergeArguments$1(a1, a2) {+ const result = [...a2];+ for (const argument of a1) {+ const existingIndex = result.findIndex(a => a.name.value === argument.name.value);+ if (existingIndex > -1) {+ const existingArg = result[existingIndex];+ if (existingArg.value.kind === 'ListValue') {+ const source = existingArg.value.values;+ const target = argument.value.values;+ // merge values of two lists+ existingArg.value.values = deduplicateLists(source, target, (targetVal, source) => {+ const value = targetVal.value;+ return !value || !source.some((sourceVal) => sourceVal.value === value);+ });+ }+ else {+ existingArg.value = argument.value;+ }+ }+ else {+ result.push(argument);+ }+ }+ return result;+}+function deduplicateDirectives(directives) {+ return directives+ .map((directive, i, all) => {+ const firstAt = all.findIndex(d => d.name.value === directive.name.value);+ if (firstAt !== i) {+ const dup = all[firstAt];+ directive.arguments = mergeArguments$1(directive.arguments, dup.arguments);+ return null;+ }+ return directive;+ })+ .filter(d => d);+}+function mergeDirectives(d1 = [], d2 = [], config) {+ const reverseOrder = config && config.reverseDirectives;+ const asNext = reverseOrder ? d1 : d2;+ const asFirst = reverseOrder ? d2 : d1;+ const result = deduplicateDirectives([...asNext]);+ for (const directive of asFirst) {+ if (directiveAlreadyExists(result, directive)) {+ const existingDirectiveIndex = result.findIndex(d => d.name.value === directive.name.value);+ const existingDirective = result[existingDirectiveIndex];+ result[existingDirectiveIndex].arguments = mergeArguments$1(directive.arguments || [], existingDirective.arguments || []);+ }+ else {+ result.push(directive);+ }+ }+ return result;+}+function validateInputs(node, existingNode) {+ const printedNode = print(node);+ const printedExistingNode = print(existingNode);+ const leaveInputs = new RegExp('(directive @w*d*)|( on .*$)', 'g');+ const sameArguments = printedNode.replace(leaveInputs, '') === printedExistingNode.replace(leaveInputs, '');+ if (!sameArguments) {+ throw new Error(`Unable to merge GraphQL directive "${node.name.value}". \nExisting directive: \n\t${printedExistingNode} \nReceived directive: \n\t${printedNode}`);+ }+}+function mergeDirective(node, existingNode) {+ if (existingNode) {+ validateInputs(node, existingNode);+ return {+ ...node,+ locations: [+ ...existingNode.locations,+ ...node.locations.filter(name => !nameAlreadyExists(name, existingNode.locations)),+ ],+ };+ }+ return node;+}+function deduplicateLists(source, target, filterFn) {+ return source.concat(target.filter(val => filterFn(val, source)));+}++function mergeEnumValues(first, second, config) {+ const enumValueMap = new Map();+ for (const firstValue of first) {+ enumValueMap.set(firstValue.name.value, firstValue);+ }+ for (const secondValue of second) {+ const enumValue = secondValue.name.value;+ if (enumValueMap.has(enumValue)) {+ const firstValue = enumValueMap.get(enumValue);+ firstValue.description = secondValue.description || firstValue.description;+ firstValue.directives = mergeDirectives(secondValue.directives, firstValue.directives);+ }+ else {+ enumValueMap.set(enumValue, secondValue);+ }+ }+ const result = [...enumValueMap.values()];+ if (config && config.sort) {+ result.sort(compareNodes);+ }+ return result;+}++function mergeEnum(e1, e2, config) {+ if (e2) {+ return {+ name: e1.name,+ description: e1['description'] || e2['description'],+ kind: (config && config.convertExtensions) || e1.kind === 'EnumTypeDefinition' || e2.kind === 'EnumTypeDefinition'+ ? 'EnumTypeDefinition'+ : 'EnumTypeExtension',+ loc: e1.loc,+ directives: mergeDirectives(e1.directives, e2.directives, config),+ values: mergeEnumValues(e1.values, e2.values, config),+ };+ }+ return config && config.convertExtensions+ ? {+ ...e1,+ kind: 'EnumTypeDefinition',+ }+ : e1;+}++function isStringTypes(types) {+ return typeof types === 'string';+}+function isSourceTypes(types) {+ return types instanceof Source;+}+function isGraphQLType(definition) {+ return definition.kind === 'ObjectTypeDefinition';+}+function isGraphQLTypeExtension(definition) {+ return definition.kind === 'ObjectTypeExtension';+}+function isGraphQLEnum(definition) {+ return definition.kind === 'EnumTypeDefinition';+}+function isGraphQLEnumExtension(definition) {+ return definition.kind === 'EnumTypeExtension';+}+function isGraphQLUnion(definition) {+ return definition.kind === 'UnionTypeDefinition';+}+function isGraphQLUnionExtension(definition) {+ return definition.kind === 'UnionTypeExtension';+}+function isGraphQLScalar(definition) {+ return definition.kind === 'ScalarTypeDefinition';+}+function isGraphQLScalarExtension(definition) {+ return definition.kind === 'ScalarTypeExtension';+}+function isGraphQLInputType(definition) {+ return definition.kind === 'InputObjectTypeDefinition';+}+function isGraphQLInputTypeExtension(definition) {+ return definition.kind === 'InputObjectTypeExtension';+}+function isGraphQLInterface(definition) {+ return definition.kind === 'InterfaceTypeDefinition';+}+function isGraphQLInterfaceExtension(definition) {+ return definition.kind === 'InterfaceTypeExtension';+}+function isGraphQLDirective(definition) {+ return definition.kind === 'DirectiveDefinition';+}+function extractType(type) {+ let visitedType = type;+ while (visitedType.kind === 'ListType' || visitedType.kind === 'NonNullType') {+ visitedType = visitedType.type;+ }+ return visitedType;+}+function isSchemaDefinition(node) {+ return node.kind === 'SchemaDefinition';+}+function isWrappingTypeNode(type) {+ return type.kind !== Kind.NAMED_TYPE;+}+function isListTypeNode(type) {+ return type.kind === Kind.LIST_TYPE;+}+function isNonNullTypeNode(type) {+ return type.kind === Kind.NON_NULL_TYPE;+}+function printTypeNode(type) {+ if (isListTypeNode(type)) {+ return `[${printTypeNode(type.type)}]`;+ }+ if (isNonNullTypeNode(type)) {+ return `${printTypeNode(type.type)}!`;+ }+ return type.name.value;+}++function fieldAlreadyExists(fieldsArr, otherField) {+ const result = fieldsArr.find(field => field.name.value === otherField.name.value);+ if (result) {+ const t1 = extractType(result.type);+ const t2 = extractType(otherField.type);+ if (t1.name.value !== t2.name.value) {+ throw new Error(`Field "${otherField.name.value}" already defined with a different type. Declared as "${t1.name.value}", but you tried to override with "${t2.name.value}"`);+ }+ }+ return !!result;+}+function mergeFields(type, f1, f2, config) {+ const result = [...f2];+ for (const field of f1) {+ if (fieldAlreadyExists(result, field)) {+ const existing = result.find((f) => f.name.value === field.name.value);+ if (config && config.throwOnConflict) {+ preventConflicts(type, existing, field, false);+ }+ else {+ preventConflicts(type, existing, field, true);+ }+ if (isNonNullTypeNode(field.type) && !isNonNullTypeNode(existing.type)) {+ existing.type = field.type;+ }+ existing.arguments = mergeArguments(field['arguments'] || [], existing.arguments || [], config);+ existing.directives = mergeDirectives(field.directives, existing.directives, config);+ existing.description = field.description || existing.description;+ }+ else {+ result.push(field);+ }+ }+ if (config && config.sort) {+ result.sort(compareNodes);+ }+ if (config && config.exclusions) {+ return result.filter(field => !config.exclusions.includes(`${type.name.value}.${field.name.value}`));+ }+ return result;+}+function preventConflicts(type, a, b, ignoreNullability = false) {+ const aType = printTypeNode(a.type);+ const bType = printTypeNode(b.type);+ if (isNotEqual(aType, bType)) {+ if (safeChangeForFieldType(a.type, b.type, ignoreNullability) === false) {+ throw new Error(`Field '${type.name.value}.${a.name.value}' changed type from '${aType}' to '${bType}'`);+ }+ }+}+function safeChangeForFieldType(oldType, newType, ignoreNullability = false) {+ // both are named+ if (!isWrappingTypeNode(oldType) && !isWrappingTypeNode(newType)) {+ return oldType.toString() === newType.toString();+ }+ // new is non-null+ if (isNonNullTypeNode(newType)) {+ const ofType = isNonNullTypeNode(oldType) ? oldType.type : oldType;+ return safeChangeForFieldType(ofType, newType.type);+ }+ // old is non-null+ if (isNonNullTypeNode(oldType)) {+ return safeChangeForFieldType(newType, oldType, ignoreNullability);+ }+ // old is list+ if (isListTypeNode(oldType)) {+ return ((isListTypeNode(newType) && safeChangeForFieldType(oldType.type, newType.type)) ||+ (isNonNullTypeNode(newType) && safeChangeForFieldType(oldType, newType['type'])));+ }+ return false;+}++function mergeInputType(node, existingNode, config) {+ if (existingNode) {+ try {+ return {+ name: node.name,+ description: node['description'] || existingNode['description'],+ kind: (config && config.convertExtensions) ||+ node.kind === 'InputObjectTypeDefinition' ||+ existingNode.kind === 'InputObjectTypeDefinition'+ ? 'InputObjectTypeDefinition'+ : 'InputObjectTypeExtension',+ loc: node.loc,+ fields: mergeFields(node, node.fields, existingNode.fields, config),+ directives: mergeDirectives(node.directives, existingNode.directives, config),+ };+ }+ catch (e) {+ throw new Error(`Unable to merge GraphQL input type "${node.name.value}": ${e.message}`);+ }+ }+ return config && config.convertExtensions+ ? {+ ...node,+ kind: 'InputObjectTypeDefinition',+ }+ : node;+}++function mergeInterface(node, existingNode, config) {+ if (existingNode) {+ try {+ return {+ name: node.name,+ description: node['description'] || existingNode['description'],+ kind: (config && config.convertExtensions) ||+ node.kind === 'InterfaceTypeDefinition' ||+ existingNode.kind === 'InterfaceTypeDefinition'+ ? 'InterfaceTypeDefinition'+ : 'InterfaceTypeExtension',+ loc: node.loc,+ fields: mergeFields(node, node.fields, existingNode.fields, config),+ directives: mergeDirectives(node.directives, existingNode.directives, config),+ };+ }+ catch (e) {+ throw new Error(`Unable to merge GraphQL interface "${node.name.value}": ${e.message}`);+ }+ }+ return config && config.convertExtensions+ ? {+ ...node,+ kind: 'InterfaceTypeDefinition',+ }+ : node;+}++function alreadyExists(arr, other) {+ return !!arr.find(i => i.name.value === other.name.value);+}+function mergeNamedTypeArray(first, second, config) {+ const result = [...second, ...first.filter(d => !alreadyExists(second, d))];+ if (config && config.sort) {+ result.sort(compareNodes);+ }+ return result;+}++function mergeType(node, existingNode, config) {+ if (existingNode) {+ try {+ return {+ name: node.name,+ description: node['description'] || existingNode['description'],+ kind: (config && config.convertExtensions) ||+ node.kind === 'ObjectTypeDefinition' ||+ existingNode.kind === 'ObjectTypeDefinition'+ ? 'ObjectTypeDefinition'+ : 'ObjectTypeExtension',+ loc: node.loc,+ fields: mergeFields(node, node.fields, existingNode.fields, config),+ directives: mergeDirectives(node.directives, existingNode.directives, config),+ interfaces: mergeNamedTypeArray(node.interfaces, existingNode.interfaces, config),+ };+ }+ catch (e) {+ throw new Error(`Unable to merge GraphQL type "${node.name.value}": ${e.message}`);+ }+ }+ return config && config.convertExtensions+ ? {+ ...node,+ kind: 'ObjectTypeDefinition',+ }+ : node;+}++function mergeUnion(first, second, config) {+ if (second) {+ return {+ name: first.name,+ description: first['description'] || second['description'],+ directives: mergeDirectives(first.directives, second.directives, config),+ kind: (config && config.convertExtensions) ||+ first.kind === 'UnionTypeDefinition' ||+ second.kind === 'UnionTypeDefinition'+ ? 'UnionTypeDefinition'+ : 'UnionTypeExtension',+ loc: first.loc,+ types: mergeNamedTypeArray(first.types, second.types, config),+ };+ }+ return config && config.convertExtensions+ ? {+ ...first,+ kind: 'UnionTypeDefinition',+ }+ : first;+}++function mergeGraphQLNodes(nodes, config) {+ return nodes.reduce((prev, nodeDefinition) => {+ const node = nodeDefinition;+ if (node && node.name && node.name.value) {+ const name = node.name.value;+ if (config && config.commentDescriptions) {+ collectComment(node);+ }+ if (config &&+ config.exclusions &&+ (config.exclusions.includes(name + '.*') || config.exclusions.includes(name))) {+ delete prev[name];+ }+ else if (isGraphQLType(nodeDefinition) || isGraphQLTypeExtension(nodeDefinition)) {+ prev[name] = mergeType(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLEnum(nodeDefinition) || isGraphQLEnumExtension(nodeDefinition)) {+ prev[name] = mergeEnum(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLUnion(nodeDefinition) || isGraphQLUnionExtension(nodeDefinition)) {+ prev[name] = mergeUnion(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLScalar(nodeDefinition) || isGraphQLScalarExtension(nodeDefinition)) {+ prev[name] = nodeDefinition;+ }+ else if (isGraphQLInputType(nodeDefinition) || isGraphQLInputTypeExtension(nodeDefinition)) {+ prev[name] = mergeInputType(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLInterface(nodeDefinition) || isGraphQLInterfaceExtension(nodeDefinition)) {+ prev[name] = mergeInterface(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLDirective(nodeDefinition)) {+ prev[name] = mergeDirective(nodeDefinition, prev[name]);+ }+ }+ return prev;+ }, {});+}++function mergeTypeDefs(types, config) {+ resetComments();+ const doc = {+ kind: Kind.DOCUMENT,+ definitions: mergeGraphQLTypes(types, {+ useSchemaDefinition: true,+ forceSchemaDefinition: false,+ throwOnConflict: false,+ commentDescriptions: false,+ ...config,+ }),+ };+ let result;+ if (config && config.commentDescriptions) {+ result = printWithComments(doc);+ }+ else {+ result = doc;+ }+ resetComments();+ return result;+}+function mergeGraphQLTypes(types, config) {+ resetComments();+ const allNodes = types+ .map(type => {+ if (Array.isArray(type)) {+ type = mergeTypeDefs(type);+ }+ if (isSchema(type)) {+ return parse(printSchemaWithDirectives(type));+ }+ else if (isStringTypes(type) || isSourceTypes(type)) {+ return parse(type);+ }+ return type;+ })+ .map(ast => ast.definitions)+ .reduce((defs, newDef = []) => [...defs, ...newDef], []);+ // XXX: right now we don't handle multiple schema definitions+ let schemaDef = allNodes.filter(isSchemaDefinition).reduce((def, node) => {+ node.operationTypes+ .filter(op => op.type.name.value)+ .forEach(op => {+ def[op.operation] = op.type.name.value;+ });+ return def;+ }, {+ query: null,+ mutation: null,+ subscription: null,+ });+ const mergedNodes = mergeGraphQLNodes(allNodes, config);+ const allTypes = Object.keys(mergedNodes);+ if (config && config.sort) {+ allTypes.sort(typeof config.sort === 'function' ? config.sort : undefined);+ }+ if (config && config.useSchemaDefinition) {+ const queryType = schemaDef.query ? schemaDef.query : allTypes.find(t => t === 'Query');+ const mutationType = schemaDef.mutation ? schemaDef.mutation : allTypes.find(t => t === 'Mutation');+ const subscriptionType = schemaDef.subscription ? schemaDef.subscription : allTypes.find(t => t === 'Subscription');+ schemaDef = {+ query: queryType,+ mutation: mutationType,+ subscription: subscriptionType,+ };+ }+ const schemaDefinition = createSchemaDefinition(schemaDef, {+ force: config.forceSchemaDefinition,+ });+ if (!schemaDefinition) {+ return Object.values(mergedNodes);+ }+ return [...Object.values(mergedNodes), parse(schemaDefinition).definitions[0]];+}++const FILE_EXTENSIONS = ['.gql', '.gqls', '.graphql', '.graphqls'];+function isGraphQLImportFile(rawSDL) {+ const trimmedRawSDL = rawSDL.trim();+ return trimmedRawSDL.startsWith('# import') || trimmedRawSDL.startsWith('#import');+}+/**+ * This loader loads documents and type definitions from `.graphql` files.+ *+ * You can load a single source:+ *+ * ```js+ * const schema = await loadSchema('schema.graphql', {+ * loaders: [+ * new GraphQLFileLoader()+ * ]+ * });+ * ```+ *+ * Or provide a glob pattern to load multiple sources:+ *+ * ```js+ * const schema = await loadSchema('graphql/*.graphql', {+ * loaders: [+ * new GraphQLFileLoader()+ * ]+ * });+ * ```+ */+class GraphQLFileLoader {+ loaderId() {+ return 'graphql-file';+ }+ async canLoad(pointer, options) {+ if (isValidPath(pointer)) {+ if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {+ const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);+ return lib.pathExists(normalizedFilePath);+ }+ }+ return false;+ }+ canLoadSync(pointer, options) {+ if (isValidPath(pointer)) {+ if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {+ const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);+ return lib.pathExistsSync(normalizedFilePath);+ }+ }+ return false;+ }+ async load(pointer, options) {+ const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);+ const rawSDL = await lib.readFile(normalizedFilePath, { encoding: 'utf8' });+ return this.handleFileContent(rawSDL, pointer, options);+ }+ loadSync(pointer, options) {+ const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);+ const rawSDL = lib.readFileSync(normalizedFilePath, { encoding: 'utf8' });+ return this.handleFileContent(rawSDL, pointer, options);+ }+ handleFileContent(rawSDL, pointer, options) {+ if (!options.skipGraphQLImport && isGraphQLImportFile(rawSDL)) {+ const document = processImport(pointer, options.cwd);+ const typeSystemDefinitions = document.definitions+ .filter(d => !isExecutableDefinitionNode(d))+ .map(definition => ({+ kind: Kind.DOCUMENT,+ definitions: [definition],+ }));+ const mergedTypeDefs = mergeTypeDefs(typeSystemDefinitions, { useSchemaDefinition: false });+ const executableDefinitions = document.definitions.filter(isExecutableDefinitionNode);+ return {+ location: pointer,+ document: {+ ...mergedTypeDefs,+ definitions: [...mergedTypeDefs.definitions, ...executableDefinitions],+ },+ };+ }+ return parseGraphQLSDL(pointer, rawSDL, options);+ }+}++const FILE_EXTENSIONS$1 = ['.json'];+/**+ * This loader loads documents and type definitions from JSON files.+ *+ * The JSON file can be the result of an introspection query made against a schema:+ *+ * ```js+ * const schema = await loadSchema('schema-introspection.json', {+ * loaders: [+ * new JsonFileLoader()+ * ]+ * });+ * ```+ *+ * Or it can be a `DocumentNode` object representing a GraphQL document or type definitions:+ *+ * ```js+ * const documents = await loadDocuments('queries/*.json', {+ * loaders: [+ * new GraphQLFileLoader()+ * ]+ * });+ * ```+ */+class JsonFileLoader {+ loaderId() {+ return 'json-file';+ }+ async canLoad(pointer, options) {+ if (isValidPath(pointer)) {+ if (FILE_EXTENSIONS$1.find(extension => pointer.endsWith(extension))) {+ const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);+ return lib.pathExists(normalizedFilePath);+ }+ }+ return false;+ }+ canLoadSync(pointer, options) {+ if (isValidPath(pointer)) {+ if (FILE_EXTENSIONS$1.find(extension => pointer.endsWith(extension))) {+ const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);+ return lib.pathExistsSync(normalizedFilePath);+ }+ }+ return false;+ }+ async load(pointer, options) {+ const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);+ try {+ const jsonContent = await lib.readFile(normalizedFilePath, { encoding: 'utf8' });+ return parseGraphQLJSON(pointer, jsonContent, options);+ }+ catch (e) {+ throw new Error(`Unable to read JSON file: ${normalizedFilePath}: ${e.message || /* istanbul ignore next */ e}`);+ }+ }+ loadSync(pointer, options) {+ const normalizedFilepath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process$1.cwd(), pointer);+ try {+ const jsonContent = lib.readFileSync(normalizedFilepath, 'utf8');+ return parseGraphQLJSON(pointer, jsonContent, options);+ }+ catch (e) {+ throw new Error(`Unable to read JSON file: ${normalizedFilepath}: ${e.message || /* istanbul ignore next */ e}`);+ }+ }+}++/*!+ * is-extglob <https://github.com/jonschlinkert/is-extglob>+ *+ * Copyright (c) 2014-2016, Jon Schlinkert.+ * Licensed under the MIT License.+ */++var isExtglob = function isExtglob(str) {+ if (typeof str !== 'string' || str === '') {+ return false;+ }++ var match;+ while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {+ if (match[2]) return true;+ str = str.slice(match.index + match[0].length);+ }++ return false;+};++/*!+ * is-glob <https://github.com/jonschlinkert/is-glob>+ *+ * Copyright (c) 2014-2017, Jon Schlinkert.+ * Released under the MIT License.+ */+++var chars = { '{': '}', '(': ')', '[': ']'};+var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;+var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;++var isGlob = function isGlob(str, options) {+ if (typeof str !== 'string' || str === '') {+ return false;+ }++ if (isExtglob(str)) {+ return true;+ }++ var regex = strictRegex;+ var match;++ // optionally relax regex+ if (options && options.strict === false) {+ regex = relaxedRegex;+ }++ while ((match = regex.exec(str))) {+ if (match[2]) return true;+ var idx = match.index + match[0].length;++ // if an open bracket/brace/paren is escaped,+ // set the index to the next closing character+ var open = match[1];+ var close = open ? chars[open] : null;+ if (open && close) {+ var n = str.indexOf(close, idx);+ if (n !== -1) {+ idx = n + 1;+ }+ }++ str = str.slice(idx);+ }+ return false;+};++const pTry = (fn, ...arguments_) => new Promise(resolve => {+ resolve(fn(...arguments_));+});++var pTry_1 = pTry;+// TODO: remove this in the next major version+var _default = pTry;+pTry_1.default = _default;++const pLimit = concurrency => {+ if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {+ throw new TypeError('Expected `concurrency` to be a number from 1 and up');+ }++ const queue = [];+ let activeCount = 0;++ const next = () => {+ activeCount--;++ if (queue.length > 0) {+ queue.shift()();+ }+ };++ const run = async (fn, resolve, ...args) => {+ activeCount++;++ // TODO: Get rid of `pTry`. It's not needed anymore.+ const result = pTry_1(fn, ...args);++ resolve(result);++ try {+ await result;+ } catch {}++ next();+ };++ const enqueue = (fn, resolve, ...args) => {+ queue.push(run.bind(null, fn, resolve, ...args));++ (async () => {+ // This function needs to wait until the next microtask before comparing+ // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously+ // when the run function is dequeued and called. The comparison in the if-statement+ // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.+ await Promise.resolve();++ if (activeCount < concurrency && queue.length > 0) {+ queue.shift()();+ }+ })();+ };++ const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));+ Object.defineProperties(generator, {+ activeCount: {+ get: () => activeCount+ },+ pendingCount: {+ get: () => queue.length+ },+ clearQueue: {+ value: () => {+ queue.length = 0;+ }+ }+ });++ return generator;+};++var pLimit_1 = pLimit;++var importFrom = (fromDirectory, moduleId) => commonjsRequire(resolveFrom_1(fromDirectory, moduleId));++var silent$1 = (fromDirectory, moduleId) => {+ try {+ return commonjsRequire(resolveFrom_1(fromDirectory, moduleId));+ } catch (_) {}+};+importFrom.silent = silent$1;++var isWin = process.platform === 'win32';++var removeTrailingSeparator = function (str) {+ var i = str.length - 1;+ if (i < 2) {+ return str;+ }+ while (isSeparator(str, i)) {+ i--;+ }+ return str.substr(0, i + 1);+};++function isSeparator(str, i) {+ var char = str[i];+ return i > 0 && (char === '/' || (isWin && char === '\\'));+}++/*!+ * normalize-path <https://github.com/jonschlinkert/normalize-path>+ *+ * Copyright (c) 2014-2017, Jon Schlinkert.+ * Released under the MIT License.+ */++++var normalizePath = function normalizePath(str, stripTrailing) {+ if (typeof str !== 'string') {+ throw new TypeError('expected a string');+ }+ str = str.replace(/[\\\/]+/g, '/');+ if (stripTrailing !== false) {+ str = removeTrailingSeparator(str);+ }+ return str;+};++var unixify = function unixify(filepath, stripTrailing) {+ filepath = normalizePath(filepath, stripTrailing);+ return filepath.replace(/^([a-zA-Z]+:|\.\/)/, '');+};++var arrayUnion = (...arguments_) => {+ return [...new Set([].concat(...arguments_))];+};++/*+ * merge2+ * https://github.com/teambition/merge2+ *+ * Copyright (c) 2014-2020 Teambition+ * Licensed under the MIT license.+ */++const PassThrough = Stream__default['default'].PassThrough;+const slice = Array.prototype.slice;++var merge2_1 = merge2;++function merge2 () {+ const streamsQueue = [];+ const args = slice.call(arguments);+ let merging = false;+ let options = args[args.length - 1];++ if (options && !Array.isArray(options) && options.pipe == null) {+ args.pop();+ } else {+ options = {};+ }++ const doEnd = options.end !== false;+ const doPipeError = options.pipeError === true;+ if (options.objectMode == null) {+ options.objectMode = true;+ }+ if (options.highWaterMark == null) {+ options.highWaterMark = 64 * 1024;+ }+ const mergedStream = PassThrough(options);++ function addStream () {+ for (let i = 0, len = arguments.length; i < len; i++) {+ streamsQueue.push(pauseStreams(arguments[i], options));+ }+ mergeStream();+ return this+ }++ function mergeStream () {+ if (merging) {+ return+ }+ merging = true;++ let streams = streamsQueue.shift();+ if (!streams) {+ process.nextTick(endStream);+ return+ }+ if (!Array.isArray(streams)) {+ streams = [streams];+ }++ let pipesCount = streams.length + 1;++ function next () {+ if (--pipesCount > 0) {+ return+ }+ merging = false;+ mergeStream();+ }++ function pipe (stream) {+ function onend () {+ stream.removeListener('merge2UnpipeEnd', onend);+ stream.removeListener('end', onend);+ if (doPipeError) {+ stream.removeListener('error', onerror);+ }+ next();+ }+ function onerror (err) {+ mergedStream.emit('error', err);+ }+ // skip ended stream+ if (stream._readableState.endEmitted) {+ return next()+ }++ stream.on('merge2UnpipeEnd', onend);+ stream.on('end', onend);++ if (doPipeError) {+ stream.on('error', onerror);+ }++ stream.pipe(mergedStream, { end: false });+ // compatible for old stream+ stream.resume();+ }++ for (let i = 0; i < streams.length; i++) {+ pipe(streams[i]);+ }++ next();+ }++ function endStream () {+ merging = false;+ // emit 'queueDrain' when all streams merged.+ mergedStream.emit('queueDrain');+ if (doEnd) {+ mergedStream.end();+ }+ }++ mergedStream.setMaxListeners(0);+ mergedStream.add = addStream;+ mergedStream.on('unpipe', function (stream) {+ stream.emit('merge2UnpipeEnd');+ });++ if (args.length) {+ addStream.apply(null, args);+ }+ return mergedStream+}++// check and pause streams for pipe.+function pauseStreams (streams, options) {+ if (!Array.isArray(streams)) {+ // Backwards-compat with old-style streams+ if (!streams._readableState && streams.pipe) {+ streams = streams.pipe(PassThrough(options));+ }+ if (!streams._readableState || !streams.pause || !streams.pipe) {+ throw new Error('Only readable stream can be merged.')+ }+ streams.pause();+ } else {+ for (let i = 0, len = streams.length; i < len; i++) {+ streams[i] = pauseStreams(streams[i], options);+ }+ }+ return streams+}++var array = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.splitWhen = exports.flatten = void 0; +function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +exports.flatten = flatten; +function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } + else { + result[groupIndex].push(item); + } + } + return result; +} +exports.splitWhen = splitWhen;+});++var errno = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; +} +exports.isEnoentCodeError = isEnoentCodeError;+});++var fs = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats;+});++var path_1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0; + +const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ +const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +function unixify(filepath) { + return filepath.replace(/\\/g, '/'); +} +exports.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path__default['default'].resolve(cwd, filepath); +} +exports.makeAbsolute = makeAbsolute; +function escape(pattern) { + return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escape = escape; +function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + return entry; +} +exports.removeLeadingDotSegment = removeLeadingDotSegment;+});++var pathPosixDirname = path__default['default'].posix.dirname;+var isWin32 = require$$1__default['default'].platform() === 'win32';++var slash = '/';+var backslash = /\\/g;+var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;+var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;+var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;++/**+ * @param {string} str+ * @param {Object} opts+ * @param {boolean} [opts.flipBackslashes=true]+ */+var globParent = function globParent(str, opts) {+ var options = Object.assign({ flipBackslashes: true }, opts);++ // flip windows path separators+ if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {+ str = str.replace(backslash, slash);+ }++ // special case for strings ending in enclosure containing path separator+ if (enclosure.test(str)) {+ str += slash;+ }++ // preserves full path in case of trailing path separator+ str += 'a';++ // remove path parts that are globby+ do {+ str = pathPosixDirname(str);+ } while (isGlob(str) || globby.test(str));++ // remove escape chars and return result+ return str.replace(escaped, '$1');+};++var utils$1 = createCommonjsModule(function (module, exports) {++exports.isInteger = num => {+ if (typeof num === 'number') {+ return Number.isInteger(num);+ }+ if (typeof num === 'string' && num.trim() !== '') {+ return Number.isInteger(Number(num));+ }+ return false;+};++/**+ * Find a node of the given type+ */++exports.find = (node, type) => node.nodes.find(node => node.type === type);++/**+ * Find a node of the given type+ */++exports.exceedsLimit = (min, max, step = 1, limit) => {+ if (limit === false) return false;+ if (!exports.isInteger(min) || !exports.isInteger(max)) return false;+ return ((Number(max) - Number(min)) / Number(step)) >= limit;+};++/**+ * Escape the given node with '\\' before node.value+ */++exports.escapeNode = (block, n = 0, type) => {+ let node = block.nodes[n];+ if (!node) return;++ if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {+ if (node.escaped !== true) {+ node.value = '\\' + node.value;+ node.escaped = true;+ }+ }+};++/**+ * Returns true if the given brace node should be enclosed in literal braces+ */++exports.encloseBrace = node => {+ if (node.type !== 'brace') return false;+ if ((node.commas >> 0 + node.ranges >> 0) === 0) {+ node.invalid = true;+ return true;+ }+ return false;+};++/**+ * Returns true if a brace node is invalid.+ */++exports.isInvalidBrace = block => {+ if (block.type !== 'brace') return false;+ if (block.invalid === true || block.dollar) return true;+ if ((block.commas >> 0 + block.ranges >> 0) === 0) {+ block.invalid = true;+ return true;+ }+ if (block.open !== true || block.close !== true) {+ block.invalid = true;+ return true;+ }+ return false;+};++/**+ * Returns true if a node is an open or close node+ */++exports.isOpenOrClose = node => {+ if (node.type === 'open' || node.type === 'close') {+ return true;+ }+ return node.open === true || node.close === true;+};++/**+ * Reduce an array of text nodes.+ */++exports.reduce = nodes => nodes.reduce((acc, node) => {+ if (node.type === 'text') acc.push(node.value);+ if (node.type === 'range') node.type = 'text';+ return acc;+}, []);++/**+ * Flatten an array+ */++exports.flatten = (...args) => {+ const result = [];+ const flat = arr => {+ for (let i = 0; i < arr.length; i++) {+ let ele = arr[i];+ Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);+ }+ return result;+ };+ flat(args);+ return result;+};+});++var stringify$4 = (ast, options = {}) => {+ let stringify = (node, parent = {}) => {+ let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent);+ let invalidNode = node.invalid === true && options.escapeInvalid === true;+ let output = '';++ if (node.value) {+ if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) {+ return '\\' + node.value;+ }+ return node.value;+ }++ if (node.value) {+ return node.value;+ }++ if (node.nodes) {+ for (let child of node.nodes) {+ output += stringify(child);+ }+ }+ return output;+ };++ return stringify(ast);+};++/*!+ * is-number <https://github.com/jonschlinkert/is-number>+ *+ * Copyright (c) 2014-present, Jon Schlinkert.+ * Released under the MIT License.+ */++var isNumber = function(num) {+ if (typeof num === 'number') {+ return num - num === 0;+ }+ if (typeof num === 'string' && num.trim() !== '') {+ return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);+ }+ return false;+};++const toRegexRange = (min, max, options) => {+ if (isNumber(min) === false) {+ throw new TypeError('toRegexRange: expected the first argument to be a number');+ }++ if (max === void 0 || min === max) {+ return String(min);+ }++ if (isNumber(max) === false) {+ throw new TypeError('toRegexRange: expected the second argument to be a number.');+ }++ let opts = { relaxZeros: true, ...options };+ if (typeof opts.strictZeros === 'boolean') {+ opts.relaxZeros = opts.strictZeros === false;+ }++ let relax = String(opts.relaxZeros);+ let shorthand = String(opts.shorthand);+ let capture = String(opts.capture);+ let wrap = String(opts.wrap);+ let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;++ if (toRegexRange.cache.hasOwnProperty(cacheKey)) {+ return toRegexRange.cache[cacheKey].result;+ }++ let a = Math.min(min, max);+ let b = Math.max(min, max);++ if (Math.abs(a - b) === 1) {+ let result = min + '|' + max;+ if (opts.capture) {+ return `(${result})`;+ }+ if (opts.wrap === false) {+ return result;+ }+ return `(?:${result})`;+ }++ let isPadded = hasPadding(min) || hasPadding(max);+ let state = { min, max, a, b };+ let positives = [];+ let negatives = [];++ if (isPadded) {+ state.isPadded = isPadded;+ state.maxLen = String(state.max).length;+ }++ if (a < 0) {+ let newMin = b < 0 ? Math.abs(b) : 1;+ negatives = splitToPatterns(newMin, Math.abs(a), state, opts);+ a = state.a = 0;+ }++ if (b >= 0) {+ positives = splitToPatterns(a, b, state, opts);+ }++ state.negatives = negatives;+ state.positives = positives;+ state.result = collatePatterns(negatives, positives);++ if (opts.capture === true) {+ state.result = `(${state.result})`;+ } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {+ state.result = `(?:${state.result})`;+ }++ toRegexRange.cache[cacheKey] = state;+ return state.result;+};++function collatePatterns(neg, pos, options) {+ let onlyNegative = filterPatterns(neg, pos, '-', false) || [];+ let onlyPositive = filterPatterns(pos, neg, '', false) || [];+ let intersected = filterPatterns(neg, pos, '-?', true) || [];+ let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);+ return subpatterns.join('|');+}++function splitToRanges(min, max) {+ let nines = 1;+ let zeros = 1;++ let stop = countNines(min, nines);+ let stops = new Set([max]);++ while (min <= stop && stop <= max) {+ stops.add(stop);+ nines += 1;+ stop = countNines(min, nines);+ }++ stop = countZeros(max + 1, zeros) - 1;++ while (min < stop && stop <= max) {+ stops.add(stop);+ zeros += 1;+ stop = countZeros(max + 1, zeros) - 1;+ }++ stops = [...stops];+ stops.sort(compare);+ return stops;+}++/**+ * Convert a range to a regex pattern+ * @param {Number} `start`+ * @param {Number} `stop`+ * @return {String}+ */++function rangeToPattern(start, stop, options) {+ if (start === stop) {+ return { pattern: start, count: [], digits: 0 };+ }++ let zipped = zip(start, stop);+ let digits = zipped.length;+ let pattern = '';+ let count = 0;++ for (let i = 0; i < digits; i++) {+ let [startDigit, stopDigit] = zipped[i];++ if (startDigit === stopDigit) {+ pattern += startDigit;++ } else if (startDigit !== '0' || stopDigit !== '9') {+ pattern += toCharacterClass(startDigit, stopDigit);++ } else {+ count++;+ }+ }++ if (count) {+ pattern += options.shorthand === true ? '\\d' : '[0-9]';+ }++ return { pattern, count: [count], digits };+}++function splitToPatterns(min, max, tok, options) {+ let ranges = splitToRanges(min, max);+ let tokens = [];+ let start = min;+ let prev;++ for (let i = 0; i < ranges.length; i++) {+ let max = ranges[i];+ let obj = rangeToPattern(String(start), String(max), options);+ let zeros = '';++ if (!tok.isPadded && prev && prev.pattern === obj.pattern) {+ if (prev.count.length > 1) {+ prev.count.pop();+ }++ prev.count.push(obj.count[0]);+ prev.string = prev.pattern + toQuantifier(prev.count);+ start = max + 1;+ continue;+ }++ if (tok.isPadded) {+ zeros = padZeros(max, tok, options);+ }++ obj.string = zeros + obj.pattern + toQuantifier(obj.count);+ tokens.push(obj);+ start = max + 1;+ prev = obj;+ }++ return tokens;+}++function filterPatterns(arr, comparison, prefix, intersection, options) {+ let result = [];++ for (let ele of arr) {+ let { string } = ele;++ // only push if _both_ are negative...+ if (!intersection && !contains(comparison, 'string', string)) {+ result.push(prefix + string);+ }++ // or _both_ are positive+ if (intersection && contains(comparison, 'string', string)) {+ result.push(prefix + string);+ }+ }+ return result;+}++/**+ * Zip strings+ */++function zip(a, b) {+ let arr = [];+ for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);+ return arr;+}++function compare(a, b) {+ return a > b ? 1 : b > a ? -1 : 0;+}++function contains(arr, key, val) {+ return arr.some(ele => ele[key] === val);+}++function countNines(min, len) {+ return Number(String(min).slice(0, -len) + '9'.repeat(len));+}++function countZeros(integer, zeros) {+ return integer - (integer % Math.pow(10, zeros));+}++function toQuantifier(digits) {+ let [start = 0, stop = ''] = digits;+ if (stop || start > 1) {+ return `{${start + (stop ? ',' + stop : '')}}`;+ }+ return '';+}++function toCharacterClass(a, b, options) {+ return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;+}++function hasPadding(str) {+ return /^-?(0+)\d/.test(str);+}++function padZeros(value, tok, options) {+ if (!tok.isPadded) {+ return value;+ }++ let diff = Math.abs(tok.maxLen - String(value).length);+ let relax = options.relaxZeros !== false;++ switch (diff) {+ case 0:+ return '';+ case 1:+ return relax ? '0?' : '0';+ case 2:+ return relax ? '0{0,2}' : '00';+ default: {+ return relax ? `0{0,${diff}}` : `0{${diff}}`;+ }+ }+}++/**+ * Cache+ */++toRegexRange.cache = {};+toRegexRange.clearCache = () => (toRegexRange.cache = {});++/**+ * Expose `toRegexRange`+ */++var toRegexRange_1 = toRegexRange;++const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);++const transform = toNumber => {+ return value => toNumber === true ? Number(value) : String(value);+};++const isValidValue = value => {+ return typeof value === 'number' || (typeof value === 'string' && value !== '');+};++const isNumber$1 = num => Number.isInteger(+num);++const zeros = input => {+ let value = `${input}`;+ let index = -1;+ if (value[0] === '-') value = value.slice(1);+ if (value === '0') return false;+ while (value[++index] === '0');+ return index > 0;+};++const stringify$5 = (start, end, options) => {+ if (typeof start === 'string' || typeof end === 'string') {+ return true;+ }+ return options.stringify === true;+};++const pad = (input, maxLength, toNumber) => {+ if (maxLength > 0) {+ let dash = input[0] === '-' ? '-' : '';+ if (dash) input = input.slice(1);+ input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));+ }+ if (toNumber === false) {+ return String(input);+ }+ return input;+};++const toMaxLen = (input, maxLength) => {+ let negative = input[0] === '-' ? '-' : '';+ if (negative) {+ input = input.slice(1);+ maxLength--;+ }+ while (input.length < maxLength) input = '0' + input;+ return negative ? ('-' + input) : input;+};++const toSequence = (parts, options) => {+ parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);+ parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);++ let prefix = options.capture ? '' : '?:';+ let positives = '';+ let negatives = '';+ let result;++ if (parts.positives.length) {+ positives = parts.positives.join('|');+ }++ if (parts.negatives.length) {+ negatives = `-(${prefix}${parts.negatives.join('|')})`;+ }++ if (positives && negatives) {+ result = `${positives}|${negatives}`;+ } else {+ result = positives || negatives;+ }++ if (options.wrap) {+ return `(${prefix}${result})`;+ }++ return result;+};++const toRange = (a, b, isNumbers, options) => {+ if (isNumbers) {+ return toRegexRange_1(a, b, { wrap: false, ...options });+ }++ let start = String.fromCharCode(a);+ if (a === b) return start;++ let stop = String.fromCharCode(b);+ return `[${start}-${stop}]`;+};++const toRegex = (start, end, options) => {+ if (Array.isArray(start)) {+ let wrap = options.wrap === true;+ let prefix = options.capture ? '' : '?:';+ return wrap ? `(${prefix}${start.join('|')})` : start.join('|');+ }+ return toRegexRange_1(start, end, options);+};++const rangeError = (...args) => {+ return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args));+};++const invalidRange = (start, end, options) => {+ if (options.strictRanges === true) throw rangeError([start, end]);+ return [];+};++const invalidStep = (step, options) => {+ if (options.strictRanges === true) {+ throw new TypeError(`Expected step "${step}" to be a number`);+ }+ return [];+};++const fillNumbers = (start, end, step = 1, options = {}) => {+ let a = Number(start);+ let b = Number(end);++ if (!Number.isInteger(a) || !Number.isInteger(b)) {+ if (options.strictRanges === true) throw rangeError([start, end]);+ return [];+ }++ // fix negative zero+ if (a === 0) a = 0;+ if (b === 0) b = 0;++ let descending = a > b;+ let startString = String(start);+ let endString = String(end);+ let stepString = String(step);+ step = Math.max(Math.abs(step), 1);++ let padded = zeros(startString) || zeros(endString) || zeros(stepString);+ let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;+ let toNumber = padded === false && stringify$5(start, end, options) === false;+ let format = options.transform || transform(toNumber);++ if (options.toRegex && step === 1) {+ return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);+ }++ let parts = { negatives: [], positives: [] };+ let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));+ let range = [];+ let index = 0;++ while (descending ? a >= b : a <= b) {+ if (options.toRegex === true && step > 1) {+ push(a);+ } else {+ range.push(pad(format(a, index), maxLen, toNumber));+ }+ a = descending ? a - step : a + step;+ index++;+ }++ if (options.toRegex === true) {+ return step > 1+ ? toSequence(parts, options)+ : toRegex(range, null, { wrap: false, ...options });+ }++ return range;+};++const fillLetters = (start, end, step = 1, options = {}) => {+ if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {+ return invalidRange(start, end, options);+ }+++ let format = options.transform || (val => String.fromCharCode(val));+ let a = `${start}`.charCodeAt(0);+ let b = `${end}`.charCodeAt(0);++ let descending = a > b;+ let min = Math.min(a, b);+ let max = Math.max(a, b);++ if (options.toRegex && step === 1) {+ return toRange(min, max, false, options);+ }++ let range = [];+ let index = 0;++ while (descending ? a >= b : a <= b) {+ range.push(format(a, index));+ a = descending ? a - step : a + step;+ index++;+ }++ if (options.toRegex === true) {+ return toRegex(range, null, { wrap: false, options });+ }++ return range;+};++const fill = (start, end, step, options = {}) => {+ if (end == null && isValidValue(start)) {+ return [start];+ }++ if (!isValidValue(start) || !isValidValue(end)) {+ return invalidRange(start, end, options);+ }++ if (typeof step === 'function') {+ return fill(start, end, 1, { transform: step });+ }++ if (isObject$1(step)) {+ return fill(start, end, 0, step);+ }++ let opts = { ...options };+ if (opts.capture === true) opts.wrap = true;+ step = step || opts.step || 1;++ if (!isNumber$1(step)) {+ if (step != null && !isObject$1(step)) return invalidStep(step, opts);+ return fill(start, end, 1, step);+ }++ if (isNumber$1(start) && isNumber$1(end)) {+ return fillNumbers(start, end, step, opts);+ }++ return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);+};++var fillRange = fill;++const compile = (ast, options = {}) => {+ let walk = (node, parent = {}) => {+ let invalidBlock = utils$1.isInvalidBrace(parent);+ let invalidNode = node.invalid === true && options.escapeInvalid === true;+ let invalid = invalidBlock === true || invalidNode === true;+ let prefix = options.escapeInvalid === true ? '\\' : '';+ let output = '';++ if (node.isOpen === true) {+ return prefix + node.value;+ }+ if (node.isClose === true) {+ return prefix + node.value;+ }++ if (node.type === 'open') {+ return invalid ? (prefix + node.value) : '(';+ }++ if (node.type === 'close') {+ return invalid ? (prefix + node.value) : ')';+ }++ if (node.type === 'comma') {+ return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');+ }++ if (node.value) {+ return node.value;+ }++ if (node.nodes && node.ranges > 0) {+ let args = utils$1.reduce(node.nodes);+ let range = fillRange(...args, { ...options, wrap: false, toRegex: true });++ if (range.length !== 0) {+ return args.length > 1 && range.length > 1 ? `(${range})` : range;+ }+ }++ if (node.nodes) {+ for (let child of node.nodes) {+ output += walk(child, node);+ }+ }+ return output;+ };++ return walk(ast);+};++var compile_1 = compile;++const append = (queue = '', stash = '', enclose = false) => {+ let result = [];++ queue = [].concat(queue);+ stash = [].concat(stash);++ if (!stash.length) return queue;+ if (!queue.length) {+ return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash;+ }++ for (let item of queue) {+ if (Array.isArray(item)) {+ for (let value of item) {+ result.push(append(value, stash, enclose));+ }+ } else {+ for (let ele of stash) {+ if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;+ result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));+ }+ }+ }+ return utils$1.flatten(result);+};++const expand = (ast, options = {}) => {+ let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;++ let walk = (node, parent = {}) => {+ node.queue = [];++ let p = parent;+ let q = parent.queue;++ while (p.type !== 'brace' && p.type !== 'root' && p.parent) {+ p = p.parent;+ q = p.queue;+ }++ if (node.invalid || node.dollar) {+ q.push(append(q.pop(), stringify$4(node, options)));+ return;+ }++ if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {+ q.push(append(q.pop(), ['{}']));+ return;+ }++ if (node.nodes && node.ranges > 0) {+ let args = utils$1.reduce(node.nodes);++ if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) {+ throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');+ }++ let range = fillRange(...args, options);+ if (range.length === 0) {+ range = stringify$4(node, options);+ }++ q.push(append(q.pop(), range));+ node.nodes = [];+ return;+ }++ let enclose = utils$1.encloseBrace(node);+ let queue = node.queue;+ let block = node;++ while (block.type !== 'brace' && block.type !== 'root' && block.parent) {+ block = block.parent;+ queue = block.queue;+ }++ for (let i = 0; i < node.nodes.length; i++) {+ let child = node.nodes[i];++ if (child.type === 'comma' && node.type === 'brace') {+ if (i === 1) queue.push('');+ queue.push('');+ continue;+ }++ if (child.type === 'close') {+ q.push(append(q.pop(), queue, enclose));+ continue;+ }++ if (child.value && child.type !== 'open') {+ queue.push(append(queue.pop(), child.value));+ continue;+ }++ if (child.nodes) {+ walk(child, node);+ }+ }++ return queue;+ };++ return utils$1.flatten(walk(ast));+};++var expand_1 = expand;++var constants = {+ MAX_LENGTH: 1024 * 64,++ // Digits+ CHAR_0: '0', /* 0 */+ CHAR_9: '9', /* 9 */++ // Alphabet chars.+ CHAR_UPPERCASE_A: 'A', /* A */+ CHAR_LOWERCASE_A: 'a', /* a */+ CHAR_UPPERCASE_Z: 'Z', /* Z */+ CHAR_LOWERCASE_Z: 'z', /* z */++ CHAR_LEFT_PARENTHESES: '(', /* ( */+ CHAR_RIGHT_PARENTHESES: ')', /* ) */++ CHAR_ASTERISK: '*', /* * */++ // Non-alphabetic chars.+ CHAR_AMPERSAND: '&', /* & */+ CHAR_AT: '@', /* @ */+ CHAR_BACKSLASH: '\\', /* \ */+ CHAR_BACKTICK: '`', /* ` */+ CHAR_CARRIAGE_RETURN: '\r', /* \r */+ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */+ CHAR_COLON: ':', /* : */+ CHAR_COMMA: ',', /* , */+ CHAR_DOLLAR: '$', /* . */+ CHAR_DOT: '.', /* . */+ CHAR_DOUBLE_QUOTE: '"', /* " */+ CHAR_EQUAL: '=', /* = */+ CHAR_EXCLAMATION_MARK: '!', /* ! */+ CHAR_FORM_FEED: '\f', /* \f */+ CHAR_FORWARD_SLASH: '/', /* / */+ CHAR_HASH: '#', /* # */+ CHAR_HYPHEN_MINUS: '-', /* - */+ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */+ CHAR_LEFT_CURLY_BRACE: '{', /* { */+ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */+ CHAR_LINE_FEED: '\n', /* \n */+ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */+ CHAR_PERCENT: '%', /* % */+ CHAR_PLUS: '+', /* + */+ CHAR_QUESTION_MARK: '?', /* ? */+ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */+ CHAR_RIGHT_CURLY_BRACE: '}', /* } */+ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */+ CHAR_SEMICOLON: ';', /* ; */+ CHAR_SINGLE_QUOTE: '\'', /* ' */+ CHAR_SPACE: ' ', /* */+ CHAR_TAB: '\t', /* \t */+ CHAR_UNDERSCORE: '_', /* _ */+ CHAR_VERTICAL_LINE: '|', /* | */+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */+};++/**+ * Constants+ */++const {+ MAX_LENGTH,+ CHAR_BACKSLASH, /* \ */+ CHAR_BACKTICK, /* ` */+ CHAR_COMMA, /* , */+ CHAR_DOT, /* . */+ CHAR_LEFT_PARENTHESES, /* ( */+ CHAR_RIGHT_PARENTHESES, /* ) */+ CHAR_LEFT_CURLY_BRACE, /* { */+ CHAR_RIGHT_CURLY_BRACE, /* } */+ CHAR_LEFT_SQUARE_BRACKET, /* [ */+ CHAR_RIGHT_SQUARE_BRACKET, /* ] */+ CHAR_DOUBLE_QUOTE, /* " */+ CHAR_SINGLE_QUOTE, /* ' */+ CHAR_NO_BREAK_SPACE,+ CHAR_ZERO_WIDTH_NOBREAK_SPACE+} = constants;++/**+ * parse+ */++const parse$1 = (input, options = {}) => {+ if (typeof input !== 'string') {+ throw new TypeError('Expected a string');+ }++ let opts = options || {};+ let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;+ if (input.length > max) {+ throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);+ }++ let ast = { type: 'root', input, nodes: [] };+ let stack = [ast];+ let block = ast;+ let prev = ast;+ let brackets = 0;+ let length = input.length;+ let index = 0;+ let depth = 0;+ let value;++ /**+ * Helpers+ */++ const advance = () => input[index++];+ const push = node => {+ if (node.type === 'text' && prev.type === 'dot') {+ prev.type = 'text';+ }++ if (prev && prev.type === 'text' && node.type === 'text') {+ prev.value += node.value;+ return;+ }++ block.nodes.push(node);+ node.parent = block;+ node.prev = prev;+ prev = node;+ return node;+ };++ push({ type: 'bos' });++ while (index < length) {+ block = stack[stack.length - 1];+ value = advance();++ /**+ * Invalid chars+ */++ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {+ continue;+ }++ /**+ * Escaped chars+ */++ if (value === CHAR_BACKSLASH) {+ push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });+ continue;+ }++ /**+ * Right square bracket (literal): ']'+ */++ if (value === CHAR_RIGHT_SQUARE_BRACKET) {+ push({ type: 'text', value: '\\' + value });+ continue;+ }++ /**+ * Left square bracket: '['+ */++ if (value === CHAR_LEFT_SQUARE_BRACKET) {+ brackets++;+ let next;++ while (index < length && (next = advance())) {+ value += next;++ if (next === CHAR_LEFT_SQUARE_BRACKET) {+ brackets++;+ continue;+ }++ if (next === CHAR_BACKSLASH) {+ value += advance();+ continue;+ }++ if (next === CHAR_RIGHT_SQUARE_BRACKET) {+ brackets--;++ if (brackets === 0) {+ break;+ }+ }+ }++ push({ type: 'text', value });+ continue;+ }++ /**+ * Parentheses+ */++ if (value === CHAR_LEFT_PARENTHESES) {+ block = push({ type: 'paren', nodes: [] });+ stack.push(block);+ push({ type: 'text', value });+ continue;+ }++ if (value === CHAR_RIGHT_PARENTHESES) {+ if (block.type !== 'paren') {+ push({ type: 'text', value });+ continue;+ }+ block = stack.pop();+ push({ type: 'text', value });+ block = stack[stack.length - 1];+ continue;+ }++ /**+ * Quotes: '|"|`+ */++ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {+ let open = value;+ let next;++ if (options.keepQuotes !== true) {+ value = '';+ }++ while (index < length && (next = advance())) {+ if (next === CHAR_BACKSLASH) {+ value += next + advance();+ continue;+ }++ if (next === open) {+ if (options.keepQuotes === true) value += next;+ break;+ }++ value += next;+ }++ push({ type: 'text', value });+ continue;+ }++ /**+ * Left curly brace: '{'+ */++ if (value === CHAR_LEFT_CURLY_BRACE) {+ depth++;++ let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;+ let brace = {+ type: 'brace',+ open: true,+ close: false,+ dollar,+ depth,+ commas: 0,+ ranges: 0,+ nodes: []+ };++ block = push(brace);+ stack.push(block);+ push({ type: 'open', value });+ continue;+ }++ /**+ * Right curly brace: '}'+ */++ if (value === CHAR_RIGHT_CURLY_BRACE) {+ if (block.type !== 'brace') {+ push({ type: 'text', value });+ continue;+ }++ let type = 'close';+ block = stack.pop();+ block.close = true;++ push({ type, value });+ depth--;++ block = stack[stack.length - 1];+ continue;+ }++ /**+ * Comma: ','+ */++ if (value === CHAR_COMMA && depth > 0) {+ if (block.ranges > 0) {+ block.ranges = 0;+ let open = block.nodes.shift();+ block.nodes = [open, { type: 'text', value: stringify$4(block) }];+ }++ push({ type: 'comma', value });+ block.commas++;+ continue;+ }++ /**+ * Dot: '.'+ */++ if (value === CHAR_DOT && depth > 0 && block.commas === 0) {+ let siblings = block.nodes;++ if (depth === 0 || siblings.length === 0) {+ push({ type: 'text', value });+ continue;+ }++ if (prev.type === 'dot') {+ block.range = [];+ prev.value += value;+ prev.type = 'range';++ if (block.nodes.length !== 3 && block.nodes.length !== 5) {+ block.invalid = true;+ block.ranges = 0;+ prev.type = 'text';+ continue;+ }++ block.ranges++;+ block.args = [];+ continue;+ }++ if (prev.type === 'range') {+ siblings.pop();++ let before = siblings[siblings.length - 1];+ before.value += prev.value + value;+ prev = before;+ block.ranges--;+ continue;+ }++ push({ type: 'dot', value });+ continue;+ }++ /**+ * Text+ */++ push({ type: 'text', value });+ }++ // Mark imbalanced braces and brackets as invalid+ do {+ block = stack.pop();++ if (block.type !== 'root') {+ block.nodes.forEach(node => {+ if (!node.nodes) {+ if (node.type === 'open') node.isOpen = true;+ if (node.type === 'close') node.isClose = true;+ if (!node.nodes) node.type = 'text';+ node.invalid = true;+ }+ });++ // get the location of the block on parent.nodes (block's siblings)+ let parent = stack[stack.length - 1];+ let index = parent.nodes.indexOf(block);+ // replace the (invalid) block with it's nodes+ parent.nodes.splice(index, 1, ...block.nodes);+ }+ } while (stack.length > 0);++ push({ type: 'eos' });+ return ast;+};++var parse_1 = parse$1;++/**+ * Expand the given pattern or create a regex-compatible string.+ *+ * ```js+ * const braces = require('braces');+ * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']+ * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']+ * ```+ * @param {String} `str`+ * @param {Object} `options`+ * @return {String}+ * @api public+ */++const braces = (input, options = {}) => {+ let output = [];++ if (Array.isArray(input)) {+ for (let pattern of input) {+ let result = braces.create(pattern, options);+ if (Array.isArray(result)) {+ output.push(...result);+ } else {+ output.push(result);+ }+ }+ } else {+ output = [].concat(braces.create(input, options));+ }++ if (options && options.expand === true && options.nodupes === true) {+ output = [...new Set(output)];+ }+ return output;+};++/**+ * Parse the given `str` with the given `options`.+ *+ * ```js+ * // braces.parse(pattern, [, options]);+ * const ast = braces.parse('a/{b,c}/d');+ * console.log(ast);+ * ```+ * @param {String} pattern Brace pattern to parse+ * @param {Object} options+ * @return {Object} Returns an AST+ * @api public+ */++braces.parse = (input, options = {}) => parse_1(input, options);++/**+ * Creates a braces string from an AST, or an AST node.+ *+ * ```js+ * const braces = require('braces');+ * let ast = braces.parse('foo/{a,b}/bar');+ * console.log(stringify(ast.nodes[2])); //=> '{a,b}'+ * ```+ * @param {String} `input` Brace pattern or AST.+ * @param {Object} `options`+ * @return {Array} Returns an array of expanded values.+ * @api public+ */++braces.stringify = (input, options = {}) => {+ if (typeof input === 'string') {+ return stringify$4(braces.parse(input, options), options);+ }+ return stringify$4(input, options);+};++/**+ * Compiles a brace pattern into a regex-compatible, optimized string.+ * This method is called by the main [braces](#braces) function by default.+ *+ * ```js+ * const braces = require('braces');+ * console.log(braces.compile('a/{b,c}/d'));+ * //=> ['a/(b|c)/d']+ * ```+ * @param {String} `input` Brace pattern or AST.+ * @param {Object} `options`+ * @return {Array} Returns an array of expanded values.+ * @api public+ */++braces.compile = (input, options = {}) => {+ if (typeof input === 'string') {+ input = braces.parse(input, options);+ }+ return compile_1(input, options);+};++/**+ * Expands a brace pattern into an array. This method is called by the+ * main [braces](#braces) function when `options.expand` is true. Before+ * using this method it's recommended that you read the [performance notes](#performance))+ * and advantages of using [.compile](#compile) instead.+ *+ * ```js+ * const braces = require('braces');+ * console.log(braces.expand('a/{b,c}/d'));+ * //=> ['a/b/d', 'a/c/d'];+ * ```+ * @param {String} `pattern` Brace pattern+ * @param {Object} `options`+ * @return {Array} Returns an array of expanded values.+ * @api public+ */++braces.expand = (input, options = {}) => {+ if (typeof input === 'string') {+ input = braces.parse(input, options);+ }++ let result = expand_1(input, options);++ // filter out empty strings if specified+ if (options.noempty === true) {+ result = result.filter(Boolean);+ }++ // filter out duplicates if specified+ if (options.nodupes === true) {+ result = [...new Set(result)];+ }++ return result;+};++/**+ * Processes a brace pattern and returns either an expanded array+ * (if `options.expand` is true), a highly optimized regex-compatible string.+ * This method is called by the main [braces](#braces) function.+ *+ * ```js+ * const braces = require('braces');+ * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))+ * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'+ * ```+ * @param {String} `pattern` Brace pattern+ * @param {Object} `options`+ * @return {Array} Returns an array of expanded values.+ * @api public+ */++braces.create = (input, options = {}) => {+ if (input === '' || input.length < 3) {+ return [input];+ }++ return options.expand !== true+ ? braces.compile(input, options)+ : braces.expand(input, options);+};++/**+ * Expose "braces"+ */++var braces_1 = braces;++const WIN_SLASH = '\\\\/';+const WIN_NO_SLASH = `[^${WIN_SLASH}]`;++/**+ * Posix glob regex+ */++const DOT_LITERAL = '\\.';+const PLUS_LITERAL = '\\+';+const QMARK_LITERAL = '\\?';+const SLASH_LITERAL = '\\/';+const ONE_CHAR = '(?=.)';+const QMARK = '[^/]';+const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;+const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;+const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;+const NO_DOT = `(?!${DOT_LITERAL})`;+const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;+const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;+const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;+const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;+const STAR = `${QMARK}*?`;++const POSIX_CHARS = {+ DOT_LITERAL,+ PLUS_LITERAL,+ QMARK_LITERAL,+ SLASH_LITERAL,+ ONE_CHAR,+ QMARK,+ END_ANCHOR,+ DOTS_SLASH,+ NO_DOT,+ NO_DOTS,+ NO_DOT_SLASH,+ NO_DOTS_SLASH,+ QMARK_NO_DOT,+ STAR,+ START_ANCHOR+};++/**+ * Windows glob regex+ */++const WINDOWS_CHARS = {+ ...POSIX_CHARS,++ SLASH_LITERAL: `[${WIN_SLASH}]`,+ QMARK: WIN_NO_SLASH,+ STAR: `${WIN_NO_SLASH}*?`,+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,+ NO_DOT: `(?!${DOT_LITERAL})`,+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`+};++/**+ * POSIX Bracket Regex+ */++const POSIX_REGEX_SOURCE = {+ alnum: 'a-zA-Z0-9',+ alpha: 'a-zA-Z',+ ascii: '\\x00-\\x7F',+ blank: ' \\t',+ cntrl: '\\x00-\\x1F\\x7F',+ digit: '0-9',+ graph: '\\x21-\\x7E',+ lower: 'a-z',+ print: '\\x20-\\x7E ',+ punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',+ space: ' \\t\\r\\n\\v\\f',+ upper: 'A-Z',+ word: 'A-Za-z0-9_',+ xdigit: 'A-Fa-f0-9'+};++var constants$1 = {+ MAX_LENGTH: 1024 * 64,+ POSIX_REGEX_SOURCE,++ // regular expressions+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,++ // Replace globs with equivalent patterns to reduce parsing time.+ REPLACEMENTS: {+ '***': '*',+ '**/**': '**',+ '**/**/**': '**'+ },++ // Digits+ CHAR_0: 48, /* 0 */+ CHAR_9: 57, /* 9 */++ // Alphabet chars.+ CHAR_UPPERCASE_A: 65, /* A */+ CHAR_LOWERCASE_A: 97, /* a */+ CHAR_UPPERCASE_Z: 90, /* Z */+ CHAR_LOWERCASE_Z: 122, /* z */++ CHAR_LEFT_PARENTHESES: 40, /* ( */+ CHAR_RIGHT_PARENTHESES: 41, /* ) */++ CHAR_ASTERISK: 42, /* * */++ // Non-alphabetic chars.+ CHAR_AMPERSAND: 38, /* & */+ CHAR_AT: 64, /* @ */+ CHAR_BACKWARD_SLASH: 92, /* \ */+ CHAR_CARRIAGE_RETURN: 13, /* \r */+ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */+ CHAR_COLON: 58, /* : */+ CHAR_COMMA: 44, /* , */+ CHAR_DOT: 46, /* . */+ CHAR_DOUBLE_QUOTE: 34, /* " */+ CHAR_EQUAL: 61, /* = */+ CHAR_EXCLAMATION_MARK: 33, /* ! */+ CHAR_FORM_FEED: 12, /* \f */+ CHAR_FORWARD_SLASH: 47, /* / */+ CHAR_GRAVE_ACCENT: 96, /* ` */+ CHAR_HASH: 35, /* # */+ CHAR_HYPHEN_MINUS: 45, /* - */+ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */+ CHAR_LEFT_CURLY_BRACE: 123, /* { */+ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */+ CHAR_LINE_FEED: 10, /* \n */+ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */+ CHAR_PERCENT: 37, /* % */+ CHAR_PLUS: 43, /* + */+ CHAR_QUESTION_MARK: 63, /* ? */+ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */+ CHAR_RIGHT_CURLY_BRACE: 125, /* } */+ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */+ CHAR_SEMICOLON: 59, /* ; */+ CHAR_SINGLE_QUOTE: 39, /* ' */+ CHAR_SPACE: 32, /* */+ CHAR_TAB: 9, /* \t */+ CHAR_UNDERSCORE: 95, /* _ */+ CHAR_VERTICAL_LINE: 124, /* | */+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */++ SEP: path__default['default'].sep,++ /**+ * Create EXTGLOB_CHARS+ */++ extglobChars(chars) {+ return {+ '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },+ '?': { type: 'qmark', open: '(?:', close: ')?' },+ '+': { type: 'plus', open: '(?:', close: ')+' },+ '*': { type: 'star', open: '(?:', close: ')*' },+ '@': { type: 'at', open: '(?:', close: ')' }+ };+ },++ /**+ * Create GLOB_CHARS+ */++ globChars(win32) {+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;+ }+};++var utils$2 = createCommonjsModule(function (module, exports) {+++const win32 = process.platform === 'win32';+const {+ REGEX_BACKSLASH,+ REGEX_REMOVE_BACKSLASH,+ REGEX_SPECIAL_CHARS,+ REGEX_SPECIAL_CHARS_GLOBAL+} = constants$1;++exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);+exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);+exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);+exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');+exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');++exports.removeBackslashes = str => {+ return str.replace(REGEX_REMOVE_BACKSLASH, match => {+ return match === '\\' ? '' : match;+ });+};++exports.supportsLookbehinds = () => {+ const segs = process.version.slice(1).split('.').map(Number);+ if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {+ return true;+ }+ return false;+};++exports.isWindows = options => {+ if (options && typeof options.windows === 'boolean') {+ return options.windows;+ }+ return win32 === true || path__default['default'].sep === '\\';+};++exports.escapeLast = (input, char, lastIdx) => {+ const idx = input.lastIndexOf(char, lastIdx);+ if (idx === -1) return input;+ if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;+};++exports.removePrefix = (input, state = {}) => {+ let output = input;+ if (output.startsWith('./')) {+ output = output.slice(2);+ state.prefix = './';+ }+ return output;+};++exports.wrapOutput = (input, state = {}, options = {}) => {+ const prepend = options.contains ? '' : '^';+ const append = options.contains ? '' : '$';++ let output = `${prepend}(?:${input})${append}`;+ if (state.negated === true) {+ output = `(?:^(?!${output}).*$)`;+ }+ return output;+};+});++const {+ CHAR_ASTERISK, /* * */+ CHAR_AT, /* @ */+ CHAR_BACKWARD_SLASH, /* \ */+ CHAR_COMMA: CHAR_COMMA$1, /* , */+ CHAR_DOT: CHAR_DOT$1, /* . */+ CHAR_EXCLAMATION_MARK, /* ! */+ CHAR_FORWARD_SLASH, /* / */+ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */+ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */+ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */+ CHAR_PLUS, /* + */+ CHAR_QUESTION_MARK, /* ? */+ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */+ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */+ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */+} = constants$1;++const isPathSeparator = code => {+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;+};++const depth = token => {+ if (token.isPrefix !== true) {+ token.depth = token.isGlobstar ? Infinity : 1;+ }+};++/**+ * Quickly scans a glob pattern and returns an object with a handful of+ * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),+ * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).+ *+ * ```js+ * const pm = require('picomatch');+ * console.log(pm.scan('foo/bar/*.js'));+ * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }+ * ```+ * @param {String} `str`+ * @param {Object} `options`+ * @return {Object} Returns an object with tokens and regex source string.+ * @api public+ */++const scan = (input, options) => {+ const opts = options || {};++ const length = input.length - 1;+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;+ const slashes = [];+ const tokens = [];+ const parts = [];++ let str = input;+ let index = -1;+ let start = 0;+ let lastIndex = 0;+ let isBrace = false;+ let isBracket = false;+ let isGlob = false;+ let isExtglob = false;+ let isGlobstar = false;+ let braceEscaped = false;+ let backslashes = false;+ let negated = false;+ let finished = false;+ let braces = 0;+ let prev;+ let code;+ let token = { value: '', depth: 0, isGlob: false };++ const eos = () => index >= length;+ const peek = () => str.charCodeAt(index + 1);+ const advance = () => {+ prev = code;+ return str.charCodeAt(++index);+ };++ while (index < length) {+ code = advance();+ let next;++ if (code === CHAR_BACKWARD_SLASH) {+ backslashes = token.backslashes = true;+ code = advance();++ if (code === CHAR_LEFT_CURLY_BRACE$1) {+ braceEscaped = true;+ }+ continue;+ }++ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {+ braces++;++ while (eos() !== true && (code = advance())) {+ if (code === CHAR_BACKWARD_SLASH) {+ backslashes = token.backslashes = true;+ advance();+ continue;+ }++ if (code === CHAR_LEFT_CURLY_BRACE$1) {+ braces++;+ continue;+ }++ if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {+ isBrace = token.isBrace = true;+ isGlob = token.isGlob = true;+ finished = true;++ if (scanToEnd === true) {+ continue;+ }++ break;+ }++ if (braceEscaped !== true && code === CHAR_COMMA$1) {+ isBrace = token.isBrace = true;+ isGlob = token.isGlob = true;+ finished = true;++ if (scanToEnd === true) {+ continue;+ }++ break;+ }++ if (code === CHAR_RIGHT_CURLY_BRACE$1) {+ braces--;++ if (braces === 0) {+ braceEscaped = false;+ isBrace = token.isBrace = true;+ finished = true;+ break;+ }+ }+ }++ if (scanToEnd === true) {+ continue;+ }++ break;+ }++ if (code === CHAR_FORWARD_SLASH) {+ slashes.push(index);+ tokens.push(token);+ token = { value: '', depth: 0, isGlob: false };++ if (finished === true) continue;+ if (prev === CHAR_DOT$1 && index === (start + 1)) {+ start += 2;+ continue;+ }++ lastIndex = index + 1;+ continue;+ }++ if (opts.noext !== true) {+ const isExtglobChar = code === CHAR_PLUS+ || code === CHAR_AT+ || code === CHAR_ASTERISK+ || code === CHAR_QUESTION_MARK+ || code === CHAR_EXCLAMATION_MARK;++ if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {+ isGlob = token.isGlob = true;+ isExtglob = token.isExtglob = true;+ finished = true;++ if (scanToEnd === true) {+ while (eos() !== true && (code = advance())) {+ if (code === CHAR_BACKWARD_SLASH) {+ backslashes = token.backslashes = true;+ code = advance();+ continue;+ }++ if (code === CHAR_RIGHT_PARENTHESES$1) {+ isGlob = token.isGlob = true;+ finished = true;+ break;+ }+ }+ continue;+ }+ break;+ }+ }++ if (code === CHAR_ASTERISK) {+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;+ isGlob = token.isGlob = true;+ finished = true;++ if (scanToEnd === true) {+ continue;+ }+ break;+ }++ if (code === CHAR_QUESTION_MARK) {+ isGlob = token.isGlob = true;+ finished = true;++ if (scanToEnd === true) {+ continue;+ }+ break;+ }++ if (code === CHAR_LEFT_SQUARE_BRACKET$1) {+ while (eos() !== true && (next = advance())) {+ if (next === CHAR_BACKWARD_SLASH) {+ backslashes = token.backslashes = true;+ advance();+ continue;+ }++ if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {+ isBracket = token.isBracket = true;+ isGlob = token.isGlob = true;+ finished = true;++ if (scanToEnd === true) {+ continue;+ }+ break;+ }+ }+ }++ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {+ negated = token.negated = true;+ start++;+ continue;+ }++ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {+ isGlob = token.isGlob = true;++ if (scanToEnd === true) {+ while (eos() !== true && (code = advance())) {+ if (code === CHAR_LEFT_PARENTHESES$1) {+ backslashes = token.backslashes = true;+ code = advance();+ continue;+ }++ if (code === CHAR_RIGHT_PARENTHESES$1) {+ finished = true;+ break;+ }+ }+ continue;+ }+ break;+ }++ if (isGlob === true) {+ finished = true;++ if (scanToEnd === true) {+ continue;+ }++ break;+ }+ }++ if (opts.noext === true) {+ isExtglob = false;+ isGlob = false;+ }++ let base = str;+ let prefix = '';+ let glob = '';++ if (start > 0) {+ prefix = str.slice(0, start);+ str = str.slice(start);+ lastIndex -= start;+ }++ if (base && isGlob === true && lastIndex > 0) {+ base = str.slice(0, lastIndex);+ glob = str.slice(lastIndex);+ } else if (isGlob === true) {+ base = '';+ glob = str;+ } else {+ base = str;+ }++ if (base && base !== '' && base !== '/' && base !== str) {+ if (isPathSeparator(base.charCodeAt(base.length - 1))) {+ base = base.slice(0, -1);+ }+ }++ if (opts.unescape === true) {+ if (glob) glob = utils$2.removeBackslashes(glob);++ if (base && backslashes === true) {+ base = utils$2.removeBackslashes(base);+ }+ }++ const state = {+ prefix,+ input,+ start,+ base,+ glob,+ isBrace,+ isBracket,+ isGlob,+ isExtglob,+ isGlobstar,+ negated+ };++ if (opts.tokens === true) {+ state.maxDepth = 0;+ if (!isPathSeparator(code)) {+ tokens.push(token);+ }+ state.tokens = tokens;+ }++ if (opts.parts === true || opts.tokens === true) {+ let prevIndex;++ for (let idx = 0; idx < slashes.length; idx++) {+ const n = prevIndex ? prevIndex + 1 : start;+ const i = slashes[idx];+ const value = input.slice(n, i);+ if (opts.tokens) {+ if (idx === 0 && start !== 0) {+ tokens[idx].isPrefix = true;+ tokens[idx].value = prefix;+ } else {+ tokens[idx].value = value;+ }+ depth(tokens[idx]);+ state.maxDepth += tokens[idx].depth;+ }+ if (idx !== 0 || value !== '') {+ parts.push(value);+ }+ prevIndex = i;+ }++ if (prevIndex && prevIndex + 1 < input.length) {+ const value = input.slice(prevIndex + 1);+ parts.push(value);++ if (opts.tokens) {+ tokens[tokens.length - 1].value = value;+ depth(tokens[tokens.length - 1]);+ state.maxDepth += tokens[tokens.length - 1].depth;+ }+ }++ state.slashes = slashes;+ state.parts = parts;+ }++ return state;+};++var scan_1 = scan;++/**+ * Constants+ */++const {+ MAX_LENGTH: MAX_LENGTH$1,+ POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,+ REGEX_NON_SPECIAL_CHARS,+ REGEX_SPECIAL_CHARS_BACKREF,+ REPLACEMENTS+} = constants$1;++/**+ * Helpers+ */++const expandRange = (args, options) => {+ if (typeof options.expandRange === 'function') {+ return options.expandRange(...args, options);+ }++ args.sort();+ const value = `[${args.join('-')}]`;++ try {+ /* eslint-disable-next-line no-new */+ new RegExp(value);+ } catch (ex) {+ return args.map(v => utils$2.escapeRegex(v)).join('..');+ }++ return value;+};++/**+ * Create the message for a syntax error+ */++const syntaxError$1 = (type, char) => {+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;+};++/**+ * Parse the given input string.+ * @param {String} input+ * @param {Object} options+ * @return {Object}+ */++const parse$2 = (input, options) => {+ if (typeof input !== 'string') {+ throw new TypeError('Expected a string');+ }++ input = REPLACEMENTS[input] || input;++ const opts = { ...options };+ const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;++ let len = input.length;+ if (len > max) {+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);+ }++ const bos = { type: 'bos', value: '', output: opts.prepend || '' };+ const tokens = [bos];++ const capture = opts.capture ? '' : '?:';+ const win32 = utils$2.isWindows(options);++ // create constants based on platform, for windows or posix+ const PLATFORM_CHARS = constants$1.globChars(win32);+ const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);++ const {+ DOT_LITERAL,+ PLUS_LITERAL,+ SLASH_LITERAL,+ ONE_CHAR,+ DOTS_SLASH,+ NO_DOT,+ NO_DOT_SLASH,+ NO_DOTS_SLASH,+ QMARK,+ QMARK_NO_DOT,+ STAR,+ START_ANCHOR+ } = PLATFORM_CHARS;++ const globstar = (opts) => {+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;+ };++ const nodot = opts.dot ? '' : NO_DOT;+ const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;+ let star = opts.bash === true ? globstar(opts) : STAR;++ if (opts.capture) {+ star = `(${star})`;+ }++ // minimatch options support+ if (typeof opts.noext === 'boolean') {+ opts.noextglob = opts.noext;+ }++ const state = {+ input,+ index: -1,+ start: 0,+ dot: opts.dot === true,+ consumed: '',+ output: '',+ prefix: '',+ backtrack: false,+ negated: false,+ brackets: 0,+ braces: 0,+ parens: 0,+ quotes: 0,+ globstar: false,+ tokens+ };++ input = utils$2.removePrefix(input, state);+ len = input.length;++ const extglobs = [];+ const braces = [];+ const stack = [];+ let prev = bos;+ let value;++ /**+ * Tokenizing helpers+ */++ const eos = () => state.index === len - 1;+ const peek = state.peek = (n = 1) => input[state.index + n];+ const advance = state.advance = () => input[++state.index];+ const remaining = () => input.slice(state.index + 1);+ const consume = (value = '', num = 0) => {+ state.consumed += value;+ state.index += num;+ };+ const append = token => {+ state.output += token.output != null ? token.output : token.value;+ consume(token.value);+ };++ const negate = () => {+ let count = 1;++ while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {+ advance();+ state.start++;+ count++;+ }++ if (count % 2 === 0) {+ return false;+ }++ state.negated = true;+ state.start++;+ return true;+ };++ const increment = type => {+ state[type]++;+ stack.push(type);+ };++ const decrement = type => {+ state[type]--;+ stack.pop();+ };++ /**+ * Push tokens onto the tokens array. This helper speeds up+ * tokenizing by 1) helping us avoid backtracking as much as possible,+ * and 2) helping us avoid creating extra tokens when consecutive+ * characters are plain text. This improves performance and simplifies+ * lookbehinds.+ */++ const push = tok => {+ if (prev.type === 'globstar') {+ const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');+ const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));++ if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {+ state.output = state.output.slice(0, -prev.output.length);+ prev.type = 'star';+ prev.value = '*';+ prev.output = star;+ state.output += prev.output;+ }+ }++ if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {+ extglobs[extglobs.length - 1].inner += tok.value;+ }++ if (tok.value || tok.output) append(tok);+ if (prev && prev.type === 'text' && tok.type === 'text') {+ prev.value += tok.value;+ prev.output = (prev.output || '') + tok.value;+ return;+ }++ tok.prev = prev;+ tokens.push(tok);+ prev = tok;+ };++ const extglobOpen = (type, value) => {+ const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };++ token.prev = prev;+ token.parens = state.parens;+ token.output = state.output;+ const output = (opts.capture ? '(' : '') + token.open;++ increment('parens');+ push({ type, value, output: state.output ? '' : ONE_CHAR });+ push({ type: 'paren', extglob: true, value: advance(), output });+ extglobs.push(token);+ };++ const extglobClose = token => {+ let output = token.close + (opts.capture ? ')' : '');++ if (token.type === 'negate') {+ let extglobStar = star;++ if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {+ extglobStar = globstar(opts);+ }++ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {+ output = token.close = `)$))${extglobStar}`;+ }++ if (token.prev.type === 'bos' && eos()) {+ state.negatedExtglob = true;+ }+ }++ push({ type: 'paren', extglob: true, value, output });+ decrement('parens');+ };++ /**+ * Fast paths+ */++ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {+ let backslashes = false;++ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {+ if (first === '\\') {+ backslashes = true;+ return m;+ }++ if (first === '?') {+ if (esc) {+ return esc + first + (rest ? QMARK.repeat(rest.length) : '');+ }+ if (index === 0) {+ return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');+ }+ return QMARK.repeat(chars.length);+ }++ if (first === '.') {+ return DOT_LITERAL.repeat(chars.length);+ }++ if (first === '*') {+ if (esc) {+ return esc + first + (rest ? star : '');+ }+ return star;+ }+ return esc ? m : `\\${m}`;+ });++ if (backslashes === true) {+ if (opts.unescape === true) {+ output = output.replace(/\\/g, '');+ } else {+ output = output.replace(/\\+/g, m => {+ return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');+ });+ }+ }++ if (output === input && opts.contains === true) {+ state.output = input;+ return state;+ }++ state.output = utils$2.wrapOutput(output, state, options);+ return state;+ }++ /**+ * Tokenize input until we reach end-of-string+ */++ while (!eos()) {+ value = advance();++ if (value === '\u0000') {+ continue;+ }++ /**+ * Escaped characters+ */++ if (value === '\\') {+ const next = peek();++ if (next === '/' && opts.bash !== true) {+ continue;+ }++ if (next === '.' || next === ';') {+ continue;+ }++ if (!next) {+ value += '\\';+ push({ type: 'text', value });+ continue;+ }++ // collapse slashes to reduce potential for exploits+ const match = /^\\+/.exec(remaining());+ let slashes = 0;++ if (match && match[0].length > 2) {+ slashes = match[0].length;+ state.index += slashes;+ if (slashes % 2 !== 0) {+ value += '\\';+ }+ }++ if (opts.unescape === true) {+ value = advance() || '';+ } else {+ value += advance() || '';+ }++ if (state.brackets === 0) {+ push({ type: 'text', value });+ continue;+ }+ }++ /**+ * If we're inside a regex character class, continue+ * until we reach the closing bracket.+ */++ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {+ if (opts.posix !== false && value === ':') {+ const inner = prev.value.slice(1);+ if (inner.includes('[')) {+ prev.posix = true;++ if (inner.includes(':')) {+ const idx = prev.value.lastIndexOf('[');+ const pre = prev.value.slice(0, idx);+ const rest = prev.value.slice(idx + 2);+ const posix = POSIX_REGEX_SOURCE$1[rest];+ if (posix) {+ prev.value = pre + posix;+ state.backtrack = true;+ advance();++ if (!bos.output && tokens.indexOf(prev) === 1) {+ bos.output = ONE_CHAR;+ }+ continue;+ }+ }+ }+ }++ if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {+ value = `\\${value}`;+ }++ if (value === ']' && (prev.value === '[' || prev.value === '[^')) {+ value = `\\${value}`;+ }++ if (opts.posix === true && value === '!' && prev.value === '[') {+ value = '^';+ }++ prev.value += value;+ append({ value });+ continue;+ }++ /**+ * If we're inside a quoted string, continue+ * until we reach the closing double quote.+ */++ if (state.quotes === 1 && value !== '"') {+ value = utils$2.escapeRegex(value);+ prev.value += value;+ append({ value });+ continue;+ }++ /**+ * Double quotes+ */++ if (value === '"') {+ state.quotes = state.quotes === 1 ? 0 : 1;+ if (opts.keepQuotes === true) {+ push({ type: 'text', value });+ }+ continue;+ }++ /**+ * Parentheses+ */++ if (value === '(') {+ increment('parens');+ push({ type: 'paren', value });+ continue;+ }++ if (value === ')') {+ if (state.parens === 0 && opts.strictBrackets === true) {+ throw new SyntaxError(syntaxError$1('opening', '('));+ }++ const extglob = extglobs[extglobs.length - 1];+ if (extglob && state.parens === extglob.parens + 1) {+ extglobClose(extglobs.pop());+ continue;+ }++ push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });+ decrement('parens');+ continue;+ }++ /**+ * Square brackets+ */++ if (value === '[') {+ if (opts.nobracket === true || !remaining().includes(']')) {+ if (opts.nobracket !== true && opts.strictBrackets === true) {+ throw new SyntaxError(syntaxError$1('closing', ']'));+ }++ value = `\\${value}`;+ } else {+ increment('brackets');+ }++ push({ type: 'bracket', value });+ continue;+ }++ if (value === ']') {+ if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {+ push({ type: 'text', value, output: `\\${value}` });+ continue;+ }++ if (state.brackets === 0) {+ if (opts.strictBrackets === true) {+ throw new SyntaxError(syntaxError$1('opening', '['));+ }++ push({ type: 'text', value, output: `\\${value}` });+ continue;+ }++ decrement('brackets');++ const prevValue = prev.value.slice(1);+ if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {+ value = `/${value}`;+ }++ prev.value += value;+ append({ value });++ // when literal brackets are explicitly disabled+ // assume we should match with a regex character class+ if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {+ continue;+ }++ const escaped = utils$2.escapeRegex(prev.value);+ state.output = state.output.slice(0, -prev.value.length);++ // when literal brackets are explicitly enabled+ // assume we should escape the brackets to match literal characters+ if (opts.literalBrackets === true) {+ state.output += escaped;+ prev.value = escaped;+ continue;+ }++ // when the user specifies nothing, try to match both+ prev.value = `(${capture}${escaped}|${prev.value})`;+ state.output += prev.value;+ continue;+ }++ /**+ * Braces+ */++ if (value === '{' && opts.nobrace !== true) {+ increment('braces');++ const open = {+ type: 'brace',+ value,+ output: '(',+ outputIndex: state.output.length,+ tokensIndex: state.tokens.length+ };++ braces.push(open);+ push(open);+ continue;+ }++ if (value === '}') {+ const brace = braces[braces.length - 1];++ if (opts.nobrace === true || !brace) {+ push({ type: 'text', value, output: value });+ continue;+ }++ let output = ')';++ if (brace.dots === true) {+ const arr = tokens.slice();+ const range = [];++ for (let i = arr.length - 1; i >= 0; i--) {+ tokens.pop();+ if (arr[i].type === 'brace') {+ break;+ }+ if (arr[i].type !== 'dots') {+ range.unshift(arr[i].value);+ }+ }++ output = expandRange(range, opts);+ state.backtrack = true;+ }++ if (brace.comma !== true && brace.dots !== true) {+ const out = state.output.slice(0, brace.outputIndex);+ const toks = state.tokens.slice(brace.tokensIndex);+ brace.value = brace.output = '\\{';+ value = output = '\\}';+ state.output = out;+ for (const t of toks) {+ state.output += (t.output || t.value);+ }+ }++ push({ type: 'brace', value, output });+ decrement('braces');+ braces.pop();+ continue;+ }++ /**+ * Pipes+ */++ if (value === '|') {+ if (extglobs.length > 0) {+ extglobs[extglobs.length - 1].conditions++;+ }+ push({ type: 'text', value });+ continue;+ }++ /**+ * Commas+ */++ if (value === ',') {+ let output = value;++ const brace = braces[braces.length - 1];+ if (brace && stack[stack.length - 1] === 'braces') {+ brace.comma = true;+ output = '|';+ }++ push({ type: 'comma', value, output });+ continue;+ }++ /**+ * Slashes+ */++ if (value === '/') {+ // if the beginning of the glob is "./", advance the start+ // to the current index, and don't add the "./" characters+ // to the state. This greatly simplifies lookbehinds when+ // checking for BOS characters like "!" and "." (not "./")+ if (prev.type === 'dot' && state.index === state.start + 1) {+ state.start = state.index + 1;+ state.consumed = '';+ state.output = '';+ tokens.pop();+ prev = bos; // reset "prev" to the first token+ continue;+ }++ push({ type: 'slash', value, output: SLASH_LITERAL });+ continue;+ }++ /**+ * Dots+ */++ if (value === '.') {+ if (state.braces > 0 && prev.type === 'dot') {+ if (prev.value === '.') prev.output = DOT_LITERAL;+ const brace = braces[braces.length - 1];+ prev.type = 'dots';+ prev.output += value;+ prev.value += value;+ brace.dots = true;+ continue;+ }++ if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {+ push({ type: 'text', value, output: DOT_LITERAL });+ continue;+ }++ push({ type: 'dot', value, output: DOT_LITERAL });+ continue;+ }++ /**+ * Question marks+ */++ if (value === '?') {+ const isGroup = prev && prev.value === '(';+ if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {+ extglobOpen('qmark', value);+ continue;+ }++ if (prev && prev.type === 'paren') {+ const next = peek();+ let output = value;++ if (next === '<' && !utils$2.supportsLookbehinds()) {+ throw new Error('Node.js v10 or higher is required for regex lookbehinds');+ }++ if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {+ output = `\\${value}`;+ }++ push({ type: 'text', value, output });+ continue;+ }++ if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {+ push({ type: 'qmark', value, output: QMARK_NO_DOT });+ continue;+ }++ push({ type: 'qmark', value, output: QMARK });+ continue;+ }++ /**+ * Exclamation+ */++ if (value === '!') {+ if (opts.noextglob !== true && peek() === '(') {+ if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {+ extglobOpen('negate', value);+ continue;+ }+ }++ if (opts.nonegate !== true && state.index === 0) {+ negate();+ continue;+ }+ }++ /**+ * Plus+ */++ if (value === '+') {+ if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {+ extglobOpen('plus', value);+ continue;+ }++ if ((prev && prev.value === '(') || opts.regex === false) {+ push({ type: 'plus', value, output: PLUS_LITERAL });+ continue;+ }++ if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {+ push({ type: 'plus', value });+ continue;+ }++ push({ type: 'plus', value: PLUS_LITERAL });+ continue;+ }++ /**+ * Plain text+ */++ if (value === '@') {+ if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {+ push({ type: 'at', extglob: true, value, output: '' });+ continue;+ }++ push({ type: 'text', value });+ continue;+ }++ /**+ * Plain text+ */++ if (value !== '*') {+ if (value === '$' || value === '^') {+ value = `\\${value}`;+ }++ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());+ if (match) {+ value += match[0];+ state.index += match[0].length;+ }++ push({ type: 'text', value });+ continue;+ }++ /**+ * Stars+ */++ if (prev && (prev.type === 'globstar' || prev.star === true)) {+ prev.type = 'star';+ prev.star = true;+ prev.value += value;+ prev.output = star;+ state.backtrack = true;+ state.globstar = true;+ consume(value);+ continue;+ }++ let rest = remaining();+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {+ extglobOpen('star', value);+ continue;+ }++ if (prev.type === 'star') {+ if (opts.noglobstar === true) {+ consume(value);+ continue;+ }++ const prior = prev.prev;+ const before = prior.prev;+ const isStart = prior.type === 'slash' || prior.type === 'bos';+ const afterStar = before && (before.type === 'star' || before.type === 'globstar');++ if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {+ push({ type: 'star', value, output: '' });+ continue;+ }++ const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');+ const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');+ if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {+ push({ type: 'star', value, output: '' });+ continue;+ }++ // strip consecutive `/**/`+ while (rest.slice(0, 3) === '/**') {+ const after = input[state.index + 4];+ if (after && after !== '/') {+ break;+ }+ rest = rest.slice(3);+ consume('/**', 3);+ }++ if (prior.type === 'bos' && eos()) {+ prev.type = 'globstar';+ prev.value += value;+ prev.output = globstar(opts);+ state.output = prev.output;+ state.globstar = true;+ consume(value);+ continue;+ }++ if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {+ state.output = state.output.slice(0, -(prior.output + prev.output).length);+ prior.output = `(?:${prior.output}`;++ prev.type = 'globstar';+ prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');+ prev.value += value;+ state.globstar = true;+ state.output += prior.output + prev.output;+ consume(value);+ continue;+ }++ if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {+ const end = rest[1] !== void 0 ? '|$' : '';++ state.output = state.output.slice(0, -(prior.output + prev.output).length);+ prior.output = `(?:${prior.output}`;++ prev.type = 'globstar';+ prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;+ prev.value += value;++ state.output += prior.output + prev.output;+ state.globstar = true;++ consume(value + advance());++ push({ type: 'slash', value: '/', output: '' });+ continue;+ }++ if (prior.type === 'bos' && rest[0] === '/') {+ prev.type = 'globstar';+ prev.value += value;+ prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;+ state.output = prev.output;+ state.globstar = true;+ consume(value + advance());+ push({ type: 'slash', value: '/', output: '' });+ continue;+ }++ // remove single star from output+ state.output = state.output.slice(0, -prev.output.length);++ // reset previous token to globstar+ prev.type = 'globstar';+ prev.output = globstar(opts);+ prev.value += value;++ // reset output with globstar+ state.output += prev.output;+ state.globstar = true;+ consume(value);+ continue;+ }++ const token = { type: 'star', value, output: star };++ if (opts.bash === true) {+ token.output = '.*?';+ if (prev.type === 'bos' || prev.type === 'slash') {+ token.output = nodot + token.output;+ }+ push(token);+ continue;+ }++ if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {+ token.output = value;+ push(token);+ continue;+ }++ if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {+ if (prev.type === 'dot') {+ state.output += NO_DOT_SLASH;+ prev.output += NO_DOT_SLASH;++ } else if (opts.dot === true) {+ state.output += NO_DOTS_SLASH;+ prev.output += NO_DOTS_SLASH;++ } else {+ state.output += nodot;+ prev.output += nodot;+ }++ if (peek() !== '*') {+ state.output += ONE_CHAR;+ prev.output += ONE_CHAR;+ }+ }++ push(token);+ }++ while (state.brackets > 0) {+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']'));+ state.output = utils$2.escapeLast(state.output, '[');+ decrement('brackets');+ }++ while (state.parens > 0) {+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')'));+ state.output = utils$2.escapeLast(state.output, '(');+ decrement('parens');+ }++ while (state.braces > 0) {+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}'));+ state.output = utils$2.escapeLast(state.output, '{');+ decrement('braces');+ }++ if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {+ push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });+ }++ // rebuild the output if we had to backtrack at any point+ if (state.backtrack === true) {+ state.output = '';++ for (const token of state.tokens) {+ state.output += token.output != null ? token.output : token.value;++ if (token.suffix) {+ state.output += token.suffix;+ }+ }+ }++ return state;+};++/**+ * Fast paths for creating regular expressions for common glob patterns.+ * This can significantly speed up processing and has very little downside+ * impact when none of the fast paths match.+ */++parse$2.fastpaths = (input, options) => {+ const opts = { ...options };+ const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;+ const len = input.length;+ if (len > max) {+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);+ }++ input = REPLACEMENTS[input] || input;+ const win32 = utils$2.isWindows(options);++ // create constants based on platform, for windows or posix+ const {+ DOT_LITERAL,+ SLASH_LITERAL,+ ONE_CHAR,+ DOTS_SLASH,+ NO_DOT,+ NO_DOTS,+ NO_DOTS_SLASH,+ STAR,+ START_ANCHOR+ } = constants$1.globChars(win32);++ const nodot = opts.dot ? NO_DOTS : NO_DOT;+ const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;+ const capture = opts.capture ? '' : '?:';+ const state = { negated: false, prefix: '' };+ let star = opts.bash === true ? '.*?' : STAR;++ if (opts.capture) {+ star = `(${star})`;+ }++ const globstar = (opts) => {+ if (opts.noglobstar === true) return star;+ return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;+ };++ const create = str => {+ switch (str) {+ case '*':+ return `${nodot}${ONE_CHAR}${star}`;++ case '.*':+ return `${DOT_LITERAL}${ONE_CHAR}${star}`;++ case '*.*':+ return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;++ case '*/*':+ return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;++ case '**':+ return nodot + globstar(opts);++ case '**/*':+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;++ case '**/*.*':+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;++ case '**/.*':+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;++ default: {+ const match = /^(.*?)\.(\w+)$/.exec(str);+ if (!match) return;++ const source = create(match[1]);+ if (!source) return;++ return source + DOT_LITERAL + match[2];+ }+ }+ };++ const output = utils$2.removePrefix(input, state);+ let source = create(output);++ if (source && opts.strictSlashes !== true) {+ source += `${SLASH_LITERAL}?`;+ }++ return source;+};++var parse_1$1 = parse$2;++const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);++/**+ * Creates a matcher function from one or more glob patterns. The+ * returned function takes a string to match as its first argument,+ * and returns true if the string is a match. The returned matcher+ * function also takes a boolean as the second argument that, when true,+ * returns an object with additional information.+ *+ * ```js+ * const picomatch = require('picomatch');+ * // picomatch(glob[, options]);+ *+ * const isMatch = picomatch('*.!(*a)');+ * console.log(isMatch('a.a')); //=> false+ * console.log(isMatch('a.b')); //=> true+ * ```+ * @name picomatch+ * @param {String|Array} `globs` One or more glob patterns.+ * @param {Object=} `options`+ * @return {Function=} Returns a matcher function.+ * @api public+ */++const picomatch = (glob, options, returnState = false) => {+ if (Array.isArray(glob)) {+ const fns = glob.map(input => picomatch(input, options, returnState));+ const arrayMatcher = str => {+ for (const isMatch of fns) {+ const state = isMatch(str);+ if (state) return state;+ }+ return false;+ };+ return arrayMatcher;+ }++ const isState = isObject$2(glob) && glob.tokens && glob.input;++ if (glob === '' || (typeof glob !== 'string' && !isState)) {+ throw new TypeError('Expected pattern to be a non-empty string');+ }++ const opts = options || {};+ const posix = utils$2.isWindows(options);+ const regex = isState+ ? picomatch.compileRe(glob, options)+ : picomatch.makeRe(glob, options, false, true);++ const state = regex.state;+ delete regex.state;++ let isIgnored = () => false;+ if (opts.ignore) {+ const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };+ isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);+ }++ const matcher = (input, returnObject = false) => {+ const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });+ const result = { glob, state, regex, posix, input, output, match, isMatch };++ if (typeof opts.onResult === 'function') {+ opts.onResult(result);+ }++ if (isMatch === false) {+ result.isMatch = false;+ return returnObject ? result : false;+ }++ if (isIgnored(input)) {+ if (typeof opts.onIgnore === 'function') {+ opts.onIgnore(result);+ }+ result.isMatch = false;+ return returnObject ? result : false;+ }++ if (typeof opts.onMatch === 'function') {+ opts.onMatch(result);+ }+ return returnObject ? result : true;+ };++ if (returnState) {+ matcher.state = state;+ }++ return matcher;+};++/**+ * Test `input` with the given `regex`. This is used by the main+ * `picomatch()` function to test the input string.+ *+ * ```js+ * const picomatch = require('picomatch');+ * // picomatch.test(input, regex[, options]);+ *+ * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));+ * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }+ * ```+ * @param {String} `input` String to test.+ * @param {RegExp} `regex`+ * @return {Object} Returns an object with matching info.+ * @api public+ */++picomatch.test = (input, regex, options, { glob, posix } = {}) => {+ if (typeof input !== 'string') {+ throw new TypeError('Expected input to be a string');+ }++ if (input === '') {+ return { isMatch: false, output: '' };+ }++ const opts = options || {};+ const format = opts.format || (posix ? utils$2.toPosixSlashes : null);+ let match = input === glob;+ let output = (match && format) ? format(input) : input;++ if (match === false) {+ output = format ? format(input) : input;+ match = output === glob;+ }++ if (match === false || opts.capture === true) {+ if (opts.matchBase === true || opts.basename === true) {+ match = picomatch.matchBase(input, regex, options, posix);+ } else {+ match = regex.exec(output);+ }+ }++ return { isMatch: Boolean(match), match, output };+};++/**+ * Match the basename of a filepath.+ *+ * ```js+ * const picomatch = require('picomatch');+ * // picomatch.matchBase(input, glob[, options]);+ * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true+ * ```+ * @param {String} `input` String to test.+ * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).+ * @return {Boolean}+ * @api public+ */++picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {+ const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);+ return regex.test(path__default['default'].basename(input));+};++/**+ * Returns true if **any** of the given glob `patterns` match the specified `string`.+ *+ * ```js+ * const picomatch = require('picomatch');+ * // picomatch.isMatch(string, patterns[, options]);+ *+ * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true+ * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false+ * ```+ * @param {String|Array} str The string to test.+ * @param {String|Array} patterns One or more glob patterns to use for matching.+ * @param {Object} [options] See available [options](#options).+ * @return {Boolean} Returns true if any patterns match `str`+ * @api public+ */++picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);++/**+ * Parse a glob pattern to create the source string for a regular+ * expression.+ *+ * ```js+ * const picomatch = require('picomatch');+ * const result = picomatch.parse(pattern[, options]);+ * ```+ * @param {String} `pattern`+ * @param {Object} `options`+ * @return {Object} Returns an object with useful properties and output to be used as a regex source string.+ * @api public+ */++picomatch.parse = (pattern, options) => {+ if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));+ return parse_1$1(pattern, { ...options, fastpaths: false });+};++/**+ * Scan a glob pattern to separate the pattern into segments.+ *+ * ```js+ * const picomatch = require('picomatch');+ * // picomatch.scan(input[, options]);+ *+ * const result = picomatch.scan('!./foo/*.js');+ * console.log(result);+ * { prefix: '!./',+ * input: '!./foo/*.js',+ * start: 3,+ * base: 'foo',+ * glob: '*.js',+ * isBrace: false,+ * isBracket: false,+ * isGlob: true,+ * isExtglob: false,+ * isGlobstar: false,+ * negated: true }+ * ```+ * @param {String} `input` Glob pattern to scan.+ * @param {Object} `options`+ * @return {Object} Returns an object with+ * @api public+ */++picomatch.scan = (input, options) => scan_1(input, options);++/**+ * Create a regular expression from a parsed glob pattern.+ *+ * ```js+ * const picomatch = require('picomatch');+ * const state = picomatch.parse('*.js');+ * // picomatch.compileRe(state[, options]);+ *+ * console.log(picomatch.compileRe(state));+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/+ * ```+ * @param {String} `state` The object returned from the `.parse` method.+ * @param {Object} `options`+ * @return {RegExp} Returns a regex created from the given pattern.+ * @api public+ */++picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {+ if (returnOutput === true) {+ return parsed.output;+ }++ const opts = options || {};+ const prepend = opts.contains ? '' : '^';+ const append = opts.contains ? '' : '$';++ let source = `${prepend}(?:${parsed.output})${append}`;+ if (parsed && parsed.negated === true) {+ source = `^(?!${source}).*$`;+ }++ const regex = picomatch.toRegex(source, options);+ if (returnState === true) {+ regex.state = parsed;+ }++ return regex;+};++picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {+ if (!input || typeof input !== 'string') {+ throw new TypeError('Expected a non-empty string');+ }++ const opts = options || {};+ let parsed = { negated: false, fastpaths: true };+ let prefix = '';+ let output;++ if (input.startsWith('./')) {+ input = input.slice(2);+ prefix = parsed.prefix = './';+ }++ if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {+ output = parse_1$1.fastpaths(input, options);+ }++ if (output === undefined) {+ parsed = parse_1$1(input, options);+ parsed.prefix = prefix + (parsed.prefix || '');+ } else {+ parsed.output = output;+ }++ return picomatch.compileRe(parsed, options, returnOutput, returnState);+};++/**+ * Create a regular expression from the given regex source string.+ *+ * ```js+ * const picomatch = require('picomatch');+ * // picomatch.toRegex(source[, options]);+ *+ * const { output } = picomatch.parse('*.js');+ * console.log(picomatch.toRegex(output));+ * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/+ * ```+ * @param {String} `source` Regular expression source string.+ * @param {Object} `options`+ * @return {RegExp}+ * @api public+ */++picomatch.toRegex = (source, options) => {+ try {+ const opts = options || {};+ return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));+ } catch (err) {+ if (options && options.debug === true) throw err;+ return /$^/;+ }+};++/**+ * Picomatch constants.+ * @return {Object}+ */++picomatch.constants = constants$1;++/**+ * Expose "picomatch"+ */++var picomatch_1 = picomatch;++var picomatch$1 = picomatch_1;++const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');++/**+ * Returns an array of strings that match one or more glob patterns.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm(list, patterns[, options]);+ *+ * console.log(mm(['a.js', 'a.txt'], ['*.js']));+ * //=> [ 'a.js' ]+ * ```+ * @param {String|Array<string>} list List of strings to match.+ * @param {String|Array<string>} patterns One or more glob patterns to use for matching.+ * @param {Object} options See available [options](#options)+ * @return {Array} Returns an array of matches+ * @summary false+ * @api public+ */++const micromatch = (list, patterns, options) => {+ patterns = [].concat(patterns);+ list = [].concat(list);++ let omit = new Set();+ let keep = new Set();+ let items = new Set();+ let negatives = 0;++ let onResult = state => {+ items.add(state.output);+ if (options && options.onResult) {+ options.onResult(state);+ }+ };++ for (let i = 0; i < patterns.length; i++) {+ let isMatch = picomatch$1(String(patterns[i]), { ...options, onResult }, true);+ let negated = isMatch.state.negated || isMatch.state.negatedExtglob;+ if (negated) negatives++;++ for (let item of list) {+ let matched = isMatch(item, true);++ let match = negated ? !matched.isMatch : matched.isMatch;+ if (!match) continue;++ if (negated) {+ omit.add(matched.output);+ } else {+ omit.delete(matched.output);+ keep.add(matched.output);+ }+ }+ }++ let result = negatives === patterns.length ? [...items] : [...keep];+ let matches = result.filter(item => !omit.has(item));++ if (options && matches.length === 0) {+ if (options.failglob === true) {+ throw new Error(`No matches found for "${patterns.join(', ')}"`);+ }++ if (options.nonull === true || options.nullglob === true) {+ return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;+ }+ }++ return matches;+};++/**+ * Backwards compatibility+ */++micromatch.match = micromatch;++/**+ * Returns a matcher function from the given glob `pattern` and `options`.+ * The returned function takes a string to match as its only argument and returns+ * true if the string is a match.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.matcher(pattern[, options]);+ *+ * const isMatch = mm.matcher('*.!(*a)');+ * console.log(isMatch('a.a')); //=> false+ * console.log(isMatch('a.b')); //=> true+ * ```+ * @param {String} `pattern` Glob pattern+ * @param {Object} `options`+ * @return {Function} Returns a matcher function.+ * @api public+ */++micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);++/**+ * Returns true if **any** of the given glob `patterns` match the specified `string`.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.isMatch(string, patterns[, options]);+ *+ * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true+ * console.log(mm.isMatch('a.a', 'b.*')); //=> false+ * ```+ * @param {String} str The string to test.+ * @param {String|Array} patterns One or more glob patterns to use for matching.+ * @param {Object} [options] See available [options](#options).+ * @return {Boolean} Returns true if any patterns match `str`+ * @api public+ */++micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);++/**+ * Backwards compatibility+ */++micromatch.any = micromatch.isMatch;++/**+ * Returns a list of strings that _**do not match any**_ of the given `patterns`.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.not(list, patterns[, options]);+ *+ * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));+ * //=> ['b.b', 'c.c']+ * ```+ * @param {Array} `list` Array of strings to match.+ * @param {String|Array} `patterns` One or more glob pattern to use for matching.+ * @param {Object} `options` See available [options](#options) for changing how matches are performed+ * @return {Array} Returns an array of strings that **do not match** the given patterns.+ * @api public+ */++micromatch.not = (list, patterns, options = {}) => {+ patterns = [].concat(patterns).map(String);+ let result = new Set();+ let items = [];++ let onResult = state => {+ if (options.onResult) options.onResult(state);+ items.push(state.output);+ };++ let matches = micromatch(list, patterns, { ...options, onResult });++ for (let item of items) {+ if (!matches.includes(item)) {+ result.add(item);+ }+ }+ return [...result];+};++/**+ * Returns true if the given `string` contains the given pattern. Similar+ * to [.isMatch](#isMatch) but the pattern can match any part of the string.+ *+ * ```js+ * var mm = require('micromatch');+ * // mm.contains(string, pattern[, options]);+ *+ * console.log(mm.contains('aa/bb/cc', '*b'));+ * //=> true+ * console.log(mm.contains('aa/bb/cc', '*d'));+ * //=> false+ * ```+ * @param {String} `str` The string to match.+ * @param {String|Array} `patterns` Glob pattern to use for matching.+ * @param {Object} `options` See available [options](#options) for changing how matches are performed+ * @return {Boolean} Returns true if the patter matches any part of `str`.+ * @api public+ */++micromatch.contains = (str, pattern, options) => {+ if (typeof str !== 'string') {+ throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);+ }++ if (Array.isArray(pattern)) {+ return pattern.some(p => micromatch.contains(str, p, options));+ }++ if (typeof pattern === 'string') {+ if (isEmptyString(str) || isEmptyString(pattern)) {+ return false;+ }++ if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {+ return true;+ }+ }++ return micromatch.isMatch(str, pattern, { ...options, contains: true });+};++/**+ * Filter the keys of the given object with the given `glob` pattern+ * and `options`. Does not attempt to match nested keys. If you need this feature,+ * use [glob-object][] instead.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.matchKeys(object, patterns[, options]);+ *+ * const obj = { aa: 'a', ab: 'b', ac: 'c' };+ * console.log(mm.matchKeys(obj, '*b'));+ * //=> { ab: 'b' }+ * ```+ * @param {Object} `object` The object with keys to filter.+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.+ * @param {Object} `options` See available [options](#options) for changing how matches are performed+ * @return {Object} Returns an object with only keys that match the given patterns.+ * @api public+ */++micromatch.matchKeys = (obj, patterns, options) => {+ if (!utils$2.isObject(obj)) {+ throw new TypeError('Expected the first argument to be an object');+ }+ let keys = micromatch(Object.keys(obj), patterns, options);+ let res = {};+ for (let key of keys) res[key] = obj[key];+ return res;+};++/**+ * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.some(list, patterns[, options]);+ *+ * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));+ * // true+ * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));+ * // false+ * ```+ * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.+ * @param {Object} `options` See available [options](#options) for changing how matches are performed+ * @return {Boolean} Returns true if any patterns match `str`+ * @api public+ */++micromatch.some = (list, patterns, options) => {+ let items = [].concat(list);++ for (let pattern of [].concat(patterns)) {+ let isMatch = picomatch$1(String(pattern), options);+ if (items.some(item => isMatch(item))) {+ return true;+ }+ }+ return false;+};++/**+ * Returns true if every string in the given `list` matches+ * any of the given glob `patterns`.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.every(list, patterns[, options]);+ *+ * console.log(mm.every('foo.js', ['foo.js']));+ * // true+ * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));+ * // true+ * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));+ * // false+ * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));+ * // false+ * ```+ * @param {String|Array} `list` The string or array of strings to test.+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.+ * @param {Object} `options` See available [options](#options) for changing how matches are performed+ * @return {Boolean} Returns true if any patterns match `str`+ * @api public+ */++micromatch.every = (list, patterns, options) => {+ let items = [].concat(list);++ for (let pattern of [].concat(patterns)) {+ let isMatch = picomatch$1(String(pattern), options);+ if (!items.every(item => isMatch(item))) {+ return false;+ }+ }+ return true;+};++/**+ * Returns true if **all** of the given `patterns` match+ * the specified string.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.all(string, patterns[, options]);+ *+ * console.log(mm.all('foo.js', ['foo.js']));+ * // true+ *+ * console.log(mm.all('foo.js', ['*.js', '!foo.js']));+ * // false+ *+ * console.log(mm.all('foo.js', ['*.js', 'foo.js']));+ * // true+ *+ * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));+ * // true+ * ```+ * @param {String|Array} `str` The string to test.+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.+ * @param {Object} `options` See available [options](#options) for changing how matches are performed+ * @return {Boolean} Returns true if any patterns match `str`+ * @api public+ */++micromatch.all = (str, patterns, options) => {+ if (typeof str !== 'string') {+ throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);+ }++ return [].concat(patterns).every(p => picomatch$1(p, options)(str));+};++/**+ * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.capture(pattern, string[, options]);+ *+ * console.log(mm.capture('test/*.js', 'test/foo.js'));+ * //=> ['foo']+ * console.log(mm.capture('test/*.js', 'foo/bar.css'));+ * //=> null+ * ```+ * @param {String} `glob` Glob pattern to use for matching.+ * @param {String} `input` String to match+ * @param {Object} `options` See available [options](#options) for changing how matches are performed+ * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.+ * @api public+ */++micromatch.capture = (glob, input, options) => {+ let posix = utils$2.isWindows(options);+ let regex = picomatch$1.makeRe(String(glob), { ...options, capture: true });+ let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input);++ if (match) {+ return match.slice(1).map(v => v === void 0 ? '' : v);+ }+};++/**+ * Create a regular expression from the given glob `pattern`.+ *+ * ```js+ * const mm = require('micromatch');+ * // mm.makeRe(pattern[, options]);+ *+ * console.log(mm.makeRe('*.js'));+ * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/+ * ```+ * @param {String} `pattern` A glob pattern to convert to regex.+ * @param {Object} `options`+ * @return {RegExp} Returns a regex created from the given pattern.+ * @api public+ */++micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);++/**+ * Scan a glob pattern to separate the pattern into segments. Used+ * by the [split](#split) method.+ *+ * ```js+ * const mm = require('micromatch');+ * const state = mm.scan(pattern[, options]);+ * ```+ * @param {String} `pattern`+ * @param {Object} `options`+ * @return {Object} Returns an object with+ * @api public+ */++micromatch.scan = (...args) => picomatch$1.scan(...args);++/**+ * Parse a glob pattern to create the source string for a regular+ * expression.+ *+ * ```js+ * const mm = require('micromatch');+ * const state = mm(pattern[, options]);+ * ```+ * @param {String} `glob`+ * @param {Object} `options`+ * @return {Object} Returns an object with useful properties and output to be used as regex source string.+ * @api public+ */++micromatch.parse = (patterns, options) => {+ let res = [];+ for (let pattern of [].concat(patterns || [])) {+ for (let str of braces_1(String(pattern), options)) {+ res.push(picomatch$1.parse(str, options));+ }+ }+ return res;+};++/**+ * Process the given brace `pattern`.+ *+ * ```js+ * const { braces } = require('micromatch');+ * console.log(braces('foo/{a,b,c}/bar'));+ * //=> [ 'foo/(a|b|c)/bar' ]+ *+ * console.log(braces('foo/{a,b,c}/bar', { expand: true }));+ * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]+ * ```+ * @param {String} `pattern` String with brace pattern to process.+ * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.+ * @return {Array}+ * @api public+ */++micromatch.braces = (pattern, options) => {+ if (typeof pattern !== 'string') throw new TypeError('Expected a string');+ if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {+ return [pattern];+ }+ return braces_1(pattern, options);+};++/**+ * Expand braces+ */++micromatch.braceExpand = (pattern, options) => {+ if (typeof pattern !== 'string') throw new TypeError('Expected a string');+ return micromatch.braces(pattern, { ...options, expand: true });+};++/**+ * Expose micromatch+ */++var micromatch_1 = micromatch;++var pattern = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; + + + + +const GLOBSTAR = '**'; +const ESCAPE_SYMBOL = '\\'; +const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; +const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; +const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/; +const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/; +const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +exports.isStaticPattern = isStaticPattern; +function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { + return true; + } + return false; +} +exports.isDynamicPattern = isDynamicPattern; +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +exports.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +exports.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +exports.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +exports.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +exports.getNegativePatterns = getNegativePatterns; +function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); +} +exports.getPositivePatterns = getPositivePatterns; +function getBaseDirectory(pattern) { + return globParent(pattern, { flipBackslashes: false }); +} +exports.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); +} +exports.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); +} +exports.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path__default['default'].basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; +function expandBraceExpansion(pattern) { + return micromatch_1.braces(pattern, { + expand: true, + nodupes: true + }); +} +exports.expandBraceExpansion = expandBraceExpansion; +function getPatternParts(pattern, options) { + let { parts } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + return parts; +} +exports.getPatternParts = getPatternParts; +function makeRe(pattern, options) { + return micromatch_1.makeRe(pattern, options); +} +exports.makeRe = makeRe; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); +} +exports.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +exports.matchAny = matchAny;+});++var stream = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.merge = void 0; + +function merge(streams) { + const mergedStream = merge2_1(streams); + streams.forEach((stream) => { + stream.once('error', (error) => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; +} +exports.merge = merge; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); +}+});++var string = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.isEmpty = exports.isString = void 0; +function isString(input) { + return typeof input === 'string'; +} +exports.isString = isString; +function isEmpty(input) { + return input === ''; +} +exports.isEmpty = isEmpty;+});++var utils$3 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; + +exports.array = array; + +exports.errno = errno; + +exports.fs = fs; + +exports.path = path_1; + +exports.pattern = pattern; + +exports.stream = stream; + +exports.string = string;+});++var tasks = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; + +function generate(patterns, settings) { + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils$3.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils$3.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +exports.generate = generate; +function convertPatternsToTasks(positive, negative, dynamic) { + const positivePatternsGroup = groupPatternsByBaseDirectory(positive); + // When we have a global group – there is no reason to divide the patterns into independent tasks. + // In this case, the global task covers the rest. + if ('.' in positivePatternsGroup) { + const task = convertPatternGroupToTask('.', positive, negative, dynamic); + return [task]; + } + return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic); +} +exports.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils$3.pattern.getPositivePatterns(patterns); +} +exports.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils$3.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils$3.pattern.convertToPositivePattern); + return positive; +} +exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils$3.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils$3.pattern.convertToNegativePattern)) + }; +} +exports.convertPatternGroupToTask = convertPatternGroupToTask;+});++var async = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +function read(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + return callFailureCallback(callback, lstatError); + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return callSuccessCallback(callback, lstat); + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + return callFailureCallback(callback, statError); + } + return callSuccessCallback(callback, lstat); + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback(callback, stat); + }); + }); +} +exports.read = read; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +}+});++var sync = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +exports.read = read;+});++var fs_1$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + stat: fs__default['default'].stat, + lstatSync: fs__default['default'].lstatSync, + statSync: fs__default['default'].statSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter;+});++var settings = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs_1$1.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option === undefined ? value : option; + } +} +exports.default = Settings;+});++var out = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + +exports.Settings = settings.default; +function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return async.read(path, getSettings(), optionsOrSettingsOrCallback); + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.stat = stat; +function statSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.statSync = statSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings.default) { + return settingsOrOptions; + } + return new settings.default(settingsOrOptions); +}+});++var runParallel_1 = runParallel;++function runParallel (tasks, cb) {+ var results, pending, keys;+ var isSync = true;++ if (Array.isArray(tasks)) {+ results = [];+ pending = tasks.length;+ } else {+ keys = Object.keys(tasks);+ results = {};+ pending = keys.length;+ }++ function done (err) {+ function end () {+ if (cb) cb(err, results);+ cb = null;+ }+ if (isSync) process.nextTick(end);+ else end();+ }++ function each (i, err, result) {+ results[i] = result;+ if (--pending === 0 || err) {+ done(err);+ }+ }++ if (!pending) {+ // empty+ done(null);+ } else if (keys) {+ // object+ keys.forEach(function (key) {+ tasks[key](function (err, result) { each(key, err, result); });+ });+ } else {+ // array+ tasks.forEach(function (task, i) {+ task(function (err, result) { each(i, err, result); });+ });+ }++ isSync = false;+}++var constants$2 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); +const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); +const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); +const SUPPORTED_MAJOR_VERSION = 10; +const SUPPORTED_MINOR_VERSION = 10; +const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; +const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; +/** + * IS `true` for Node.js 10.10 and greater. + */ +exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;+});++var fs$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats;+});++var utils$4 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +exports.fs = fs$1;+});++var async$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + + +function read(directory, settings, callback) { + if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings, callback); + } + return readdir(directory, settings, callback); +} +exports.read = read; +function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + return callFailureCallback(callback, readdirError); + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: `${directory}${settings.pathSegmentSeparator}${dirent.name}` + })); + if (!settings.followSymbolicLinks) { + return callSuccessCallback(callback, entries); + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + runParallel_1(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + return callFailureCallback(callback, rplError); + } + callSuccessCallback(callback, rplEntries); + }); + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + return done(null, entry); + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + return done(statError); + } + return done(null, entry); + } + entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats); + return done(null, entry); + }); + }; +} +function readdir(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + return callFailureCallback(callback, readdirError); + } + const filepaths = names.map((name) => `${directory}${settings.pathSegmentSeparator}${name}`); + const tasks = filepaths.map((filepath) => { + return (done) => out.stat(filepath, settings.fsStatSettings, done); + }); + runParallel_1(tasks, (rplError, results) => { + if (rplError !== null) { + return callFailureCallback(callback, rplError); + } + const entries = []; + names.forEach((name, index) => { + const stats = results[index]; + const entry = { + name, + path: filepaths[index], + dirent: utils$4.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + entries.push(entry); + }); + callSuccessCallback(callback, entries); + }); + }); +} +exports.readdir = readdir; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +}+});++var sync$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + +function read(directory, settings) { + if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir(directory, settings); +} +exports.read = read; +function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: `${directory}${settings.pathSegmentSeparator}${dirent.name}` + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function readdir(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`; + const stats = out.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils$4.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +exports.readdir = readdir;+});++var fs_1$2 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + stat: fs__default['default'].stat, + lstatSync: fs__default['default'].lstatSync, + statSync: fs__default['default'].statSync, + readdir: fs__default['default'].readdir, + readdirSync: fs__default['default'].readdirSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter;+});++var settings$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs_1$2.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new out.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option === undefined ? value : option; + } +} +exports.default = Settings;+});++var out$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + +exports.Settings = settings$1.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return async$1.read(path, getSettings(), optionsOrSettingsOrCallback); + } + async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync$1.read(path, settings); +} +exports.scandirSync = scandirSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings$1.default) { + return settingsOrOptions; + } + return new settings$1.default(settingsOrOptions); +}+});++function reusify (Constructor) {+ var head = new Constructor();+ var tail = head;++ function get () {+ var current = head;++ if (current.next) {+ head = current.next;+ } else {+ head = new Constructor();+ tail = head;+ }++ current.next = null;++ return current+ }++ function release (obj) {+ tail.next = obj;+ tail = obj;+ }++ return {+ get: get,+ release: release+ }+}++var reusify_1 = reusify;++function fastqueue (context, worker, concurrency) {+ if (typeof context === 'function') {+ concurrency = worker;+ worker = context;+ context = null;+ }++ var cache = reusify_1(Task);+ var queueHead = null;+ var queueTail = null;+ var _running = 0;++ var self = {+ push: push,+ drain: noop,+ saturated: noop,+ pause: pause,+ paused: false,+ concurrency: concurrency,+ running: running,+ resume: resume,+ idle: idle,+ length: length,+ getQueue: getQueue,+ unshift: unshift,+ empty: noop,+ kill: kill,+ killAndDrain: killAndDrain+ };++ return self++ function running () {+ return _running+ }++ function pause () {+ self.paused = true;+ }++ function length () {+ var current = queueHead;+ var counter = 0;++ while (current) {+ current = current.next;+ counter++;+ }++ return counter+ }++ function getQueue () {+ var current = queueHead;+ var tasks = [];++ while (current) {+ tasks.push(current.value);+ current = current.next;+ }++ return tasks+ }++ function resume () {+ if (!self.paused) return+ self.paused = false;+ for (var i = 0; i < self.concurrency; i++) {+ _running++;+ release();+ }+ }++ function idle () {+ return _running === 0 && self.length() === 0+ }++ function push (value, done) {+ var current = cache.get();++ current.context = context;+ current.release = release;+ current.value = value;+ current.callback = done || noop;++ if (_running === self.concurrency || self.paused) {+ if (queueTail) {+ queueTail.next = current;+ queueTail = current;+ } else {+ queueHead = current;+ queueTail = current;+ self.saturated();+ }+ } else {+ _running++;+ worker.call(context, current.value, current.worked);+ }+ }++ function unshift (value, done) {+ var current = cache.get();++ current.context = context;+ current.release = release;+ current.value = value;+ current.callback = done || noop;++ if (_running === self.concurrency || self.paused) {+ if (queueHead) {+ current.next = queueHead;+ queueHead = current;+ } else {+ queueHead = current;+ queueTail = current;+ self.saturated();+ }+ } else {+ _running++;+ worker.call(context, current.value, current.worked);+ }+ }++ function release (holder) {+ if (holder) {+ cache.release(holder);+ }+ var next = queueHead;+ if (next) {+ if (!self.paused) {+ if (queueTail === queueHead) {+ queueTail = null;+ }+ queueHead = next.next;+ next.next = null;+ worker.call(context, next.value, next.worked);+ if (queueTail === null) {+ self.empty();+ }+ } else {+ _running--;+ }+ } else if (--_running === 0) {+ self.drain();+ }+ }++ function kill () {+ queueHead = null;+ queueTail = null;+ self.drain = noop;+ }++ function killAndDrain () {+ queueHead = null;+ queueTail = null;+ self.drain();+ self.drain = noop;+ }+}++function noop () {}++function Task () {+ this.value = null;+ this.callback = noop;+ this.next = null;+ this.release = noop;+ this.context = null;++ var self = this;++ this.worked = function worked (err, result) {+ var callback = self.callback;+ self.value = null;+ self.callback = noop;+ callback.call(self.context, err, result);+ self.release(self);+ };+}++var queue = fastqueue;++var common = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +exports.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +exports.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[\\/]/).join(separator); +} +exports.replacePathSegmentSeparator = replacePathSegmentSeparator; +function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments;+});++var reader = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +} +exports.default = Reader;+});++var async$2 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + + + +class AsyncReader extends reader.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = out$1.scandir; + this._emitter = new EventEmitter__default['default'].EventEmitter(); + this._queue = queue(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error) => { + if (error !== null) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + return done(error, undefined); + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +exports.default = AsyncReader;+});++var async$3 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async$2.default(this._root, this._settings); + this._storage = new Set(); + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.add(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, [...this._storage]); + }); + this._reader.read(); + } +} +exports.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +}+});++var stream$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async$2.default(this._root, this._settings); + this._stream = new Stream__default['default'].Readable({ + objectMode: true, + read: () => { }, + destroy: this._reader.destroy.bind(this._reader) + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +exports.default = StreamProvider;+});++var sync$2 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + +class SyncReader extends reader.default { + constructor() { + super(...arguments); + this._scandir = out$1.scandirSync; + this._storage = new Set(); + this._queue = new Set(); + } + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return [...this._storage]; + } + _pushToQueue(directory, base) { + this._queue.add({ directory, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } + catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, entry.path); + } + } + _pushToStorage(entry) { + this._storage.add(entry); + } +} +exports.default = SyncReader;+});++var sync$3 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync$2.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } +} +exports.default = SyncProvider;+});++var settings$2 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Infinity); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep); + this.fsScandirSettings = new out$1.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option === undefined ? value : option; + } +} +exports.default = Settings;+});++var out$2 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + + +exports.Settings = settings$2.default; +function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return new async$3.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + } + new async$3.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +exports.walk = walk; +function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync$3.default(directory, settings); + return provider.read(); +} +exports.walkSync = walkSync; +function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream$1.default(directory, settings); + return provider.read(); +} +exports.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings$2.default) { + return settingsOrOptions; + } + return new settings$2.default(settingsOrOptions); +}+});++var reader$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new out.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path__default['default'].resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils$3.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils$3.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +exports.default = Reader;+});++var stream$2 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + + +class ReaderStream extends reader$1.default { + constructor() { + super(...arguments); + this._walkStream = out$2.walkStream; + this._stat = out.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new Stream__default['default'].PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options) + .then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + if (index === filepaths.length - 1) { + stream.end(); + } + done(); + }) + .catch(done); + }; + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath) + .then((stats) => this._makeEntry(stats, pattern)) + .catch((error) => { + if (options.errorFilter(error)) { + return null; + } + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } +} +exports.default = ReaderStream;+});++var matcher = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + /** + * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). + * So, before expand patterns with brace expansion into separated patterns. + */ + const patterns = utils$3.pattern.expandPatternsWithBraceExpansion(this._patterns); + for (const pattern of patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + const parts = utils$3.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils$3.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils$3.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils$3.array.splitWhen(segments, (segment) => segment.dynamic && utils$3.pattern.hasGlobStar(segment.pattern)); + } +} +exports.default = Matcher;+});++var partial = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class PartialMatcher extends matcher.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) { + return true; + } + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match) { + return true; + } + } + return false; + } +} +exports.default = PartialMatcher;+});++var deep = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils$3.pattern.isAffectDepthOfReadingPattern); + return utils$3.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + const filepath = utils$3.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + if (basePath === '') { + return entryPathDepth; + } + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils$3.pattern.matchAny(entryPath, patternsRe); + } +} +exports.default = DeepFilter;+});++var entry = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); + const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions); + return (entry) => this._filter(entry, positiveRe, negativeRe); + } + _filter(entry, positiveRe, negativeRe) { + if (this._settings.unique && this._isDuplicateEntry(entry)) { + return false; + } + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { + return false; + } + const filepath = this._settings.baseNameMatch ? entry.name : entry.path; + const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); + if (this._settings.unique && isMatched) { + this._createIndexRecord(entry); + } + return isMatched; + } + _isDuplicateEntry(entry) { + return this.index.has(entry.path); + } + _createIndexRecord(entry) { + this.index.set(entry.path, undefined); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { + if (!this._settings.absolute) { + return false; + } + const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); + return utils$3.pattern.matchAny(fullpath, patternsRe); + } + _isMatchToPatterns(entryPath, patternsRe) { + const filepath = utils$3.path.removeLeadingDotSegment(entryPath); + return utils$3.pattern.matchAny(filepath, patternsRe); + } +} +exports.default = EntryFilter;+});++var error = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils$3.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } +} +exports.default = ErrorFilter;+});++var entry$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + +class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils$3.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils$3.path.unixify(filepath); + } + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + if (!this._settings.objectMode) { + return filepath; + } + return Object.assign(Object.assign({}, entry), { path: filepath }); + } +} +exports.default = EntryTransformer;+});++var provider = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + + + +class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error.default(this._settings); + this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry$1.default(this._settings); + } + _getRootDirectory(task) { + return path__default['default'].resolve(this._settings.cwd, task.base); + } + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } +} +exports.default = Provider;+});++var async$4 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + +class ProviderAsync extends provider.default { + constructor() { + super(...arguments); + this._reader = new stream$2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = []; + return new Promise((resolve, reject) => { + const stream = this.api(root, task, options); + stream.once('error', reject); + stream.on('data', (entry) => entries.push(options.transform(entry))); + stream.once('end', () => resolve(entries)); + }); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderAsync;+});++var stream$3 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + +class ProviderStream extends provider.default { + constructor() { + super(...arguments); + this._reader = new stream$2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new Stream__default['default'].Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => destination.emit('error', error)) + .on('data', (entry) => destination.emit('data', options.transform(entry))) + .once('end', () => destination.emit('end')); + destination + .once('close', () => source.destroy()); + return destination; + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderStream;+});++var sync$4 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + + +class ReaderSync extends reader$1.default { + constructor() { + super(...arguments); + this._walkSync = out$2.walkSync; + this._statSync = out.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; + } + entries.push(entry); + } + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; + } + } + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } +} +exports.default = ReaderSync;+});++var sync$5 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); + + +class ProviderSync extends provider.default { + constructor() { + super(...arguments); + this._reader = new sync$4.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = this.api(root, task, options); + return entries.map(options.transform); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +exports.default = ProviderSync;+});++var settings$3 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; + + +const CPU_COUNT = require$$1__default['default'].cpus().length; +exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + lstatSync: fs__default['default'].lstatSync, + stat: fs__default['default'].stat, + statSync: fs__default['default'].statSync, + readdir: fs__default['default'].readdir, + readdirSync: fs__default['default'].readdirSync +}; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; + } + if (this.stats) { + this.objectMode = true; + } + } + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } +} +exports.default = Settings;+});++async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async$4.default, options); + const result = await Promise.all(works); + return utils$3.array.flatten(result); +} +// https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare +(function (FastGlob) { + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync$5.default, options); + return utils$3.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream$3.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils$3.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings$3.default(options); + return tasks.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings$3.default(options); + return utils$3.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils$3.path.escape(source); + } + FastGlob.escapePath = escapePath; +})(FastGlob || (FastGlob = {})); +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings$3.default(options); + const tasks$1 = tasks.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks$1.map(provider.read, provider); +} +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils$3.string.isString(item) && !utils$3.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} +var out$3 = FastGlob;++const {promisify} = util__default['default'];+++async function isType$1(fsStatType, statsMethodName, filePath) {+ if (typeof filePath !== 'string') {+ throw new TypeError(`Expected a string, got ${typeof filePath}`);+ }++ try {+ const stats = await promisify(fs__default['default'][fsStatType])(filePath);+ return stats[statsMethodName]();+ } catch (error) {+ if (error.code === 'ENOENT') {+ return false;+ }++ throw error;+ }+}++function isTypeSync(fsStatType, statsMethodName, filePath) {+ if (typeof filePath !== 'string') {+ throw new TypeError(`Expected a string, got ${typeof filePath}`);+ }++ try {+ return fs__default['default'][fsStatType](filePath)[statsMethodName]();+ } catch (error) {+ if (error.code === 'ENOENT') {+ return false;+ }++ throw error;+ }+}++var isFile = isType$1.bind(null, 'stat', 'isFile');+var isDirectory = isType$1.bind(null, 'stat', 'isDirectory');+var isSymlink = isType$1.bind(null, 'lstat', 'isSymbolicLink');+var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');+var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');+var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');++var pathType = {+ isFile: isFile,+ isDirectory: isDirectory,+ isSymlink: isSymlink,+ isFileSync: isFileSync,+ isDirectorySync: isDirectorySync,+ isSymlinkSync: isSymlinkSync+};++const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];++const getPath = (filepath, cwd) => {+ const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;+ return path__default['default'].isAbsolute(pth) ? pth : path__default['default'].join(cwd, pth);+};++const addExtensions = (file, extensions) => {+ if (path__default['default'].extname(file)) {+ return `**/${file}`;+ }++ return `**/${file}.${getExtensions(extensions)}`;+};++const getGlob = (directory, options) => {+ if (options.files && !Array.isArray(options.files)) {+ throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);+ }++ if (options.extensions && !Array.isArray(options.extensions)) {+ throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);+ }++ if (options.files && options.extensions) {+ return options.files.map(x => path__default['default'].posix.join(directory, addExtensions(x, options.extensions)));+ }++ if (options.files) {+ return options.files.map(x => path__default['default'].posix.join(directory, `**/${x}`));+ }++ if (options.extensions) {+ return [path__default['default'].posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];+ }++ return [path__default['default'].posix.join(directory, '**')];+};++var dirGlob = async (input, options) => {+ options = {+ cwd: process.cwd(),+ ...options+ };++ if (typeof options.cwd !== 'string') {+ throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);+ }++ const globs = await Promise.all([].concat(input).map(async x => {+ const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));+ return isDirectory ? getGlob(x, options) : x;+ }));++ return [].concat.apply([], globs); // eslint-disable-line prefer-spread+};++var sync$6 = (input, options) => {+ options = {+ cwd: process.cwd(),+ ...options+ };++ if (typeof options.cwd !== 'string') {+ throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);+ }++ const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);++ return [].concat.apply([], globs); // eslint-disable-line prefer-spread+};+dirGlob.sync = sync$6;++// A simple implementation of make-array+function makeArray (subject) {+ return Array.isArray(subject)+ ? subject+ : [subject]+}++const EMPTY = '';+const SPACE = ' ';+const ESCAPE = '\\';+const REGEX_TEST_BLANK_LINE = /^\s+$/;+const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;+const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;+const REGEX_SPLITALL_CRLF = /\r?\n/g;+// /foo,+// ./foo,+// ../foo,+// .+// ..+const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;++const SLASH = '/';+const KEY_IGNORE = typeof Symbol !== 'undefined'+ ? Symbol.for('node-ignore')+ /* istanbul ignore next */+ : 'node-ignore';++const define = (object, key, value) =>+ Object.defineProperty(object, key, {value});++const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;++// Sanitize the range of a regular expression+// The cases are complicated, see test cases for details+const sanitizeRange = range => range.replace(+ REGEX_REGEXP_RANGE,+ (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)+ ? match+ // Invalid range (out of order) which is ok for gitignore rules but+ // fatal for JavaScript regular expression, so eliminate it.+ : EMPTY+);++// See fixtures #59+const cleanRangeBackSlash = slashes => {+ const {length} = slashes;+ return slashes.slice(0, length - length % 2)+};++// > If the pattern ends with a slash,+// > it is removed for the purpose of the following description,+// > but it would only find a match with a directory.+// > In other words, foo/ will match a directory foo and paths underneath it,+// > but will not match a regular file or a symbolic link foo+// > (this is consistent with the way how pathspec works in general in Git).+// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'+// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call+// you could use option `mark: true` with `glob`++// '`foo/`' should not continue with the '`..`'+const REPLACERS = [++ // > Trailing spaces are ignored unless they are quoted with backslash ("\")+ [+ // (a\ ) -> (a )+ // (a ) -> (a)+ // (a \ ) -> (a )+ /\\?\s+$/,+ match => match.indexOf('\\') === 0+ ? SPACE+ : EMPTY+ ],++ // replace (\ ) with ' '+ [+ /\\\s/g,+ () => SPACE+ ],++ // Escape metacharacters+ // which is written down by users but means special for regular expressions.++ // > There are 12 characters with special meanings:+ // > - the backslash \,+ // > - the caret ^,+ // > - the dollar sign $,+ // > - the period or dot .,+ // > - the vertical bar or pipe symbol |,+ // > - the question mark ?,+ // > - the asterisk or star *,+ // > - the plus sign +,+ // > - the opening parenthesis (,+ // > - the closing parenthesis ),+ // > - and the opening square bracket [,+ // > - the opening curly brace {,+ // > These special characters are often called "metacharacters".+ [+ /[\\$.|*+(){^]/g,+ match => `\\${match}`+ ],++ [+ // > a question mark (?) matches a single character+ /(?!\\)\?/g,+ () => '[^/]'+ ],++ // leading slash+ [++ // > A leading slash matches the beginning of the pathname.+ // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".+ // A leading slash matches the beginning of the pathname+ /^\//,+ () => '^'+ ],++ // replace special metacharacter slash after the leading slash+ [+ /\//g,+ () => '\\/'+ ],++ [+ // > A leading "**" followed by a slash means match in all directories.+ // > For example, "**/foo" matches file or directory "foo" anywhere,+ // > the same as pattern "foo".+ // > "**/foo/bar" matches file or directory "bar" anywhere that is directly+ // > under directory "foo".+ // Notice that the '*'s have been replaced as '\\*'+ /^\^*\\\*\\\*\\\//,++ // '**/foo' <-> 'foo'+ () => '^(?:.*\\/)?'+ ],++ // starting+ [+ // there will be no leading '/'+ // (which has been replaced by section "leading slash")+ // If starts with '**', adding a '^' to the regular expression also works+ /^(?=[^^])/,+ function startingReplacer () {+ // If has a slash `/` at the beginning or middle+ return !/\/(?!$)/.test(this)+ // > Prior to 2.22.1+ // > If the pattern does not contain a slash /,+ // > Git treats it as a shell glob pattern+ // Actually, if there is only a trailing slash,+ // git also treats it as a shell glob pattern++ // After 2.22.1 (compatible but clearer)+ // > If there is a separator at the beginning or middle (or both)+ // > of the pattern, then the pattern is relative to the directory+ // > level of the particular .gitignore file itself.+ // > Otherwise the pattern may also match at any level below+ // > the .gitignore level.+ ? '(?:^|\\/)'++ // > Otherwise, Git treats the pattern as a shell glob suitable for+ // > consumption by fnmatch(3)+ : '^'+ }+ ],++ // two globstars+ [+ // Use lookahead assertions so that we could match more than one `'/**'`+ /\\\/\\\*\\\*(?=\\\/|$)/g,++ // Zero, one or several directories+ // should not use '*', or it will be replaced by the next replacer++ // Check if it is not the last `'/**'`+ (_, index, str) => index + 6 < str.length++ // case: /**/+ // > A slash followed by two consecutive asterisks then a slash matches+ // > zero or more directories.+ // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.+ // '/**/'+ ? '(?:\\/[^\\/]+)*'++ // case: /**+ // > A trailing `"/**"` matches everything inside.++ // #21: everything inside but it should not include the current folder+ : '\\/.+'+ ],++ // intermediate wildcards+ [+ // Never replace escaped '*'+ // ignore rule '\*' will match the path '*'++ // 'abc.*/' -> go+ // 'abc.*' -> skip this rule+ /(^|[^\\]+)\\\*(?=.+)/g,++ // '*.js' matches '.js'+ // '*.js' doesn't match 'abc'+ (_, p1) => `${p1}[^\\/]*`+ ],++ [+ // unescape, revert step 3 except for back slash+ // For example, if a user escape a '\\*',+ // after step 3, the result will be '\\\\\\*'+ /\\\\\\(?=[$.|*+(){^])/g,+ () => ESCAPE+ ],++ [+ // '\\\\' -> '\\'+ /\\\\/g,+ () => ESCAPE+ ],++ [+ // > The range notation, e.g. [a-zA-Z],+ // > can be used to match one of the characters in a range.++ // `\` is escaped by step 3+ /(\\)?\[([^\]/]*?)(\\*)($|\])/g,+ (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE+ // '\\[bar]' -> '\\\\[bar\\]'+ ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`+ : close === ']'+ ? endEscape.length % 2 === 0+ // A normal case, and it is a range notation+ // '[bar]'+ // '[bar\\\\]'+ ? `[${sanitizeRange(range)}${endEscape}]`+ // Invalid range notaton+ // '[bar\\]' -> '[bar\\\\]'+ : '[]'+ : '[]'+ ],++ // ending+ [+ // 'js' will not match 'js.'+ // 'ab' will not match 'abc'+ /(?:[^*])$/,++ // WTF!+ // https://git-scm.com/docs/gitignore+ // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)+ // which re-fixes #24, #38++ // > If there is a separator at the end of the pattern then the pattern+ // > will only match directories, otherwise the pattern can match both+ // > files and directories.++ // 'js*' will not match 'a.js'+ // 'js/' will not match 'a.js'+ // 'js' will match 'a.js' and 'a.js/'+ match => /\/$/.test(match)+ // foo/ will not match 'foo'+ ? `${match}$`+ // foo matches 'foo' and 'foo/'+ : `${match}(?=$|\\/$)`+ ],++ // trailing wildcard+ [+ /(\^|\\\/)?\\\*$/,+ (_, p1) => {+ const prefix = p1+ // '\^':+ // '/*' does not match EMPTY+ // '/*' does not match everything++ // '\\\/':+ // 'abc/*' does not match 'abc/'+ ? `${p1}[^/]+`++ // 'a*' matches 'a'+ // 'a*' matches 'aa'+ : '[^/]*';++ return `${prefix}(?=$|\\/$)`+ }+ ],+];++// A simple cache, because an ignore rule only has only one certain meaning+const regexCache = Object.create(null);++// @param {pattern}+const makeRegex = (pattern, negative, ignorecase) => {+ const r = regexCache[pattern];+ if (r) {+ return r+ }++ // const replacers = negative+ // ? NEGATIVE_REPLACERS+ // : POSITIVE_REPLACERS++ const source = REPLACERS.reduce(+ (prev, current) => prev.replace(current[0], current[1].bind(pattern)),+ pattern+ );++ return regexCache[pattern] = ignorecase+ ? new RegExp(source, 'i')+ : new RegExp(source)+};++const isString = subject => typeof subject === 'string';++// > A blank line matches no files, so it can serve as a separator for readability.+const checkPattern = pattern => pattern+ && isString(pattern)+ && !REGEX_TEST_BLANK_LINE.test(pattern)++ // > A line starting with # serves as a comment.+ && pattern.indexOf('#') !== 0;++const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);++class IgnoreRule {+ constructor (+ origin,+ pattern,+ negative,+ regex+ ) {+ this.origin = origin;+ this.pattern = pattern;+ this.negative = negative;+ this.regex = regex;+ }+}++const createRule = (pattern, ignorecase) => {+ const origin = pattern;+ let negative = false;++ // > An optional prefix "!" which negates the pattern;+ if (pattern.indexOf('!') === 0) {+ negative = true;+ pattern = pattern.substr(1);+ }++ pattern = pattern+ // > Put a backslash ("\") in front of the first "!" for patterns that+ // > begin with a literal "!", for example, `"\!important!.txt"`.+ .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')+ // > Put a backslash ("\") in front of the first hash for patterns that+ // > begin with a hash.+ .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');++ const regex = makeRegex(pattern, negative, ignorecase);++ return new IgnoreRule(+ origin,+ pattern,+ negative,+ regex+ )+};++const throwError = (message, Ctor) => {+ throw new Ctor(message)+};++const checkPath$1 = (path, originalPath, doThrow) => {+ if (!isString(path)) {+ return doThrow(+ `path must be a string, but got \`${originalPath}\``,+ TypeError+ )+ }++ // We don't know if we should ignore EMPTY, so throw+ if (!path) {+ return doThrow(`path must not be empty`, TypeError)+ }++ // Check if it is a relative path+ if (checkPath$1.isNotRelative(path)) {+ const r = '`path.relative()`d';+ return doThrow(+ `path should be a ${r} string, but got "${originalPath}"`,+ RangeError+ )+ }++ return true+};++const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);++checkPath$1.isNotRelative = isNotRelative;+checkPath$1.convert = p => p;++class Ignore {+ constructor ({+ ignorecase = true+ } = {}) {+ this._rules = [];+ this._ignorecase = ignorecase;+ define(this, KEY_IGNORE, true);+ this._initCache();+ }++ _initCache () {+ this._ignoreCache = Object.create(null);+ this._testCache = Object.create(null);+ }++ _addPattern (pattern) {+ // #32+ if (pattern && pattern[KEY_IGNORE]) {+ this._rules = this._rules.concat(pattern._rules);+ this._added = true;+ return+ }++ if (checkPattern(pattern)) {+ const rule = createRule(pattern, this._ignorecase);+ this._added = true;+ this._rules.push(rule);+ }+ }++ // @param {Array<string> | string | Ignore} pattern+ add (pattern) {+ this._added = false;++ makeArray(+ isString(pattern)+ ? splitPattern(pattern)+ : pattern+ ).forEach(this._addPattern, this);++ // Some rules have just added to the ignore,+ // making the behavior changed.+ if (this._added) {+ this._initCache();+ }++ return this+ }++ // legacy+ addPattern (pattern) {+ return this.add(pattern)+ }++ // | ignored : unignored+ // negative | 0:0 | 0:1 | 1:0 | 1:1+ // -------- | ------- | ------- | ------- | --------+ // 0 | TEST | TEST | SKIP | X+ // 1 | TESTIF | SKIP | TEST | X++ // - SKIP: always skip+ // - TEST: always test+ // - TESTIF: only test if checkUnignored+ // - X: that never happen++ // @param {boolean} whether should check if the path is unignored,+ // setting `checkUnignored` to `false` could reduce additional+ // path matching.++ // @returns {TestResult} true if a file is ignored+ _testOne (path, checkUnignored) {+ let ignored = false;+ let unignored = false;++ this._rules.forEach(rule => {+ const {negative} = rule;+ if (+ unignored === negative && ignored !== unignored+ || negative && !ignored && !unignored && !checkUnignored+ ) {+ return+ }++ const matched = rule.regex.test(path);++ if (matched) {+ ignored = !negative;+ unignored = negative;+ }+ });++ return {+ ignored,+ unignored+ }+ }++ // @returns {TestResult}+ _test (originalPath, cache, checkUnignored, slices) {+ const path = originalPath+ // Supports nullable path+ && checkPath$1.convert(originalPath);++ checkPath$1(path, originalPath, throwError);++ return this._t(path, cache, checkUnignored, slices)+ }++ _t (path, cache, checkUnignored, slices) {+ if (path in cache) {+ return cache[path]+ }++ if (!slices) {+ // path/to/a.js+ // ['path', 'to', 'a.js']+ slices = path.split(SLASH);+ }++ slices.pop();++ // If the path has no parent directory, just test it+ if (!slices.length) {+ return cache[path] = this._testOne(path, checkUnignored)+ }++ const parent = this._t(+ slices.join(SLASH) + SLASH,+ cache,+ checkUnignored,+ slices+ );++ // If the path contains a parent directory, check the parent first+ return cache[path] = parent.ignored+ // > It is not possible to re-include a file if a parent directory of+ // > that file is excluded.+ ? parent+ : this._testOne(path, checkUnignored)+ }++ ignores (path) {+ return this._test(path, this._ignoreCache, false).ignored+ }++ createFilter () {+ return path => !this.ignores(path)+ }++ filter (paths) {+ return makeArray(paths).filter(this.createFilter())+ }++ // @returns {TestResult}+ test (path) {+ return this._test(path, this._testCache, true)+ }+}++const factory = options => new Ignore(options);++const returnFalse = () => false;++const isPathValid = path =>+ checkPath$1(path && checkPath$1.convert(path), path, returnFalse);++factory.isPathValid = isPathValid;++// Fixes typescript+factory.default = factory;++var ignore = factory;++// Windows+// --------------------------------------------------------------+/* istanbul ignore if */+if (+ // Detect `process` so that it can run in browsers.+ typeof process !== 'undefined'+ && (+ process.env && process.env.IGNORE_TEST_WIN32+ || process.platform === 'win32'+ )+) {+ /* eslint no-control-regex: "off" */+ const makePosix = str => /^\\\\\?\\/.test(str)+ || /["<>|\u0000-\u001F]+/u.test(str)+ ? str+ : str.replace(/\\/g, '/');++ checkPath$1.convert = makePosix;++ // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'+ // 'd:\\foo'+ const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;+ checkPath$1.isNotRelative = path =>+ REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path)+ || isNotRelative(path);+}++var slash$1 = path => {+ const isExtendedLengthPath = /^\\\\\?\\/.test(path);+ const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex++ if (isExtendedLengthPath || hasNonAscii) {+ return path;+ }++ return path.replace(/\\/g, '/');+};++const {promisify: promisify$1} = util__default['default'];+++++++const DEFAULT_IGNORE = [+ '**/node_modules/**',+ '**/flow-typed/**',+ '**/coverage/**',+ '**/.git'+];++const readFileP = promisify$1(fs__default['default'].readFile);++const mapGitIgnorePatternTo = base => ignore => {+ if (ignore.startsWith('!')) {+ return '!' + path__default['default'].posix.join(base, ignore.slice(1));+ }++ return path__default['default'].posix.join(base, ignore);+};++const parseGitIgnore = (content, options) => {+ const base = slash$1(path__default['default'].relative(options.cwd, path__default['default'].dirname(options.fileName)));++ return content+ .split(/\r?\n/)+ .filter(Boolean)+ .filter(line => !line.startsWith('#'))+ .map(mapGitIgnorePatternTo(base));+};++const reduceIgnore = files => {+ return files.reduce((ignores, file) => {+ ignores.add(parseGitIgnore(file.content, {+ cwd: file.cwd,+ fileName: file.filePath+ }));+ return ignores;+ }, ignore());+};++const ensureAbsolutePathForCwd = (cwd, p) => {+ cwd = slash$1(cwd);+ if (path__default['default'].isAbsolute(p)) {+ if (p.startsWith(cwd)) {+ return p;+ }++ throw new Error(`Path ${p} is not in cwd ${cwd}`);+ }++ return path__default['default'].join(cwd, p);+};++const getIsIgnoredPredecate = (ignores, cwd) => {+ return p => ignores.ignores(slash$1(path__default['default'].relative(cwd, ensureAbsolutePathForCwd(cwd, p))));+};++const getFile = async (file, cwd) => {+ const filePath = path__default['default'].join(cwd, file);+ const content = await readFileP(filePath, 'utf8');++ return {+ cwd,+ filePath,+ content+ };+};++const getFileSync = (file, cwd) => {+ const filePath = path__default['default'].join(cwd, file);+ const content = fs__default['default'].readFileSync(filePath, 'utf8');++ return {+ cwd,+ filePath,+ content+ };+};++const normalizeOptions = ({+ ignore = [],+ cwd = slash$1(process.cwd())+} = {}) => {+ return {ignore, cwd};+};++var gitignore = async options => {+ options = normalizeOptions(options);++ const paths = await out$3('**/.gitignore', {+ ignore: DEFAULT_IGNORE.concat(options.ignore),+ cwd: options.cwd+ });++ const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));+ const ignores = reduceIgnore(files);++ return getIsIgnoredPredecate(ignores, options.cwd);+};++var sync$7 = options => {+ options = normalizeOptions(options);++ const paths = out$3.sync('**/.gitignore', {+ ignore: DEFAULT_IGNORE.concat(options.ignore),+ cwd: options.cwd+ });++ const files = paths.map(file => getFileSync(file, options.cwd));+ const ignores = reduceIgnore(files);++ return getIsIgnoredPredecate(ignores, options.cwd);+};+gitignore.sync = sync$7;++const {Transform} = Stream__default['default'];++class ObjectTransform extends Transform {+ constructor() {+ super({+ objectMode: true+ });+ }+}++class FilterStream extends ObjectTransform {+ constructor(filter) {+ super();+ this._filter = filter;+ }++ _transform(data, encoding, callback) {+ if (this._filter(data)) {+ this.push(data);+ }++ callback();+ }+}++class UniqueStream extends ObjectTransform {+ constructor() {+ super();+ this._pushed = new Set();+ }++ _transform(data, encoding, callback) {+ if (!this._pushed.has(data)) {+ this.push(data);+ this._pushed.add(data);+ }++ callback();+ }+}++var streamUtils = {+ FilterStream,+ UniqueStream+};++const {FilterStream: FilterStream$1, UniqueStream: UniqueStream$1} = streamUtils;++const DEFAULT_FILTER = () => false;++const isNegative = pattern => pattern[0] === '!';++const assertPatternsInput$1 = patterns => {+ if (!patterns.every(pattern => typeof pattern === 'string')) {+ throw new TypeError('Patterns must be a string or an array of strings');+ }+};++const checkCwdOption = (options = {}) => {+ if (!options.cwd) {+ return;+ }++ let stat;+ try {+ stat = fs__default['default'].statSync(options.cwd);+ } catch (_) {+ return;+ }++ if (!stat.isDirectory()) {+ throw new Error('The `cwd` option must be a path to a directory');+ }+};++const getPathString = p => p.stats instanceof fs__default['default'].Stats ? p.path : p;++const generateGlobTasks = (patterns, taskOptions) => {+ patterns = arrayUnion([].concat(patterns));+ assertPatternsInput$1(patterns);+ checkCwdOption(taskOptions);++ const globTasks = [];++ taskOptions = {+ ignore: [],+ expandDirectories: true,+ ...taskOptions+ };++ for (const [index, pattern] of patterns.entries()) {+ if (isNegative(pattern)) {+ continue;+ }++ const ignore = patterns+ .slice(index)+ .filter(isNegative)+ .map(pattern => pattern.slice(1));++ const options = {+ ...taskOptions,+ ignore: taskOptions.ignore.concat(ignore)+ };++ globTasks.push({pattern, options});+ }++ return globTasks;+};++const globDirs = (task, fn) => {+ let options = {};+ if (task.options.cwd) {+ options.cwd = task.options.cwd;+ }++ if (Array.isArray(task.options.expandDirectories)) {+ options = {+ ...options,+ files: task.options.expandDirectories+ };+ } else if (typeof task.options.expandDirectories === 'object') {+ options = {+ ...options,+ ...task.options.expandDirectories+ };+ }++ return fn(task.pattern, options);+};++const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];++const getFilterSync = options => {+ return options && options.gitignore ?+ gitignore.sync({cwd: options.cwd, ignore: options.ignore}) :+ DEFAULT_FILTER;+};++const globToTask = task => glob => {+ const {options} = task;+ if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {+ options.ignore = dirGlob.sync(options.ignore);+ }++ return {+ pattern: glob,+ options+ };+};++var globby$1 = async (patterns, options) => {+ const globTasks = generateGlobTasks(patterns, options);++ const getFilter = async () => {+ return options && options.gitignore ?+ gitignore({cwd: options.cwd, ignore: options.ignore}) :+ DEFAULT_FILTER;+ };++ const getTasks = async () => {+ const tasks = await Promise.all(globTasks.map(async task => {+ const globs = await getPattern(task, dirGlob);+ return Promise.all(globs.map(globToTask(task)));+ }));++ return arrayUnion(...tasks);+ };++ const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);+ const paths = await Promise.all(tasks.map(task => out$3(task.pattern, task.options)));++ return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));+};++var sync$8 = (patterns, options) => {+ const globTasks = generateGlobTasks(patterns, options);++ const tasks = globTasks.reduce((tasks, task) => {+ const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));+ return tasks.concat(newTask);+ }, []);++ const filter = getFilterSync(options);++ return tasks.reduce(+ (matches, task) => arrayUnion(matches, out$3.sync(task.pattern, task.options)),+ []+ ).filter(path_ => !filter(path_));+};++var stream$4 = (patterns, options) => {+ const globTasks = generateGlobTasks(patterns, options);++ const tasks = globTasks.reduce((tasks, task) => {+ const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));+ return tasks.concat(newTask);+ }, []);++ const filter = getFilterSync(options);+ const filterStream = new FilterStream$1(p => !filter(p));+ const uniqueStream = new UniqueStream$1();++ return merge2_1(tasks.map(task => out$3.stream(task.pattern, task.options)))+ .pipe(filterStream)+ .pipe(uniqueStream);+};++var generateGlobTasks_1 = generateGlobTasks;++var hasMagic = (patterns, options) => []+ .concat(patterns)+ .some(pattern => out$3.isDynamicPattern(pattern, options));++var gitignore_1 = gitignore;+globby$1.sync = sync$8;+globby$1.stream = stream$4;+globby$1.generateGlobTasks = generateGlobTasks_1;+globby$1.hasMagic = hasMagic;+globby$1.gitignore = gitignore_1;++/*+ * fn: The function to decorate with the logger+ * logger: an object instance of type Logger+ * hint: an optional hint to add to the error's message+ */+function decorateWithLogger(fn, logger, hint) {+ const resolver = fn != null ? fn : defaultFieldResolver;+ const logError = (e) => {+ // TODO: clone the error properly+ const newE = new Error();+ newE.stack = e.stack;+ /* istanbul ignore else: always get the hint from addErrorLoggingToSchema */+ if (hint) {+ newE['originalMessage'] = e.message;+ newE.message = `Error in resolver ${hint}\n${e.message}`;+ }+ logger.log(newE);+ };+ return (root, args, ctx, info) => {+ try {+ const result = resolver(root, args, ctx, info);+ // If the resolver returns a Promise log any Promise rejects.+ if (result && typeof result.then === 'function' && typeof result.catch === 'function') {+ result.catch((reason) => {+ // make sure that it's an error we're logging.+ const error = reason instanceof Error ? reason : new Error(reason);+ logError(error);+ // We don't want to leave an unhandled exception so pass on error.+ return reason;+ });+ }+ return result;+ }+ catch (e) {+ logError(e);+ // we want to pass on the error, just in case.+ throw e;+ }+ };+}++// If we have any union or interface types throw if no there is no resolveType or isTypeOf resolvers+function checkForResolveTypeResolver(schema, requireResolversForResolveType) {+ Object.keys(schema.getTypeMap())+ .map(typeName => schema.getType(typeName))+ .forEach((type) => {+ if (!isAbstractType(type)) {+ return;+ }+ if (!type.resolveType) {+ if (!requireResolversForResolveType) {+ return;+ }+ throw new Error(`Type "${type.name}" is missing a "__resolveType" resolver. Pass false into ` ++ '"resolverValidationOptions.requireResolversForResolveType" to disable this error.');+ }+ });+}++function extendResolversFromInterfaces(schema, resolvers) {+ const typeNames = Object.keys({+ ...schema.getTypeMap(),+ ...resolvers,+ });+ const extendedResolvers = {};+ typeNames.forEach(typeName => {+ const type = schema.getType(typeName);+ if ('getInterfaces' in type) {+ const allInterfaceResolvers = type+ .getInterfaces()+ .map(iFace => resolvers[iFace.name])+ .filter(interfaceResolvers => interfaceResolvers != null);+ extendedResolvers[typeName] = {};+ allInterfaceResolvers.forEach(interfaceResolvers => {+ Object.keys(interfaceResolvers).forEach(fieldName => {+ if (fieldName === '__isTypeOf' || !fieldName.startsWith('__')) {+ extendedResolvers[typeName][fieldName] = interfaceResolvers[fieldName];+ }+ });+ });+ const typeResolvers = resolvers[typeName];+ extendedResolvers[typeName] = {+ ...extendedResolvers[typeName],+ ...typeResolvers,+ };+ }+ else {+ const typeResolvers = resolvers[typeName];+ if (typeResolvers != null) {+ extendedResolvers[typeName] = typeResolvers;+ }+ }+ });+ return extendedResolvers;+}++function addResolversToSchema(schemaOrOptions, legacyInputResolvers, legacyInputValidationOptions) {+ const options = isSchema(schemaOrOptions)+ ? {+ schema: schemaOrOptions,+ resolvers: legacyInputResolvers,+ resolverValidationOptions: legacyInputValidationOptions,+ }+ : schemaOrOptions;+ let { schema, resolvers: inputResolvers, defaultFieldResolver, resolverValidationOptions = {}, inheritResolversFromInterfaces = false, updateResolversInPlace = false, } = options;+ const { allowResolversNotInSchema = false, requireResolversForResolveType } = resolverValidationOptions;+ const resolvers = inheritResolversFromInterfaces+ ? extendResolversFromInterfaces(schema, inputResolvers)+ : inputResolvers;+ Object.keys(resolvers).forEach(typeName => {+ const resolverValue = resolvers[typeName];+ const resolverType = typeof resolverValue;+ if (typeName === '__schema') {+ if (resolverType !== 'function') {+ throw new Error(`"${typeName}" defined in resolvers, but has invalid value "${resolverValue}". A schema resolver's value must be of type object or function.`);+ }+ }+ else {+ if (resolverType !== 'object') {+ throw new Error(`"${typeName}" defined in resolvers, but has invalid value "${resolverValue}". The resolver's value must be of type object.`);+ }+ const type = schema.getType(typeName);+ if (type == null) {+ if (allowResolversNotInSchema) {+ return;+ }+ throw new Error(`"${typeName}" defined in resolvers, but not in schema`);+ }+ else if (isSpecifiedScalarType(type)) {+ // allow -- without recommending -- overriding of specified scalar types+ Object.keys(resolverValue).forEach(fieldName => {+ if (fieldName.startsWith('__')) {+ type[fieldName.substring(2)] = resolverValue[fieldName];+ }+ else {+ type[fieldName] = resolverValue[fieldName];+ }+ });+ }+ else if (isEnumType(type)) {+ const values = type.getValues();+ Object.keys(resolverValue).forEach(fieldName => {+ if (!fieldName.startsWith('__') &&+ !values.some(value => value.name === fieldName) &&+ !allowResolversNotInSchema) {+ throw new Error(`${type.name}.${fieldName} was defined in resolvers, but not present within ${type.name}`);+ }+ });+ }+ else if (isUnionType(type)) {+ Object.keys(resolverValue).forEach(fieldName => {+ if (!fieldName.startsWith('__') && !allowResolversNotInSchema) {+ throw new Error(`${type.name}.${fieldName} was defined in resolvers, but ${type.name} is not an object or interface type`);+ }+ });+ }+ else if (isObjectType(type) || isInterfaceType(type)) {+ Object.keys(resolverValue).forEach(fieldName => {+ if (!fieldName.startsWith('__')) {+ const fields = type.getFields();+ const field = fields[fieldName];+ if (field == null && !allowResolversNotInSchema) {+ throw new Error(`${typeName}.${fieldName} defined in resolvers, but not in schema`);+ }+ const fieldResolve = resolverValue[fieldName];+ if (typeof fieldResolve !== 'function' && typeof fieldResolve !== 'object') {+ throw new Error(`Resolver ${typeName}.${fieldName} must be object or function`);+ }+ }+ });+ }+ }+ });+ schema = updateResolversInPlace+ ? addResolversToExistingSchema(schema, resolvers, defaultFieldResolver)+ : createNewSchemaWithResolvers(schema, resolvers, defaultFieldResolver);+ checkForResolveTypeResolver(schema, requireResolversForResolveType);+ return schema;+}+function addResolversToExistingSchema(schema, resolvers, defaultFieldResolver) {+ const typeMap = schema.getTypeMap();+ Object.keys(resolvers).forEach(typeName => {+ if (typeName !== '__schema') {+ const type = schema.getType(typeName);+ const resolverValue = resolvers[typeName];+ if (isScalarType(type)) {+ Object.keys(resolverValue).forEach(fieldName => {+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;+ if (fieldName.startsWith('__')) {+ type[fieldName.substring(2)] = resolverValue[fieldName];+ }+ else if (fieldName === 'astNode' && type.astNode != null) {+ type.astNode = {+ ...type.astNode,+ description: (_c = (_b = (_a = resolverValue) === null || _a === void 0 ? void 0 : _a.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : type.astNode.description,+ directives: ((_d = type.astNode.directives) !== null && _d !== void 0 ? _d : []).concat((_g = (_f = (_e = resolverValue) === null || _e === void 0 ? void 0 : _e.astNode) === null || _f === void 0 ? void 0 : _f.directives) !== null && _g !== void 0 ? _g : []),+ };+ }+ else if (fieldName === 'extensionASTNodes' && type.extensionASTNodes != null) {+ type.extensionASTNodes = ((_h = []) !== null && _h !== void 0 ? _h : type.extensionASTNodes).concat((_k = (_j = resolverValue) === null || _j === void 0 ? void 0 : _j.extensionASTNodes) !== null && _k !== void 0 ? _k : []);+ }+ else if (fieldName === 'extensions' &&+ type.extensions != null &&+ resolverValue.extensions != null) {+ type.extensions = Object.assign({}, type.extensions, resolverValue.extensions);+ }+ else {+ type[fieldName] = resolverValue[fieldName];+ }+ });+ }+ else if (isEnumType(type)) {+ const config = type.toConfig();+ const enumValueConfigMap = config.values;+ Object.keys(resolverValue).forEach(fieldName => {+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;+ if (fieldName.startsWith('__')) {+ config[fieldName.substring(2)] = resolverValue[fieldName];+ }+ else if (fieldName === 'astNode' && config.astNode != null) {+ config.astNode = {+ ...config.astNode,+ description: (_c = (_b = (_a = resolverValue) === null || _a === void 0 ? void 0 : _a.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : config.astNode.description,+ directives: ((_d = config.astNode.directives) !== null && _d !== void 0 ? _d : []).concat((_g = (_f = (_e = resolverValue) === null || _e === void 0 ? void 0 : _e.astNode) === null || _f === void 0 ? void 0 : _f.directives) !== null && _g !== void 0 ? _g : []),+ };+ }+ else if (fieldName === 'extensionASTNodes' && config.extensionASTNodes != null) {+ config.extensionASTNodes = config.extensionASTNodes.concat((_j = (_h = resolverValue) === null || _h === void 0 ? void 0 : _h.extensionASTNodes) !== null && _j !== void 0 ? _j : []);+ }+ else if (fieldName === 'extensions' &&+ type.extensions != null &&+ resolverValue.extensions != null) {+ type.extensions = Object.assign({}, type.extensions, resolverValue.extensions);+ }+ else if (enumValueConfigMap[fieldName]) {+ enumValueConfigMap[fieldName].value = resolverValue[fieldName];+ }+ });+ typeMap[typeName] = new GraphQLEnumType(config);+ }+ else if (isUnionType(type)) {+ Object.keys(resolverValue).forEach(fieldName => {+ if (fieldName.startsWith('__')) {+ type[fieldName.substring(2)] = resolverValue[fieldName];+ }+ });+ }+ else if (isObjectType(type) || isInterfaceType(type)) {+ Object.keys(resolverValue).forEach(fieldName => {+ if (fieldName.startsWith('__')) {+ // this is for isTypeOf and resolveType and all the other stuff.+ type[fieldName.substring(2)] = resolverValue[fieldName];+ return;+ }+ const fields = type.getFields();+ const field = fields[fieldName];+ if (field != null) {+ const fieldResolve = resolverValue[fieldName];+ if (typeof fieldResolve === 'function') {+ // for convenience. Allows shorter syntax in resolver definition file+ field.resolve = fieldResolve;+ }+ else {+ setFieldProperties(field, fieldResolve);+ }+ }+ });+ }+ }+ });+ // serialize all default values prior to healing fields with new scalar/enum types.+ forEachDefaultValue(schema, serializeInputValue);+ // schema may have new scalar/enum types that require healing+ healSchema(schema);+ // reparse all default values with new parsing functions.+ forEachDefaultValue(schema, parseInputValue);+ if (defaultFieldResolver != null) {+ forEachField(schema, field => {+ if (!field.resolve) {+ field.resolve = defaultFieldResolver;+ }+ });+ }+ return schema;+}+function createNewSchemaWithResolvers(schema, resolvers, defaultFieldResolver) {+ schema = mapSchema(schema, {+ [MapperKind.SCALAR_TYPE]: type => {+ const config = type.toConfig();+ const resolverValue = resolvers[type.name];+ if (!isSpecifiedScalarType(type) && resolverValue != null) {+ Object.keys(resolverValue).forEach(fieldName => {+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;+ if (fieldName.startsWith('__')) {+ config[fieldName.substring(2)] = resolverValue[fieldName];+ }+ else if (fieldName === 'astNode' && config.astNode != null) {+ config.astNode = {+ ...config.astNode,+ description: (_c = (_b = (_a = resolverValue) === null || _a === void 0 ? void 0 : _a.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : config.astNode.description,+ directives: ((_d = config.astNode.directives) !== null && _d !== void 0 ? _d : []).concat((_g = (_f = (_e = resolverValue) === null || _e === void 0 ? void 0 : _e.astNode) === null || _f === void 0 ? void 0 : _f.directives) !== null && _g !== void 0 ? _g : []),+ };+ }+ else if (fieldName === 'extensionASTNodes' && config.extensionASTNodes != null) {+ config.extensionASTNodes = config.extensionASTNodes.concat((_j = (_h = resolverValue) === null || _h === void 0 ? void 0 : _h.extensionASTNodes) !== null && _j !== void 0 ? _j : []);+ }+ else if (fieldName === 'extensions' &&+ config.extensions != null &&+ resolverValue.extensions != null) {+ config.extensions = Object.assign({}, type.extensions, resolverValue.extensions);+ }+ else {+ config[fieldName] = resolverValue[fieldName];+ }+ });+ return new GraphQLScalarType(config);+ }+ },+ [MapperKind.ENUM_TYPE]: type => {+ const resolverValue = resolvers[type.name];+ const config = type.toConfig();+ const enumValueConfigMap = config.values;+ if (resolverValue != null) {+ Object.keys(resolverValue).forEach(fieldName => {+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;+ if (fieldName.startsWith('__')) {+ config[fieldName.substring(2)] = resolverValue[fieldName];+ }+ else if (fieldName === 'astNode' && config.astNode != null) {+ config.astNode = {+ ...config.astNode,+ description: (_c = (_b = (_a = resolverValue) === null || _a === void 0 ? void 0 : _a.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : config.astNode.description,+ directives: ((_d = config.astNode.directives) !== null && _d !== void 0 ? _d : []).concat((_g = (_f = (_e = resolverValue) === null || _e === void 0 ? void 0 : _e.astNode) === null || _f === void 0 ? void 0 : _f.directives) !== null && _g !== void 0 ? _g : []),+ };+ }+ else if (fieldName === 'extensionASTNodes' && config.extensionASTNodes != null) {+ config.extensionASTNodes = config.extensionASTNodes.concat((_j = (_h = resolverValue) === null || _h === void 0 ? void 0 : _h.extensionASTNodes) !== null && _j !== void 0 ? _j : []);+ }+ else if (fieldName === 'extensions' &&+ config.extensions != null &&+ resolverValue.extensions != null) {+ config.extensions = Object.assign({}, type.extensions, resolverValue.extensions);+ }+ else if (enumValueConfigMap[fieldName]) {+ enumValueConfigMap[fieldName].value = resolverValue[fieldName];+ }+ });+ return new GraphQLEnumType(config);+ }+ },+ [MapperKind.UNION_TYPE]: type => {+ const resolverValue = resolvers[type.name];+ if (resolverValue != null) {+ const config = type.toConfig();+ Object.keys(resolverValue).forEach(fieldName => {+ if (fieldName.startsWith('__')) {+ config[fieldName.substring(2)] = resolverValue[fieldName];+ }+ });+ return new GraphQLUnionType(config);+ }+ },+ [MapperKind.OBJECT_TYPE]: type => {+ const resolverValue = resolvers[type.name];+ if (resolverValue != null) {+ const config = type.toConfig();+ Object.keys(resolverValue).forEach(fieldName => {+ if (fieldName.startsWith('__')) {+ config[fieldName.substring(2)] = resolverValue[fieldName];+ }+ });+ return new GraphQLObjectType(config);+ }+ },+ [MapperKind.INTERFACE_TYPE]: type => {+ const resolverValue = resolvers[type.name];+ if (resolverValue != null) {+ const config = type.toConfig();+ Object.keys(resolverValue).forEach(fieldName => {+ if (fieldName.startsWith('__')) {+ config[fieldName.substring(2)] = resolverValue[fieldName];+ }+ });+ return new GraphQLInterfaceType(config);+ }+ },+ [MapperKind.COMPOSITE_FIELD]: (fieldConfig, fieldName, typeName) => {+ const resolverValue = resolvers[typeName];+ if (resolverValue != null) {+ const fieldResolve = resolverValue[fieldName];+ if (fieldResolve != null) {+ const newFieldConfig = { ...fieldConfig };+ if (typeof fieldResolve === 'function') {+ // for convenience. Allows shorter syntax in resolver definition file+ newFieldConfig.resolve = fieldResolve;+ }+ else {+ setFieldProperties(newFieldConfig, fieldResolve);+ }+ return newFieldConfig;+ }+ }+ },+ });+ if (defaultFieldResolver != null) {+ schema = mapSchema(schema, {+ [MapperKind.OBJECT_FIELD]: fieldConfig => ({+ ...fieldConfig,+ resolve: fieldConfig.resolve != null ? fieldConfig.resolve : defaultFieldResolver,+ }),+ });+ }+ return schema;+}+function setFieldProperties(field, propertiesObj) {+ Object.keys(propertiesObj).forEach(propertyName => {+ field[propertyName] = propertiesObj[propertyName];+ });+}++function addErrorLoggingToSchema(schema, logger) {+ if (!logger) {+ throw new Error('Must provide a logger');+ }+ if (typeof logger.log !== 'function') {+ throw new Error('Logger.log must be a function');+ }+ return mapSchema(schema, {+ [MapperKind.OBJECT_FIELD]: (fieldConfig, fieldName, typeName) => ({+ ...fieldConfig,+ resolve: decorateWithLogger(fieldConfig.resolve, logger, `${typeName}.${fieldName}`),+ }),+ });+}++/**+ * Deep merges multiple resolver definition objects into a single definition.+ * @param resolversDefinitions Resolver definitions to be merged+ * @param options Additional options+ *+ * ```js+ * const { mergeResolvers } = require('@graphql-tools/merge');+ * const clientResolver = require('./clientResolver');+ * const productResolver = require('./productResolver');+ *+ * const resolvers = mergeResolvers([+ * clientResolver,+ * productResolver,+ * ]);+ * ```+ *+ * If you don't want to manually create the array of resolver objects, you can+ * also use this function along with loadFiles:+ *+ * ```js+ * const path = require('path');+ * const { mergeResolvers } = require('@graphql-tools/merge');+ * const { loadFilesSync } = require('@graphql-tools/load-files');+ *+ * const resolversArray = loadFilesSync(path.join(__dirname, './resolvers'));+ *+ * const resolvers = mergeResolvers(resolversArray)+ * ```+ */+function mergeResolvers(resolversDefinitions, options) {+ if (!resolversDefinitions || resolversDefinitions.length === 0) {+ return {};+ }+ if (resolversDefinitions.length === 1) {+ const singleDefinition = resolversDefinitions[0];+ if (Array.isArray(singleDefinition)) {+ return mergeResolvers(singleDefinition);+ }+ return singleDefinition;+ }+ const resolversFactories = new Array();+ const resolvers = new Array();+ for (let resolversDefinition of resolversDefinitions) {+ if (Array.isArray(resolversDefinition)) {+ resolversDefinition = mergeResolvers(resolversDefinition);+ }+ if (typeof resolversDefinition === 'function') {+ resolversFactories.push(resolversDefinition);+ }+ else if (typeof resolversDefinition === 'object') {+ resolvers.push(resolversDefinition);+ }+ }+ let result = {};+ if (resolversFactories.length) {+ result = ((...args) => {+ const resultsOfFactories = resolversFactories.map(factory => factory(...args));+ return resolvers.concat(resultsOfFactories).reduce(mergeDeep, {});+ });+ }+ else {+ result = resolvers.reduce(mergeDeep, {});+ }+ if (options && options.exclusions) {+ for (const exclusion of options.exclusions) {+ const [typeName, fieldName] = exclusion.split('.');+ if (!fieldName || fieldName === '*') {+ delete result[typeName];+ }+ else if (result[typeName]) {+ delete result[typeName][fieldName];+ }+ }+ }+ return result;+}++function mergeArguments$2(args1, args2, config) {+ const result = deduplicateArguments$1([].concat(args2, args1).filter(a => a));+ if (config && config.sort) {+ result.sort(compareNodes);+ }+ return result;+}+function deduplicateArguments$1(args) {+ return args.reduce((acc, current) => {+ const dup = acc.find(arg => arg.name.value === current.name.value);+ if (!dup) {+ return acc.concat([current]);+ }+ return acc;+ }, []);+}++let commentsRegistry$1 = {};+function resetComments$1() {+ commentsRegistry$1 = {};+}+function collectComment$1(node) {+ const entityName = node.name.value;+ pushComment$1(node, entityName);+ switch (node.kind) {+ case 'EnumTypeDefinition':+ node.values.forEach(value => {+ pushComment$1(value, entityName, value.name.value);+ });+ break;+ case 'ObjectTypeDefinition':+ case 'InputObjectTypeDefinition':+ case 'InterfaceTypeDefinition':+ if (node.fields) {+ node.fields.forEach((field) => {+ pushComment$1(field, entityName, field.name.value);+ if (isFieldDefinitionNode$1(field) && field.arguments) {+ field.arguments.forEach(arg => {+ pushComment$1(arg, entityName, field.name.value, arg.name.value);+ });+ }+ });+ }+ break;+ }+}+function pushComment$1(node, entity, field, argument) {+ const comment = getDescription(node, { commentDescriptions: true });+ if (typeof comment !== 'string' || comment.length === 0) {+ return;+ }+ const keys = [entity];+ if (field) {+ keys.push(field);+ if (argument) {+ keys.push(argument);+ }+ }+ const path = keys.join('.');+ if (!commentsRegistry$1[path]) {+ commentsRegistry$1[path] = [];+ }+ commentsRegistry$1[path].push(comment);+}+function printComment$1(comment) {+ return '\n# ' + comment.replace(/\n/g, '\n# ');+}+/**+ * 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.+ */+/**+ * NOTE: ==> This file has been modified just to add comments to the printed AST+ * This is a temp measure, we will move to using the original non modified printer.js ASAP.+ */+// import { visit, VisitFn } from 'graphql/language/visitor';+/**+ * Given maybeArray, print an empty string if it is null or empty, otherwise+ * print all items together separated by separator if provided+ */+function join$2(maybeArray, separator) {+ return maybeArray ? maybeArray.filter(x => x).join(separator || '') : '';+}+function addDescription$2(cb) {+ return (node, _key, _parent, path, ancestors) => {+ const keys = [];+ const parent = path.reduce((prev, key) => {+ if (['fields', 'arguments', 'values'].includes(key)) {+ keys.push(prev.name.value);+ }+ return prev[key];+ }, ancestors[0]);+ const key = [...keys, parent.name.value].join('.');+ const items = [];+ if (commentsRegistry$1[key]) {+ items.push(...commentsRegistry$1[key]);+ }+ return join$2([...items.map(printComment$1), node.description, cb(node)], '\n');+ };+}+function indent$2(maybeString) {+ return maybeString && ` ${maybeString.replace(/\n/g, '\n ')}`;+}+/**+ * Given array, print each item on its own line, wrapped in an+ * indented "{ }" block.+ */+function block$2(array) {+ return array && array.length !== 0 ? `{\n${indent$2(join$2(array, '\n'))}\n}` : '';+}+/**+ * If maybeString is not null or empty, then wrap with start and end, otherwise+ * print an empty string.+ */+function wrap$2(start, maybeString, end) {+ return maybeString ? start + maybeString + (end || '') : '';+}+/**+ * 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$2(value, isDescription) {+ const escaped = value.replace(/"""/g, '\\"""');+ return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1+ ? `"""${escaped.replace(/"$/, '"\n')}"""`+ : `"""\n${isDescription ? escaped : indent$2(escaped)}\n"""`;+}+/**+ * Converts an AST into a string, using one set of reasonable+ * formatting rules.+ */+function printWithComments$1(ast) {+ return visit(ast, {+ leave: {+ Name: node => node.value,+ Variable: node => `$${node.name}`,+ // Document+ Document: node => `${node.definitions+ .map(defNode => `${defNode}\n${defNode[0] === '#' ? '' : '\n'}`)+ .join('')+ .trim()}\n`,+ OperationTypeDefinition: node => `${node.operation}: ${node.type}`,+ VariableDefinition: ({ variable, type, defaultValue }) => `${variable}: ${type}${wrap$2(' = ', defaultValue)}`,+ SelectionSet: ({ selections }) => block$2(selections),+ Field: ({ alias, name, arguments: args, directives, selectionSet }) => join$2([wrap$2('', alias, ': ') + name + wrap$2('(', join$2(args, ', '), ')'), join$2(directives, ' '), selectionSet], ' '),+ Argument: addDescription$2(({ name, value }) => `${name}: ${value}`),+ // Value+ IntValue: ({ value }) => value,+ FloatValue: ({ value }) => value,+ StringValue: ({ value, block: isBlockString }, key) => isBlockString ? printBlockString$2(value, key === 'description') : JSON.stringify(value),+ BooleanValue: ({ value }) => (value ? 'true' : 'false'),+ NullValue: () => 'null',+ EnumValue: ({ value }) => value,+ ListValue: ({ values }) => `[${join$2(values, ', ')}]`,+ ObjectValue: ({ fields }) => `{${join$2(fields, ', ')}}`,+ ObjectField: ({ name, value }) => `${name}: ${value}`,+ // Directive+ Directive: ({ name, arguments: args }) => `@${name}${wrap$2('(', join$2(args, ', '), ')')}`,+ // Type+ NamedType: ({ name }) => name,+ ListType: ({ type }) => `[${type}]`,+ NonNullType: ({ type }) => `${type}!`,+ // Type System Definitions+ SchemaDefinition: ({ directives, operationTypes }) => join$2(['schema', join$2(directives, ' '), block$2(operationTypes)], ' '),+ ScalarTypeDefinition: addDescription$2(({ name, directives }) => join$2(['scalar', name, join$2(directives, ' ')], ' ')),+ ObjectTypeDefinition: addDescription$2(({ name, interfaces, directives, fields }) => join$2(['type', name, wrap$2('implements ', join$2(interfaces, ' & ')), join$2(directives, ' '), block$2(fields)], ' ')),+ FieldDefinition: addDescription$2(({ name, arguments: args, type, directives }) => `${name + wrap$2('(', join$2(args, ', '), ')')}: ${type}${wrap$2(' ', join$2(directives, ' '))}`),+ InputValueDefinition: addDescription$2(({ name, type, defaultValue, directives }) => join$2([`${name}: ${type}`, wrap$2('= ', defaultValue), join$2(directives, ' ')], ' ')),+ InterfaceTypeDefinition: addDescription$2(({ name, directives, fields }) => join$2(['interface', name, join$2(directives, ' '), block$2(fields)], ' ')),+ UnionTypeDefinition: addDescription$2(({ name, directives, types }) => join$2(['union', name, join$2(directives, ' '), types && types.length !== 0 ? `= ${join$2(types, ' | ')}` : ''], ' ')),+ EnumTypeDefinition: addDescription$2(({ name, directives, values }) => join$2(['enum', name, join$2(directives, ' '), block$2(values)], ' ')),+ EnumValueDefinition: addDescription$2(({ name, directives }) => join$2([name, join$2(directives, ' ')], ' ')),+ InputObjectTypeDefinition: addDescription$2(({ name, directives, fields }) => join$2(['input', name, join$2(directives, ' '), block$2(fields)], ' ')),+ ScalarTypeExtension: ({ name, directives }) => join$2(['extend scalar', name, join$2(directives, ' ')], ' '),+ ObjectTypeExtension: ({ name, interfaces, directives, fields }) => join$2(['extend type', name, wrap$2('implements ', join$2(interfaces, ' & ')), join$2(directives, ' '), block$2(fields)], ' '),+ InterfaceTypeExtension: ({ name, directives, fields }) => join$2(['extend interface', name, join$2(directives, ' '), block$2(fields)], ' '),+ UnionTypeExtension: ({ name, directives, types }) => join$2(['extend union', name, join$2(directives, ' '), types && types.length !== 0 ? `= ${join$2(types, ' | ')}` : ''], ' '),+ EnumTypeExtension: ({ name, directives, values }) => join$2(['extend enum', name, join$2(directives, ' '), block$2(values)], ' '),+ InputObjectTypeExtension: ({ name, directives, fields }) => join$2(['extend input', name, join$2(directives, ' '), block$2(fields)], ' '),+ DirectiveDefinition: addDescription$2(({ name, arguments: args, locations }) => `directive @${name}${wrap$2('(', join$2(args, ', '), ')')} on ${join$2(locations, ' | ')}`),+ },+ });+}+function isFieldDefinitionNode$1(node) {+ return node.kind === 'FieldDefinition';+}++function directiveAlreadyExists$1(directivesArr, otherDirective) {+ return !!directivesArr.find(directive => directive.name.value === otherDirective.name.value);+}+function nameAlreadyExists$1(name, namesArr) {+ return namesArr.some(({ value }) => value === name.value);+}+function mergeArguments$1$1(a1, a2) {+ const result = [...a2];+ for (const argument of a1) {+ const existingIndex = result.findIndex(a => a.name.value === argument.name.value);+ if (existingIndex > -1) {+ const existingArg = result[existingIndex];+ if (existingArg.value.kind === 'ListValue') {+ const source = existingArg.value.values;+ const target = argument.value.values;+ // merge values of two lists+ existingArg.value.values = deduplicateLists$1(source, target, (targetVal, source) => {+ const value = targetVal.value;+ return !value || !source.some((sourceVal) => sourceVal.value === value);+ });+ }+ else {+ existingArg.value = argument.value;+ }+ }+ else {+ result.push(argument);+ }+ }+ return result;+}+function deduplicateDirectives$1(directives) {+ return directives+ .map((directive, i, all) => {+ const firstAt = all.findIndex(d => d.name.value === directive.name.value);+ if (firstAt !== i) {+ const dup = all[firstAt];+ directive.arguments = mergeArguments$1$1(directive.arguments, dup.arguments);+ return null;+ }+ return directive;+ })+ .filter(d => d);+}+function mergeDirectives$1(d1 = [], d2 = [], config) {+ const reverseOrder = config && config.reverseDirectives;+ const asNext = reverseOrder ? d1 : d2;+ const asFirst = reverseOrder ? d2 : d1;+ const result = deduplicateDirectives$1([...asNext]);+ for (const directive of asFirst) {+ if (directiveAlreadyExists$1(result, directive)) {+ const existingDirectiveIndex = result.findIndex(d => d.name.value === directive.name.value);+ const existingDirective = result[existingDirectiveIndex];+ result[existingDirectiveIndex].arguments = mergeArguments$1$1(directive.arguments || [], existingDirective.arguments || []);+ }+ else {+ result.push(directive);+ }+ }+ return result;+}+function validateInputs$1(node, existingNode) {+ const printedNode = print(node);+ const printedExistingNode = print(existingNode);+ const leaveInputs = new RegExp('(directive @w*d*)|( on .*$)', 'g');+ const sameArguments = printedNode.replace(leaveInputs, '') === printedExistingNode.replace(leaveInputs, '');+ if (!sameArguments) {+ throw new Error(`Unable to merge GraphQL directive "${node.name.value}". \nExisting directive: \n\t${printedExistingNode} \nReceived directive: \n\t${printedNode}`);+ }+}+function mergeDirective$1(node, existingNode) {+ if (existingNode) {+ validateInputs$1(node, existingNode);+ return {+ ...node,+ locations: [+ ...existingNode.locations,+ ...node.locations.filter(name => !nameAlreadyExists$1(name, existingNode.locations)),+ ],+ };+ }+ return node;+}+function deduplicateLists$1(source, target, filterFn) {+ return source.concat(target.filter(val => filterFn(val, source)));+}++function mergeEnumValues$1(first, second, config) {+ const enumValueMap = new Map();+ for (const firstValue of first) {+ enumValueMap.set(firstValue.name.value, firstValue);+ }+ for (const secondValue of second) {+ const enumValue = secondValue.name.value;+ if (enumValueMap.has(enumValue)) {+ const firstValue = enumValueMap.get(enumValue);+ firstValue.description = secondValue.description || firstValue.description;+ firstValue.directives = mergeDirectives$1(secondValue.directives, firstValue.directives);+ }+ else {+ enumValueMap.set(enumValue, secondValue);+ }+ }+ const result = [...enumValueMap.values()];+ if (config && config.sort) {+ result.sort(compareNodes);+ }+ return result;+}++function mergeEnum$1(e1, e2, config) {+ if (e2) {+ return {+ name: e1.name,+ description: e1['description'] || e2['description'],+ kind: (config && config.convertExtensions) || e1.kind === 'EnumTypeDefinition' || e2.kind === 'EnumTypeDefinition'+ ? 'EnumTypeDefinition'+ : 'EnumTypeExtension',+ loc: e1.loc,+ directives: mergeDirectives$1(e1.directives, e2.directives, config),+ values: mergeEnumValues$1(e1.values, e2.values, config),+ };+ }+ return config && config.convertExtensions+ ? {+ ...e1,+ kind: 'EnumTypeDefinition',+ }+ : e1;+}++function isStringTypes$1(types) {+ return typeof types === 'string';+}+function isSourceTypes$1(types) {+ return types instanceof Source;+}+function isGraphQLType$1(definition) {+ return definition.kind === 'ObjectTypeDefinition';+}+function isGraphQLTypeExtension$1(definition) {+ return definition.kind === 'ObjectTypeExtension';+}+function isGraphQLEnum$1(definition) {+ return definition.kind === 'EnumTypeDefinition';+}+function isGraphQLEnumExtension$1(definition) {+ return definition.kind === 'EnumTypeExtension';+}+function isGraphQLUnion$1(definition) {+ return definition.kind === 'UnionTypeDefinition';+}+function isGraphQLUnionExtension$1(definition) {+ return definition.kind === 'UnionTypeExtension';+}+function isGraphQLScalar$1(definition) {+ return definition.kind === 'ScalarTypeDefinition';+}+function isGraphQLScalarExtension$1(definition) {+ return definition.kind === 'ScalarTypeExtension';+}+function isGraphQLInputType$1(definition) {+ return definition.kind === 'InputObjectTypeDefinition';+}+function isGraphQLInputTypeExtension$1(definition) {+ return definition.kind === 'InputObjectTypeExtension';+}+function isGraphQLInterface$1(definition) {+ return definition.kind === 'InterfaceTypeDefinition';+}+function isGraphQLInterfaceExtension$1(definition) {+ return definition.kind === 'InterfaceTypeExtension';+}+function isGraphQLDirective$1(definition) {+ return definition.kind === 'DirectiveDefinition';+}+function extractType$1(type) {+ let visitedType = type;+ while (visitedType.kind === 'ListType' || visitedType.kind === 'NonNullType') {+ visitedType = visitedType.type;+ }+ return visitedType;+}+function isSchemaDefinition$1(node) {+ return node.kind === 'SchemaDefinition';+}+function isWrappingTypeNode$1(type) {+ return type.kind !== Kind.NAMED_TYPE;+}+function isListTypeNode$1(type) {+ return type.kind === Kind.LIST_TYPE;+}+function isNonNullTypeNode$1(type) {+ return type.kind === Kind.NON_NULL_TYPE;+}+function printTypeNode$1(type) {+ if (isListTypeNode$1(type)) {+ return `[${printTypeNode$1(type.type)}]`;+ }+ if (isNonNullTypeNode$1(type)) {+ return `${printTypeNode$1(type.type)}!`;+ }+ return type.name.value;+}++function fieldAlreadyExists$1(fieldsArr, otherField) {+ const result = fieldsArr.find(field => field.name.value === otherField.name.value);+ if (result) {+ const t1 = extractType$1(result.type);+ const t2 = extractType$1(otherField.type);+ if (t1.name.value !== t2.name.value) {+ throw new Error(`Field "${otherField.name.value}" already defined with a different type. Declared as "${t1.name.value}", but you tried to override with "${t2.name.value}"`);+ }+ }+ return !!result;+}+function mergeFields$1(type, f1, f2, config) {+ const result = [...f2];+ for (const field of f1) {+ if (fieldAlreadyExists$1(result, field)) {+ const existing = result.find((f) => f.name.value === field.name.value);+ if (config && config.throwOnConflict) {+ preventConflicts$1(type, existing, field, false);+ }+ else {+ preventConflicts$1(type, existing, field, true);+ }+ if (isNonNullTypeNode$1(field.type) && !isNonNullTypeNode$1(existing.type)) {+ existing.type = field.type;+ }+ existing.arguments = mergeArguments$2(field['arguments'] || [], existing.arguments || [], config);+ existing.directives = mergeDirectives$1(field.directives, existing.directives, config);+ existing.description = field.description || existing.description;+ }+ else {+ result.push(field);+ }+ }+ if (config && config.sort) {+ result.sort(compareNodes);+ }+ if (config && config.exclusions) {+ return result.filter(field => !config.exclusions.includes(`${type.name.value}.${field.name.value}`));+ }+ return result;+}+function preventConflicts$1(type, a, b, ignoreNullability = false) {+ const aType = printTypeNode$1(a.type);+ const bType = printTypeNode$1(b.type);+ if (isNotEqual(aType, bType)) {+ if (safeChangeForFieldType$1(a.type, b.type, ignoreNullability) === false) {+ throw new Error(`Field '${type.name.value}.${a.name.value}' changed type from '${aType}' to '${bType}'`);+ }+ }+}+function safeChangeForFieldType$1(oldType, newType, ignoreNullability = false) {+ // both are named+ if (!isWrappingTypeNode$1(oldType) && !isWrappingTypeNode$1(newType)) {+ return oldType.toString() === newType.toString();+ }+ // new is non-null+ if (isNonNullTypeNode$1(newType)) {+ const ofType = isNonNullTypeNode$1(oldType) ? oldType.type : oldType;+ return safeChangeForFieldType$1(ofType, newType.type);+ }+ // old is non-null+ if (isNonNullTypeNode$1(oldType)) {+ return safeChangeForFieldType$1(newType, oldType, ignoreNullability);+ }+ // old is list+ if (isListTypeNode$1(oldType)) {+ return ((isListTypeNode$1(newType) && safeChangeForFieldType$1(oldType.type, newType.type)) ||+ (isNonNullTypeNode$1(newType) && safeChangeForFieldType$1(oldType, newType['type'])));+ }+ return false;+}++function mergeInputType$1(node, existingNode, config) {+ if (existingNode) {+ try {+ return {+ name: node.name,+ description: node['description'] || existingNode['description'],+ kind: (config && config.convertExtensions) ||+ node.kind === 'InputObjectTypeDefinition' ||+ existingNode.kind === 'InputObjectTypeDefinition'+ ? 'InputObjectTypeDefinition'+ : 'InputObjectTypeExtension',+ loc: node.loc,+ fields: mergeFields$1(node, node.fields, existingNode.fields, config),+ directives: mergeDirectives$1(node.directives, existingNode.directives, config),+ };+ }+ catch (e) {+ throw new Error(`Unable to merge GraphQL input type "${node.name.value}": ${e.message}`);+ }+ }+ return config && config.convertExtensions+ ? {+ ...node,+ kind: 'InputObjectTypeDefinition',+ }+ : node;+}++function mergeInterface$1(node, existingNode, config) {+ if (existingNode) {+ try {+ return {+ name: node.name,+ description: node['description'] || existingNode['description'],+ kind: (config && config.convertExtensions) ||+ node.kind === 'InterfaceTypeDefinition' ||+ existingNode.kind === 'InterfaceTypeDefinition'+ ? 'InterfaceTypeDefinition'+ : 'InterfaceTypeExtension',+ loc: node.loc,+ fields: mergeFields$1(node, node.fields, existingNode.fields, config),+ directives: mergeDirectives$1(node.directives, existingNode.directives, config),+ };+ }+ catch (e) {+ throw new Error(`Unable to merge GraphQL interface "${node.name.value}": ${e.message}`);+ }+ }+ return config && config.convertExtensions+ ? {+ ...node,+ kind: 'InterfaceTypeDefinition',+ }+ : node;+}++function alreadyExists$1(arr, other) {+ return !!arr.find(i => i.name.value === other.name.value);+}+function mergeNamedTypeArray$1(first, second, config) {+ const result = [...second, ...first.filter(d => !alreadyExists$1(second, d))];+ if (config && config.sort) {+ result.sort(compareNodes);+ }+ return result;+}++function mergeType$1(node, existingNode, config) {+ if (existingNode) {+ try {+ return {+ name: node.name,+ description: node['description'] || existingNode['description'],+ kind: (config && config.convertExtensions) ||+ node.kind === 'ObjectTypeDefinition' ||+ existingNode.kind === 'ObjectTypeDefinition'+ ? 'ObjectTypeDefinition'+ : 'ObjectTypeExtension',+ loc: node.loc,+ fields: mergeFields$1(node, node.fields, existingNode.fields, config),+ directives: mergeDirectives$1(node.directives, existingNode.directives, config),+ interfaces: mergeNamedTypeArray$1(node.interfaces, existingNode.interfaces, config),+ };+ }+ catch (e) {+ throw new Error(`Unable to merge GraphQL type "${node.name.value}": ${e.message}`);+ }+ }+ return config && config.convertExtensions+ ? {+ ...node,+ kind: 'ObjectTypeDefinition',+ }+ : node;+}++function mergeUnion$1(first, second, config) {+ if (second) {+ return {+ name: first.name,+ description: first['description'] || second['description'],+ directives: mergeDirectives$1(first.directives, second.directives, config),+ kind: (config && config.convertExtensions) ||+ first.kind === 'UnionTypeDefinition' ||+ second.kind === 'UnionTypeDefinition'+ ? 'UnionTypeDefinition'+ : 'UnionTypeExtension',+ loc: first.loc,+ types: mergeNamedTypeArray$1(first.types, second.types, config),+ };+ }+ return config && config.convertExtensions+ ? {+ ...first,+ kind: 'UnionTypeDefinition',+ }+ : first;+}++function mergeGraphQLNodes$1(nodes, config) {+ return nodes.reduce((prev, nodeDefinition) => {+ const node = nodeDefinition;+ if (node && node.name && node.name.value) {+ const name = node.name.value;+ if (config && config.commentDescriptions) {+ collectComment$1(node);+ }+ if (config &&+ config.exclusions &&+ (config.exclusions.includes(name + '.*') || config.exclusions.includes(name))) {+ delete prev[name];+ }+ else if (isGraphQLType$1(nodeDefinition) || isGraphQLTypeExtension$1(nodeDefinition)) {+ prev[name] = mergeType$1(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLEnum$1(nodeDefinition) || isGraphQLEnumExtension$1(nodeDefinition)) {+ prev[name] = mergeEnum$1(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLUnion$1(nodeDefinition) || isGraphQLUnionExtension$1(nodeDefinition)) {+ prev[name] = mergeUnion$1(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLScalar$1(nodeDefinition) || isGraphQLScalarExtension$1(nodeDefinition)) {+ prev[name] = nodeDefinition;+ }+ else if (isGraphQLInputType$1(nodeDefinition) || isGraphQLInputTypeExtension$1(nodeDefinition)) {+ prev[name] = mergeInputType$1(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLInterface$1(nodeDefinition) || isGraphQLInterfaceExtension$1(nodeDefinition)) {+ prev[name] = mergeInterface$1(nodeDefinition, prev[name], config);+ }+ else if (isGraphQLDirective$1(nodeDefinition)) {+ prev[name] = mergeDirective$1(nodeDefinition, prev[name]);+ }+ }+ return prev;+ }, {});+}++function mergeTypeDefs$1(types, config) {+ resetComments$1();+ const doc = {+ kind: Kind.DOCUMENT,+ definitions: mergeGraphQLTypes$1(types, {+ useSchemaDefinition: true,+ forceSchemaDefinition: false,+ throwOnConflict: false,+ commentDescriptions: false,+ ...config,+ }),+ };+ let result;+ if (config && config.commentDescriptions) {+ result = printWithComments$1(doc);+ }+ else {+ result = doc;+ }+ resetComments$1();+ return result;+}+function mergeGraphQLTypes$1(types, config) {+ resetComments$1();+ const allNodes = types+ .map(type => {+ if (Array.isArray(type)) {+ type = mergeTypeDefs$1(type);+ }+ if (isSchema(type)) {+ return parse(printSchemaWithDirectives(type));+ }+ else if (isStringTypes$1(type) || isSourceTypes$1(type)) {+ return parse(type);+ }+ return type;+ })+ .map(ast => ast.definitions)+ .reduce((defs, newDef = []) => [...defs, ...newDef], []);+ // XXX: right now we don't handle multiple schema definitions+ let schemaDef = allNodes.filter(isSchemaDefinition$1).reduce((def, node) => {+ node.operationTypes+ .filter(op => op.type.name.value)+ .forEach(op => {+ def[op.operation] = op.type.name.value;+ });+ return def;+ }, {+ query: null,+ mutation: null,+ subscription: null,+ });+ const mergedNodes = mergeGraphQLNodes$1(allNodes, config);+ const allTypes = Object.keys(mergedNodes);+ if (config && config.sort) {+ allTypes.sort(typeof config.sort === 'function' ? config.sort : undefined);+ }+ if (config && config.useSchemaDefinition) {+ const queryType = schemaDef.query ? schemaDef.query : allTypes.find(t => t === 'Query');+ const mutationType = schemaDef.mutation ? schemaDef.mutation : allTypes.find(t => t === 'Mutation');+ const subscriptionType = schemaDef.subscription ? schemaDef.subscription : allTypes.find(t => t === 'Subscription');+ schemaDef = {+ query: queryType,+ mutation: mutationType,+ subscription: subscriptionType,+ };+ }+ const schemaDefinition = createSchemaDefinition(schemaDef, {+ force: config.forceSchemaDefinition,+ });+ if (!schemaDefinition) {+ return Object.values(mergedNodes);+ }+ return [...Object.values(mergedNodes), parse(schemaDefinition).definitions[0]];+}++function travelSchemaPossibleExtensions(schema, hooks) {+ hooks.onSchema(schema);+ const typesMap = schema.getTypeMap();+ for (const [, type] of Object.entries(typesMap)) {+ const isPredefinedScalar = isScalarType(type) && isSpecifiedScalarType(type);+ const isIntrospection = isIntrospectionType(type);+ if (isPredefinedScalar || isIntrospection) {+ continue;+ }+ if (isObjectType(type)) {+ hooks.onObjectType(type);+ const fields = type.getFields();+ for (const [, field] of Object.entries(fields)) {+ hooks.onObjectField(type, field);+ const args = field.args || [];+ for (const arg of args) {+ hooks.onObjectFieldArg(type, field, arg);+ }+ }+ }+ else if (isInterfaceType(type)) {+ hooks.onInterface(type);+ const fields = type.getFields();+ for (const [, field] of Object.entries(fields)) {+ hooks.onInterfaceField(type, field);+ const args = field.args || [];+ for (const arg of args) {+ hooks.onInterfaceFieldArg(type, field, arg);+ }+ }+ }+ else if (isInputObjectType(type)) {+ hooks.onInputType(type);+ const fields = type.getFields();+ for (const [, field] of Object.entries(fields)) {+ hooks.onInputFieldType(type, field);+ }+ }+ else if (isUnionType(type)) {+ hooks.onUnion(type);+ }+ else if (isScalarType(type)) {+ hooks.onScalar(type);+ }+ else if (isEnumType(type)) {+ hooks.onEnum(type);+ for (const value of type.getValues()) {+ hooks.onEnumValue(type, value);+ }+ }+ }+}+function mergeExtensions(extensions) {+ return extensions.reduce((result, extensionObj) => [result, extensionObj].reduce(mergeDeep, {}), {});+}+function applyExtensionObject(obj, extensions) {+ if (!obj) {+ return;+ }+ obj.extensions = [obj.extensions || {}, extensions || {}].reduce(mergeDeep, {});+}+function applyExtensions(schema, extensions) {+ applyExtensionObject(schema, extensions.schemaExtensions);+ for (const [typeName, data] of Object.entries(extensions.types || {})) {+ const type = schema.getType(typeName);+ if (type) {+ applyExtensionObject(type, data.extensions);+ if (data.type === 'object' || data.type === 'interface') {+ for (const [fieldName, fieldData] of Object.entries(data.fields)) {+ const field = type.getFields()[fieldName];+ if (field) {+ applyExtensionObject(field, fieldData.extensions);+ for (const [arg, argData] of Object.entries(fieldData.arguments)) {+ applyExtensionObject(field.args.find(a => a.name === arg), argData);+ }+ }+ }+ }+ else if (data.type === 'input') {+ for (const [fieldName, fieldData] of Object.entries(data.fields)) {+ const field = type.getFields()[fieldName];+ applyExtensionObject(field, fieldData.extensions);+ }+ }+ else if (data.type === 'enum') {+ for (const [valueName, valueData] of Object.entries(data.values)) {+ const value = type.getValue(valueName);+ applyExtensionObject(value, valueData);+ }+ }+ }+ }+ return schema;+}+function extractExtensionsFromSchema(schema) {+ const result = {+ schemaExtensions: {},+ types: {},+ };+ travelSchemaPossibleExtensions(schema, {+ onSchema: schema => (result.schemaExtensions = schema.extensions || {}),+ onObjectType: type => (result.types[type.name] = { fields: {}, type: 'object', extensions: type.extensions || {} }),+ onObjectField: (type, field) => (result.types[type.name].fields[field.name] = {+ arguments: {},+ extensions: field.extensions || {},+ }),+ onObjectFieldArg: (type, field, arg) => (result.types[type.name].fields[field.name].arguments[arg.name] = arg.extensions || {}),+ onInterface: type => (result.types[type.name] = { fields: {}, type: 'interface', extensions: type.extensions || {} }),+ onInterfaceField: (type, field) => (result.types[type.name].fields[field.name] = {+ arguments: {},+ extensions: field.extensions || {},+ }),+ onInterfaceFieldArg: (type, field, arg) => (result.types[type.name].fields[field.name].arguments[arg.name] =+ arg.extensions || {}),+ onEnum: type => (result.types[type.name] = { values: {}, type: 'enum', extensions: type.extensions || {} }),+ onEnumValue: (type, value) => (result.types[type.name].values[value.name] = value.extensions || {}),+ onScalar: type => (result.types[type.name] = { type: 'scalar', extensions: type.extensions || {} }),+ onUnion: type => (result.types[type.name] = { type: 'union', extensions: type.extensions || {} }),+ onInputType: type => (result.types[type.name] = { fields: {}, type: 'input', extensions: type.extensions || {} }),+ onInputFieldType: (type, field) => (result.types[type.name].fields[field.name] = { extensions: field.extensions || {} }),+ });+ return result;+}++const defaultResolverValidationOptions = {+ requireResolversForArgs: false,+ requireResolversForNonScalar: false,+ requireResolversForAllFields: false,+ requireResolversForResolveType: false,+ allowResolversNotInSchema: true,+};+/**+ * Synchronously merges multiple schemas, typeDefinitions and/or resolvers into a single schema.+ * @param config Configuration object+ */+async function mergeSchemasAsync(config) {+ const [typeDefs, resolvers, extensions] = await Promise.all([+ mergeTypes(config),+ Promise.all(config.schemas.map(async (schema) => getResolversFromSchema(schema))).then(extractedResolvers => mergeResolvers([...extractedResolvers, ...ensureResolvers(config)], config)),+ Promise.all(config.schemas.map(async (schema) => extractExtensionsFromSchema(schema))).then(extractedExtensions => mergeExtensions(extractedExtensions)),+ ]);+ return makeSchema({ resolvers, typeDefs, extensions }, config);+}+function mergeTypes({ schemas, typeDefs, ...config }) {+ return mergeTypeDefs$1([...schemas, ...(typeDefs ? asArray(typeDefs) : [])], config);+}+function ensureResolvers(config) {+ return config.resolvers ? asArray(config.resolvers) : [];+}+function makeSchema({ resolvers, typeDefs, extensions, }, config) {+ let schema = typeof typeDefs === 'string' ? buildSchema(typeDefs, config) : buildASTSchema(typeDefs, config);+ // add resolvers+ if (resolvers) {+ schema = addResolversToSchema({+ schema,+ resolvers,+ resolverValidationOptions: {+ ...defaultResolverValidationOptions,+ ...(config.resolverValidationOptions || {}),+ },+ });+ }+ // use logger+ if (config.logger) {+ schema = addErrorLoggingToSchema(schema, config.logger);+ }+ // use schema directives+ if (config.schemaDirectives) {+ SchemaDirectiveVisitor.visitSchemaDirectives(schema, config.schemaDirectives);+ }+ // extensions+ applyExtensions(schema, extensions);+ return schema;+}++function normalizePointers(unnormalizedPointerOrPointers) {+ return asArray(unnormalizedPointerOrPointers).reduce((normalizedPointers, unnormalizedPointer) => {+ if (typeof unnormalizedPointer === 'string') {+ normalizedPointers[unnormalizedPointer] = {};+ }+ else if (typeof unnormalizedPointer === 'object') {+ Object.assign(normalizedPointers, unnormalizedPointer);+ }+ else {+ throw new Error(`Invalid pointer ${unnormalizedPointer}`);+ }+ return normalizedPointers;+ }, {});+}++function applyDefaultOptions(options) {+ options.cache = options.cache || {};+ options.cwd = options.cwd || process$1.cwd();+ options.sort = 'sort' in options ? options.sort : true;+}++async function loadFile(pointer, options) {+ const cached = useCache({ pointer, options });+ if (cached) {+ return cached;+ }+ for await (const loader of options.loaders) {+ try {+ const canLoad = await loader.canLoad(pointer, options);+ if (canLoad) {+ return await loader.load(pointer, options);+ }+ }+ catch (error) {+ debugLog(`Failed to find any GraphQL type definitions in: ${pointer} - ${error.message}`);+ throw error;+ }+ }+ return undefined;+}+function useCache({ pointer, options }) {+ if (options['cache']) {+ return options['cache'][pointer];+ }+}++/**+ * Converts a string to 32bit integer+ */+function stringToHash(str) {+ let hash = 0;+ if (str.length === 0) {+ return hash;+ }+ let char;+ for (let i = 0; i < str.length; i++) {+ char = str.charCodeAt(i);+ // tslint:disable-next-line: no-bitwise+ hash = (hash << 5) - hash + char;+ // tslint:disable-next-line: no-bitwise+ hash = hash & hash;+ }+ return hash;+}+function useStack(...fns) {+ return (input) => {+ function createNext(i) {+ if (i >= fns.length) {+ return () => { };+ }+ return function next() {+ fns[i](input, createNext(i + 1));+ };+ }+ fns[0](input, createNext(1));+ };+}+function useLimit(concurrency) {+ return pLimit_1(concurrency);+}++function getCustomLoaderByPath(path, cwd) {+ try {+ const requiredModule = importFrom(cwd, path);+ if (requiredModule) {+ if (requiredModule.default && typeof requiredModule.default === 'function') {+ return requiredModule.default;+ }+ if (typeof requiredModule === 'function') {+ return requiredModule;+ }+ }+ }+ catch (e) { }+ return null;+}+async function useCustomLoader(loaderPointer, cwd) {+ let loader;+ if (typeof loaderPointer === 'string') {+ loader = await getCustomLoaderByPath(loaderPointer, cwd);+ }+ else if (typeof loaderPointer === 'function') {+ loader = loaderPointer;+ }+ if (typeof loader !== 'function') {+ throw new Error(`Failed to load custom loader: ${loaderPointer}`);+ }+ return loader;+}++function useQueue(options) {+ const queue = [];+ const limit = (options === null || options === void 0 ? void 0 : options.concurrency) ? pLimit_1(options.concurrency) : async (fn) => fn();+ return {+ add(fn) {+ queue.push(() => limit(fn));+ },+ runAll() {+ return Promise.all(queue.map(fn => fn()));+ },+ };+}++const CONCURRENCY_LIMIT = 50;+async function collectSources({ pointerOptionMap, options, }) {+ var _a;+ const sources = [];+ const globs = [];+ const globOptions = {};+ const queue = useQueue({ concurrency: CONCURRENCY_LIMIT });+ const { addSource, addGlob, collect } = createHelpers({+ sources,+ globs,+ options,+ globOptions,+ stack: [collectDocumentString, collectGlob, collectCustomLoader, collectFallback],+ });+ for (const pointer in pointerOptionMap) {+ const pointerOptions = {+ ...((_a = pointerOptionMap[pointer]) !== null && _a !== void 0 ? _a : {}),+ unixify,+ };+ collect({+ pointer,+ pointerOptions,+ pointerOptionMap,+ options,+ addSource,+ addGlob,+ queue: queue.add,+ });+ }+ if (globs.length) {+ includeIgnored({+ options,+ globs,+ });+ const paths = await globby$1(globs, createGlobbyOptions(options));+ collectSourcesFromGlobals({+ filepaths: paths,+ options,+ globOptions,+ pointerOptionMap,+ addSource,+ queue: queue.add,+ });+ }+ await queue.runAll();+ return sources;+}+//+function createHelpers({ sources, globs, options, globOptions, stack, }) {+ const addSource = ({ pointer, source, noCache, }) => {+ sources.push(source);+ if (!noCache) {+ options.cache[pointer] = source;+ }+ };+ const collect = useStack(...stack);+ const addGlob = ({ pointerOptions, pointer }) => {+ globs.push(pointer);+ Object.assign(globOptions, pointerOptions);+ };+ return {+ addSource,+ collect,+ addGlob,+ };+}+function includeIgnored({ options, globs }) {+ if (options.ignore) {+ const ignoreList = asArray(options.ignore)+ .map(g => `!(${g})`)+ .map(unixify);+ if (ignoreList.length > 0) {+ globs.push(...ignoreList);+ }+ }+}+function createGlobbyOptions(options) {+ return { absolute: true, ...options, ignore: [] };+}+function collectSourcesFromGlobals({ filepaths, options, globOptions, pointerOptionMap, addSource, queue, }) {+ const collectFromGlobs = useStack(collectCustomLoader, collectFallback);+ for (let i = 0; i < filepaths.length; i++) {+ const pointer = filepaths[i];+ collectFromGlobs({+ pointer,+ pointerOptions: globOptions,+ pointerOptionMap,+ options,+ addSource,+ addGlob: () => {+ throw new Error(`I don't accept any new globs!`);+ },+ queue,+ });+ }+}+function addResultOfCustomLoader({ pointer, result, addSource, }) {+ if (isSchema(result)) {+ addSource({+ source: {+ location: pointer,+ schema: result,+ document: parse(printSchemaWithDirectives(result)),+ },+ pointer,+ noCache: true,+ });+ }+ else if (result.kind && result.kind === Kind.DOCUMENT) {+ addSource({+ source: {+ document: result,+ location: pointer,+ },+ pointer,+ });+ }+ else if (result.document) {+ addSource({+ source: {+ location: pointer,+ ...result,+ },+ pointer,+ });+ }+}+function collectDocumentString({ pointer, pointerOptions, options, addSource, queue }, next) {+ if (isDocumentString(pointer)) {+ return queue(() => {+ const source = parseGraphQLSDL(`${stringToHash(pointer)}.graphql`, pointer, {+ ...options,+ ...pointerOptions,+ });+ addSource({+ source,+ pointer,+ });+ });+ }+ next();+}+function collectGlob({ pointer, pointerOptions, addGlob }, next) {+ if (isGlob(pointerOptions.unixify(pointer))) {+ return addGlob({+ pointer: pointerOptions.unixify(pointer),+ pointerOptions,+ });+ }+ next();+}+function collectCustomLoader({ pointer, pointerOptions, queue, addSource, options, pointerOptionMap }, next) {+ if (pointerOptions.loader) {+ return queue(async () => {+ const loader = await useCustomLoader(pointerOptions.loader, options.cwd);+ const result = await loader(pointer, { ...options, ...pointerOptions }, pointerOptionMap);+ if (!result) {+ return;+ }+ addResultOfCustomLoader({ pointer, result, addSource });+ });+ }+ next();+}+function collectFallback({ queue, pointer, options, pointerOptions, addSource }) {+ return queue(async () => {+ const source = await loadFile(pointer, {+ ...options,+ ...pointerOptions,+ });+ if (source) {+ addSource({ source, pointer });+ }+ });+}++/**+ * @internal+ */+const filterKind = (content, filterKinds) => {+ if (content && content.definitions && content.definitions.length && filterKinds && filterKinds.length > 0) {+ const invalidDefinitions = [];+ const validDefinitions = [];+ for (const definitionNode of content.definitions) {+ if (filterKinds.includes(definitionNode.kind)) {+ invalidDefinitions.push(definitionNode);+ }+ else {+ validDefinitions.push(definitionNode);+ }+ }+ if (invalidDefinitions.length > 0) {+ invalidDefinitions.forEach(d => {+ debugLog(`Filtered document of kind ${d.kind} due to filter policy (${filterKinds.join(', ')})`);+ });+ }+ return {+ kind: Kind.DOCUMENT,+ definitions: validDefinitions,+ };+ }+ return content;+};++function parseSource({ partialSource, options, globOptions, pointerOptionMap, addValidSource }) {+ if (partialSource) {+ const input = prepareInput({+ source: partialSource,+ options,+ globOptions,+ pointerOptionMap,+ });+ parseSchema(input);+ parseRawSDL(input);+ if (input.source.document) {+ useKindsFilter(input);+ useComments(input);+ collectValidSources(input, addValidSource);+ }+ }+}+//+function prepareInput({ source, options, globOptions, pointerOptionMap, }) {+ const specificOptions = {+ ...options,+ ...(source.location in pointerOptionMap ? globOptions : pointerOptionMap[source.location]),+ };+ return { source: { ...source }, options: specificOptions };+}+function parseSchema(input) {+ if (input.source.schema) {+ input.source.schema = fixSchemaAst(input.source.schema, input.options);+ input.source.rawSDL = printSchemaWithDirectives(input.source.schema, input.options);+ }+}+function parseRawSDL(input) {+ if (input.source.rawSDL) {+ input.source.document = parseGraphQLSDL(input.source.location, input.source.rawSDL, input.options).document;+ }+}+function useKindsFilter(input) {+ if (input.options.filterKinds) {+ input.source.document = filterKind(input.source.document, input.options.filterKinds);+ }+}+function useComments(input) {+ if (!input.source.rawSDL) {+ input.source.rawSDL = printWithComments$1(input.source.document);+ resetComments$1();+ }+}+function collectValidSources(input, addValidSource) {+ if (input.source.document.definitions && input.source.document.definitions.length > 0) {+ addValidSource(input.source);+ }+}++const CONCURRENCY_LIMIT$1 = 100;+/**+ * Asynchronously loads any GraphQL documents (i.e. executable documents like+ * operations and fragments as well as type system definitions) from the+ * provided pointers.+ * @param pointerOrPointers Pointers to the sources to load the documents from+ * @param options Additional options+ */+async function loadTypedefs(pointerOrPointers, options) {+ const pointerOptionMap = normalizePointers(pointerOrPointers);+ const globOptions = {};+ applyDefaultOptions(options);+ const sources = await collectSources({+ pointerOptionMap,+ options,+ });+ const validSources = [];+ // If we have few k of files it may be an issue+ const limit = useLimit(CONCURRENCY_LIMIT$1);+ await Promise.all(sources.map(partialSource => limit(() => parseSource({+ partialSource,+ options,+ globOptions,+ pointerOptionMap,+ addValidSource(source) {+ validSources.push(source);+ },+ }))));+ return prepareResult({ options, pointerOptionMap, validSources });+}+//+function prepareResult({ options, pointerOptionMap, validSources, }) {+ const pointerList = Object.keys(pointerOptionMap);+ if (pointerList.length > 0 && validSources.length === 0) {+ throw new Error(`+ Unable to find any GraphQL type definitions for the following pointers:+ ${pointerList.map(p => `+ - ${p}+ `)}`);+ }+ return options.sort+ ? validSources.sort((left, right) => compareStrings(left.location, right.location))+ : validSources;+}++/**+ * Kinds of AST nodes that are included in executable documents+ */+const OPERATION_KINDS = [Kind.OPERATION_DEFINITION, Kind.FRAGMENT_DEFINITION];+/**+ * Kinds of AST nodes that are included in type system definition documents+ */+const NON_OPERATION_KINDS = Object.keys(Kind)+ .reduce((prev, v) => [...prev, Kind[v]], [])+ .filter(v => !OPERATION_KINDS.includes(v));+/**+ * Asynchronously loads executable documents (i.e. operations and fragments) from+ * the provided pointers. The pointers may be individual files or a glob pattern.+ * The files themselves may be `.graphql` files or `.js` and `.ts` (in which+ * case they will be parsed using graphql-tag-pluck).+ * @param pointerOrPointers Pointers to the files to load the documents from+ * @param options Additional options+ */+function loadDocuments(pointerOrPointers, options) {+ return loadTypedefs(pointerOrPointers, { noRequire: true, filterKinds: NON_OPERATION_KINDS, ...options });+}++/**+ * Asynchronously loads a schema from the provided pointers.+ * @param schemaPointers Pointers to the sources to load the schema from+ * @param options Additional options+ */+async function loadSchema(schemaPointers, options) {+ const sources = await loadTypedefs(schemaPointers, {+ filterKinds: OPERATION_KINDS,+ ...options,+ });+ const { schemas, typeDefs } = collectSchemasAndTypeDefs(sources);+ const mergeSchemasOptions = {+ schemas,+ typeDefs,+ ...options,+ };+ const schema = await mergeSchemasAsync(mergeSchemasOptions);+ if (options === null || options === void 0 ? void 0 : options.includeSources) {+ includeSources(schema, sources);+ }+ return schema;+}+function includeSources(schema, sources) {+ schema.extensions = {+ ...schema.extensions,+ sources: sources+ .filter(source => source.rawSDL || source.document)+ .map(source => new Source(source.rawSDL || print(source.document), source.location)),+ };+}+function collectSchemasAndTypeDefs(sources) {+ const schemas = [];+ const typeDefs = [];+ sources.forEach(source => {+ if (source.schema) {+ schemas.push(source.schema);+ }+ else {+ typeDefs.push(source.document);+ }+ });+ return {+ schemas,+ typeDefs,+ };+}++var validUrl = createCommonjsModule(function (module) {+(function(module) {++ module.exports.is_uri = is_iri;+ module.exports.is_http_uri = is_http_iri;+ module.exports.is_https_uri = is_https_iri;+ module.exports.is_web_uri = is_web_iri;+ // Create aliases+ module.exports.isUri = is_iri;+ module.exports.isHttpUri = is_http_iri;+ module.exports.isHttpsUri = is_https_iri;+ module.exports.isWebUri = is_web_iri;+++ // private function+ // internal URI spitter method - direct from RFC 3986+ var splitUri = function(uri) {+ var splitted = uri.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);+ return splitted;+ };++ function is_iri(value) {+ if (!value) {+ return;+ }++ // check for illegal characters+ if (/[^a-z0-9\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=\.\-\_\~\%]/i.test(value)) return;++ // check for hex escapes that aren't complete+ if (/%[^0-9a-f]/i.test(value)) return;+ if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return;++ var splitted = [];+ var scheme = '';+ var authority = '';+ var path = '';+ var query = '';+ var fragment = '';+ var out = '';++ // from RFC 3986+ splitted = splitUri(value);+ scheme = splitted[1]; + authority = splitted[2];+ path = splitted[3];+ query = splitted[4];+ fragment = splitted[5];++ // scheme and path are required, though the path can be empty+ if (!(scheme && scheme.length && path.length >= 0)) return;++ // if authority is present, the path must be empty or begin with a /+ if (authority && authority.length) {+ if (!(path.length === 0 || /^\//.test(path))) return;+ } else {+ // if authority is not present, the path must not start with //+ if (/^\/\//.test(path)) return;+ }++ // scheme must begin with a letter, then consist of letters, digits, +, ., or -+ if (!/^[a-z][a-z0-9\+\-\.]*$/.test(scheme.toLowerCase())) return;++ // re-assemble the URL per section 5.3 in RFC 3986+ out += scheme + ':';+ if (authority && authority.length) {+ out += '//' + authority;+ }++ out += path;++ if (query && query.length) {+ out += '?' + query;+ }++ if (fragment && fragment.length) {+ out += '#' + fragment;+ }++ return out;+ }++ function is_http_iri(value, allowHttps) {+ if (!is_iri(value)) {+ return;+ }++ var splitted = [];+ var scheme = '';+ var authority = '';+ var path = '';+ var port = '';+ var query = '';+ var fragment = '';+ var out = '';++ // from RFC 3986+ splitted = splitUri(value);+ scheme = splitted[1]; + authority = splitted[2];+ path = splitted[3];+ query = splitted[4];+ fragment = splitted[5];++ if (!scheme) return;++ if(allowHttps) {+ if (scheme.toLowerCase() != 'https') return;+ } else {+ if (scheme.toLowerCase() != 'http') return;+ }++ // fully-qualified URIs must have an authority section that is+ // a valid host+ if (!authority) {+ return;+ }++ // enable port component+ if (/:(\d+)$/.test(authority)) {+ port = authority.match(/:(\d+)$/)[0];+ authority = authority.replace(/:\d+$/, '');+ }++ out += scheme + ':';+ out += '//' + authority;+ + if (port) {+ out += port;+ }+ + out += path;+ + if(query && query.length){+ out += '?' + query;+ }++ if(fragment && fragment.length){+ out += '#' + fragment;+ }+ + return out;+ }++ function is_https_iri(value) {+ return is_http_iri(value, true);+ }++ function is_web_iri(value) {+ return (is_http_iri(value) || is_https_iri(value));+ }++})(module);+});++// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js++// fix for "Readable" isn't a named export issue+const Readable = Stream__default['default'].Readable;++const BUFFER = Symbol('buffer');+const TYPE = Symbol('type');++class Blob {+ constructor() {+ this[TYPE] = '';++ const blobParts = arguments[0];+ const options = arguments[1];++ const buffers = [];+ let size = 0;++ if (blobParts) {+ const a = blobParts;+ const length = Number(a.length);+ for (let i = 0; i < length; i++) {+ const element = a[i];+ let buffer;+ if (element instanceof Buffer) {+ buffer = element;+ } else if (ArrayBuffer.isView(element)) {+ buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);+ } else if (element instanceof ArrayBuffer) {+ buffer = Buffer.from(element);+ } else if (element instanceof Blob) {+ buffer = element[BUFFER];+ } else {+ buffer = Buffer.from(typeof element === 'string' ? element : String(element));+ }+ size += buffer.length;+ buffers.push(buffer);+ }+ }++ this[BUFFER] = Buffer.concat(buffers);++ let type = options && options.type !== undefined && String(options.type).toLowerCase();+ if (type && !/[^\u0020-\u007E]/.test(type)) {+ this[TYPE] = type;+ }+ }+ get size() {+ return this[BUFFER].length;+ }+ get type() {+ return this[TYPE];+ }+ text() {+ return Promise.resolve(this[BUFFER].toString());+ }+ arrayBuffer() {+ const buf = this[BUFFER];+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);+ return Promise.resolve(ab);+ }+ stream() {+ const readable = new Readable();+ readable._read = function () {};+ readable.push(this[BUFFER]);+ readable.push(null);+ return readable;+ }+ toString() {+ return '[object Blob]';+ }+ slice() {+ const size = this.size;++ const start = arguments[0];+ const end = arguments[1];+ let relativeStart, relativeEnd;+ if (start === undefined) {+ relativeStart = 0;+ } else if (start < 0) {+ relativeStart = Math.max(size + start, 0);+ } else {+ relativeStart = Math.min(start, size);+ }+ if (end === undefined) {+ relativeEnd = size;+ } else if (end < 0) {+ relativeEnd = Math.max(size + end, 0);+ } else {+ relativeEnd = Math.min(end, size);+ }+ const span = Math.max(relativeEnd - relativeStart, 0);++ const buffer = this[BUFFER];+ const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);+ const blob = new Blob([], { type: arguments[2] });+ blob[BUFFER] = slicedBuffer;+ return blob;+ }+}++Object.defineProperties(Blob.prototype, {+ size: { enumerable: true },+ type: { enumerable: true },+ slice: { enumerable: true }+});++Object.defineProperty(Blob.prototype, Symbol.toStringTag, {+ value: 'Blob',+ writable: false,+ enumerable: false,+ configurable: true+});++/**+ * fetch-error.js+ *+ * FetchError interface for operational errors+ */++/**+ * Create FetchError instance+ *+ * @param String message Error message for human+ * @param String type Error type for machine+ * @param String systemError For Node.js system error+ * @return FetchError+ */+function FetchError(message, type, systemError) {+ Error.call(this, message);++ this.message = message;+ this.type = type;++ // when err.type is `system`, err.code contains system error code+ if (systemError) {+ this.code = this.errno = systemError.code;+ }++ // hide custom error implementation details from end-users+ Error.captureStackTrace(this, this.constructor);+}++FetchError.prototype = Object.create(Error.prototype);+FetchError.prototype.constructor = FetchError;+FetchError.prototype.name = 'FetchError';++let convert;+try {+ convert = require('encoding').convert;+} catch (e) {}++const INTERNALS = Symbol('Body internals');++// fix an issue where "PassThrough" isn't a named export for node <10+const PassThrough$1 = Stream__default['default'].PassThrough;++/**+ * Body mixin+ *+ * Ref: https://fetch.spec.whatwg.org/#body+ *+ * @param Stream body Readable stream+ * @param Object opts Response options+ * @return Void+ */+function Body(body) {+ var _this = this;++ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},+ _ref$size = _ref.size;++ let size = _ref$size === undefined ? 0 : _ref$size;+ var _ref$timeout = _ref.timeout;+ let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;++ if (body == null) {+ // body is undefined or null+ body = null;+ } else if (isURLSearchParams(body)) {+ // body is a URLSearchParams+ body = Buffer.from(body.toString());+ } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {+ // body is ArrayBuffer+ body = Buffer.from(body);+ } else if (ArrayBuffer.isView(body)) {+ // body is ArrayBufferView+ body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);+ } else if (body instanceof Stream__default['default']) ; else {+ // none of the above+ // coerce to string then buffer+ body = Buffer.from(String(body));+ }+ this[INTERNALS] = {+ body,+ disturbed: false,+ error: null+ };+ this.size = size;+ this.timeout = timeout;++ if (body instanceof Stream__default['default']) {+ body.on('error', function (err) {+ const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);+ _this[INTERNALS].error = error;+ });+ }+}++Body.prototype = {+ get body() {+ return this[INTERNALS].body;+ },++ get bodyUsed() {+ return this[INTERNALS].disturbed;+ },++ /**+ * Decode response as ArrayBuffer+ *+ * @return Promise+ */+ arrayBuffer() {+ return consumeBody.call(this).then(function (buf) {+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);+ });+ },++ /**+ * Return raw response as Blob+ *+ * @return Promise+ */+ blob() {+ let ct = this.headers && this.headers.get('content-type') || '';+ return consumeBody.call(this).then(function (buf) {+ return Object.assign(+ // Prevent copying+ new Blob([], {+ type: ct.toLowerCase()+ }), {+ [BUFFER]: buf+ });+ });+ },++ /**+ * Decode response as json+ *+ * @return Promise+ */+ json() {+ var _this2 = this;++ return consumeBody.call(this).then(function (buffer) {+ try {+ return JSON.parse(buffer.toString());+ } catch (err) {+ return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));+ }+ });+ },++ /**+ * Decode response as text+ *+ * @return Promise+ */+ text() {+ return consumeBody.call(this).then(function (buffer) {+ return buffer.toString();+ });+ },++ /**+ * Decode response as buffer (non-spec api)+ *+ * @return Promise+ */+ buffer() {+ return consumeBody.call(this);+ },++ /**+ * Decode response as text, while automatically detecting the encoding and+ * trying to decode to UTF-8 (non-spec api)+ *+ * @return Promise+ */+ textConverted() {+ var _this3 = this;++ return consumeBody.call(this).then(function (buffer) {+ return convertBody(buffer, _this3.headers);+ });+ }+};++// In browsers, all properties are enumerable.+Object.defineProperties(Body.prototype, {+ body: { enumerable: true },+ bodyUsed: { enumerable: true },+ arrayBuffer: { enumerable: true },+ blob: { enumerable: true },+ json: { enumerable: true },+ text: { enumerable: true }+});++Body.mixIn = function (proto) {+ for (const name of Object.getOwnPropertyNames(Body.prototype)) {+ // istanbul ignore else: future proof+ if (!(name in proto)) {+ const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);+ Object.defineProperty(proto, name, desc);+ }+ }+};++/**+ * Consume and convert an entire Body to a Buffer.+ *+ * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body+ *+ * @return Promise+ */+function consumeBody() {+ var _this4 = this;++ if (this[INTERNALS].disturbed) {+ return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));+ }++ this[INTERNALS].disturbed = true;++ if (this[INTERNALS].error) {+ return Body.Promise.reject(this[INTERNALS].error);+ }++ let body = this.body;++ // body is null+ if (body === null) {+ return Body.Promise.resolve(Buffer.alloc(0));+ }++ // body is blob+ if (isBlob(body)) {+ body = body.stream();+ }++ // body is buffer+ if (Buffer.isBuffer(body)) {+ return Body.Promise.resolve(body);+ }++ // istanbul ignore if: should never happen+ if (!(body instanceof Stream__default['default'])) {+ return Body.Promise.resolve(Buffer.alloc(0));+ }++ // body is stream+ // get ready to actually consume the body+ let accum = [];+ let accumBytes = 0;+ let abort = false;++ return new Body.Promise(function (resolve, reject) {+ let resTimeout;++ // allow timeout on slow response body+ if (_this4.timeout) {+ resTimeout = setTimeout(function () {+ abort = true;+ reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));+ }, _this4.timeout);+ }++ // handle stream errors+ body.on('error', function (err) {+ if (err.name === 'AbortError') {+ // if the request was aborted, reject with this Error+ abort = true;+ reject(err);+ } else {+ // other errors, such as incorrect content-encoding+ reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));+ }+ });++ body.on('data', function (chunk) {+ if (abort || chunk === null) {+ return;+ }++ if (_this4.size && accumBytes + chunk.length > _this4.size) {+ abort = true;+ reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));+ return;+ }++ accumBytes += chunk.length;+ accum.push(chunk);+ });++ body.on('end', function () {+ if (abort) {+ return;+ }++ clearTimeout(resTimeout);++ try {+ resolve(Buffer.concat(accum, accumBytes));+ } catch (err) {+ // handle streams that have accumulated too much data (issue #414)+ reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));+ }+ });+ });+}++/**+ * Detect buffer encoding and convert to target encoding+ * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding+ *+ * @param Buffer buffer Incoming buffer+ * @param String encoding Target encoding+ * @return String+ */+function convertBody(buffer, headers) {+ if (typeof convert !== 'function') {+ throw new Error('The package `encoding` must be installed to use the textConverted() function');+ }++ const ct = headers.get('content-type');+ let charset = 'utf-8';+ let res, str;++ // header+ if (ct) {+ res = /charset=([^;]*)/i.exec(ct);+ }++ // no charset in content type, peek at response body for at most 1024 bytes+ str = buffer.slice(0, 1024).toString();++ // html5+ if (!res && str) {+ res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);+ }++ // html4+ if (!res && str) {+ res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);+ if (!res) {+ res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);+ if (res) {+ res.pop(); // drop last quote+ }+ }++ if (res) {+ res = /charset=(.*)/i.exec(res.pop());+ }+ }++ // xml+ if (!res && str) {+ res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);+ }++ // found charset+ if (res) {+ charset = res.pop();++ // prevent decode issues when sites use incorrect encoding+ // ref: https://hsivonen.fi/encoding-menu/+ if (charset === 'gb2312' || charset === 'gbk') {+ charset = 'gb18030';+ }+ }++ // turn raw buffers into a single utf-8 buffer+ return convert(buffer, 'UTF-8', charset).toString();+}++/**+ * Detect a URLSearchParams object+ * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143+ *+ * @param Object obj Object to detect by type or brand+ * @return String+ */+function isURLSearchParams(obj) {+ // Duck-typing as a necessary condition.+ if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {+ return false;+ }++ // Brand-checking and more duck-typing as optional condition.+ return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';+}++/**+ * Check if `obj` is a W3C `Blob` object (which `File` inherits from)+ * @param {*} obj+ * @return {boolean}+ */+function isBlob(obj) {+ return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);+}++/**+ * Clone body given Res/Req instance+ *+ * @param Mixed instance Response or Request instance+ * @return Mixed+ */+function clone$1(instance) {+ let p1, p2;+ let body = instance.body;++ // don't allow cloning a used body+ if (instance.bodyUsed) {+ throw new Error('cannot clone body after it is used');+ }++ // check that body is a stream and not form-data object+ // note: we can't clone the form-data object without having it as a dependency+ if (body instanceof Stream__default['default'] && typeof body.getBoundary !== 'function') {+ // tee instance body+ p1 = new PassThrough$1();+ p2 = new PassThrough$1();+ body.pipe(p1);+ body.pipe(p2);+ // set instance body to teed body and return the other teed body+ instance[INTERNALS].body = p1;+ body = p2;+ }++ return body;+}++/**+ * Performs the operation "extract a `Content-Type` value from |object|" as+ * specified in the specification:+ * https://fetch.spec.whatwg.org/#concept-bodyinit-extract+ *+ * This function assumes that instance.body is present.+ *+ * @param Mixed instance Any options.body input+ */+function extractContentType(body) {+ if (body === null) {+ // body is null+ return null;+ } else if (typeof body === 'string') {+ // body is string+ return 'text/plain;charset=UTF-8';+ } else if (isURLSearchParams(body)) {+ // body is a URLSearchParams+ return 'application/x-www-form-urlencoded;charset=UTF-8';+ } else if (isBlob(body)) {+ // body is blob+ return body.type || null;+ } else if (Buffer.isBuffer(body)) {+ // body is buffer+ return null;+ } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {+ // body is ArrayBuffer+ return null;+ } else if (ArrayBuffer.isView(body)) {+ // body is ArrayBufferView+ return null;+ } else if (typeof body.getBoundary === 'function') {+ // detect form data input from form-data module+ return `multipart/form-data;boundary=${body.getBoundary()}`;+ } else if (body instanceof Stream__default['default']) {+ // body is stream+ // can't really do much about this+ return null;+ } else {+ // Body constructor defaults other things to string+ return 'text/plain;charset=UTF-8';+ }+}++/**+ * The Fetch Standard treats this as if "total bytes" is a property on the body.+ * For us, we have to explicitly get it with a function.+ *+ * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes+ *+ * @param Body instance Instance of Body+ * @return Number? Number of bytes, or null if not possible+ */+function getTotalBytes(instance) {+ const body = instance.body;+++ if (body === null) {+ // body is null+ return 0;+ } else if (isBlob(body)) {+ return body.size;+ } else if (Buffer.isBuffer(body)) {+ // body is buffer+ return body.length;+ } else if (body && typeof body.getLengthSync === 'function') {+ // detect form data input from form-data module+ if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x+ body.hasKnownLength && body.hasKnownLength()) {+ // 2.x+ return body.getLengthSync();+ }+ return null;+ } else {+ // body is stream+ return null;+ }+}++/**+ * Write a Body to a Node.js WritableStream (e.g. http.Request) object.+ *+ * @param Body instance Instance of Body+ * @return Void+ */+function writeToStream(dest, instance) {+ const body = instance.body;+++ if (body === null) {+ // body is null+ dest.end();+ } else if (isBlob(body)) {+ body.stream().pipe(dest);+ } else if (Buffer.isBuffer(body)) {+ // body is buffer+ dest.write(body);+ dest.end();+ } else {+ // body is stream+ body.pipe(dest);+ }+}++// expose Promise+Body.Promise = global.Promise;++/**+ * headers.js+ *+ * Headers class offers convenient helpers+ */++const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;+const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;++function validateName$1(name) {+ name = `${name}`;+ if (invalidTokenRegex.test(name) || name === '') {+ throw new TypeError(`${name} is not a legal HTTP header name`);+ }+}++function validateValue(value) {+ value = `${value}`;+ if (invalidHeaderCharRegex.test(value)) {+ throw new TypeError(`${value} is not a legal HTTP header value`);+ }+}++/**+ * Find the key in the map object given a header name.+ *+ * Returns undefined if not found.+ *+ * @param String name Header name+ * @return String|Undefined+ */+function find$1(map, name) {+ name = name.toLowerCase();+ for (const key in map) {+ if (key.toLowerCase() === name) {+ return key;+ }+ }+ return undefined;+}++const MAP = Symbol('map');+class Headers {+ /**+ * Headers class+ *+ * @param Object headers Response headers+ * @return Void+ */+ constructor() {+ let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;++ this[MAP] = Object.create(null);++ if (init instanceof Headers) {+ const rawHeaders = init.raw();+ const headerNames = Object.keys(rawHeaders);++ for (const headerName of headerNames) {+ for (const value of rawHeaders[headerName]) {+ this.append(headerName, value);+ }+ }++ return;+ }++ // We don't worry about converting prop to ByteString here as append()+ // will handle it.+ if (init == null) ; else if (typeof init === 'object') {+ const method = init[Symbol.iterator];+ if (method != null) {+ if (typeof method !== 'function') {+ throw new TypeError('Header pairs must be iterable');+ }++ // sequence<sequence<ByteString>>+ // Note: per spec we have to first exhaust the lists then process them+ const pairs = [];+ for (const pair of init) {+ if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {+ throw new TypeError('Each header pair must be iterable');+ }+ pairs.push(Array.from(pair));+ }++ for (const pair of pairs) {+ if (pair.length !== 2) {+ throw new TypeError('Each header pair must be a name/value tuple');+ }+ this.append(pair[0], pair[1]);+ }+ } else {+ // record<ByteString, ByteString>+ for (const key of Object.keys(init)) {+ const value = init[key];+ this.append(key, value);+ }+ }+ } else {+ throw new TypeError('Provided initializer must be an object');+ }+ }++ /**+ * Return combined header value given name+ *+ * @param String name Header name+ * @return Mixed+ */+ get(name) {+ name = `${name}`;+ validateName$1(name);+ const key = find$1(this[MAP], name);+ if (key === undefined) {+ return null;+ }++ return this[MAP][key].join(', ');+ }++ /**+ * Iterate over all headers+ *+ * @param Function callback Executed for each item with parameters (value, name, thisArg)+ * @param Boolean thisArg `this` context for callback function+ * @return Void+ */+ forEach(callback) {+ let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;++ let pairs = getHeaders(this);+ let i = 0;+ while (i < pairs.length) {+ var _pairs$i = pairs[i];+ const name = _pairs$i[0],+ value = _pairs$i[1];++ callback.call(thisArg, value, name, this);+ pairs = getHeaders(this);+ i++;+ }+ }++ /**+ * Overwrite header values given name+ *+ * @param String name Header name+ * @param String value Header value+ * @return Void+ */+ set(name, value) {+ name = `${name}`;+ value = `${value}`;+ validateName$1(name);+ validateValue(value);+ const key = find$1(this[MAP], name);+ this[MAP][key !== undefined ? key : name] = [value];+ }++ /**+ * Append a value onto existing header+ *+ * @param String name Header name+ * @param String value Header value+ * @return Void+ */+ append(name, value) {+ name = `${name}`;+ value = `${value}`;+ validateName$1(name);+ validateValue(value);+ const key = find$1(this[MAP], name);+ if (key !== undefined) {+ this[MAP][key].push(value);+ } else {+ this[MAP][name] = [value];+ }+ }++ /**+ * Check for header name existence+ *+ * @param String name Header name+ * @return Boolean+ */+ has(name) {+ name = `${name}`;+ validateName$1(name);+ return find$1(this[MAP], name) !== undefined;+ }++ /**+ * Delete all header values given name+ *+ * @param String name Header name+ * @return Void+ */+ delete(name) {+ name = `${name}`;+ validateName$1(name);+ const key = find$1(this[MAP], name);+ if (key !== undefined) {+ delete this[MAP][key];+ }+ }++ /**+ * Return raw headers (non-spec api)+ *+ * @return Object+ */+ raw() {+ return this[MAP];+ }++ /**+ * Get an iterator on keys.+ *+ * @return Iterator+ */+ keys() {+ return createHeadersIterator(this, 'key');+ }++ /**+ * Get an iterator on values.+ *+ * @return Iterator+ */+ values() {+ return createHeadersIterator(this, 'value');+ }++ /**+ * Get an iterator on entries.+ *+ * This is the default iterator of the Headers object.+ *+ * @return Iterator+ */+ [Symbol.iterator]() {+ return createHeadersIterator(this, 'key+value');+ }+}+Headers.prototype.entries = Headers.prototype[Symbol.iterator];++Object.defineProperty(Headers.prototype, Symbol.toStringTag, {+ value: 'Headers',+ writable: false,+ enumerable: false,+ configurable: true+});++Object.defineProperties(Headers.prototype, {+ get: { enumerable: true },+ forEach: { enumerable: true },+ set: { enumerable: true },+ append: { enumerable: true },+ has: { enumerable: true },+ delete: { enumerable: true },+ keys: { enumerable: true },+ values: { enumerable: true },+ entries: { enumerable: true }+});++function getHeaders(headers) {+ let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';++ const keys = Object.keys(headers[MAP]).sort();+ return keys.map(kind === 'key' ? function (k) {+ return k.toLowerCase();+ } : kind === 'value' ? function (k) {+ return headers[MAP][k].join(', ');+ } : function (k) {+ return [k.toLowerCase(), headers[MAP][k].join(', ')];+ });+}++const INTERNAL = Symbol('internal');++function createHeadersIterator(target, kind) {+ const iterator = Object.create(HeadersIteratorPrototype);+ iterator[INTERNAL] = {+ target,+ kind,+ index: 0+ };+ return iterator;+}++const HeadersIteratorPrototype = Object.setPrototypeOf({+ next() {+ // istanbul ignore if+ if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {+ throw new TypeError('Value of `this` is not a HeadersIterator');+ }++ var _INTERNAL = this[INTERNAL];+ const target = _INTERNAL.target,+ kind = _INTERNAL.kind,+ index = _INTERNAL.index;++ const values = getHeaders(target, kind);+ const len = values.length;+ if (index >= len) {+ return {+ value: undefined,+ done: true+ };+ }++ this[INTERNAL].index = index + 1;++ return {+ value: values[index],+ done: false+ };+ }+}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));++Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {+ value: 'HeadersIterator',+ writable: false,+ enumerable: false,+ configurable: true+});++/**+ * Export the Headers object in a form that Node.js can consume.+ *+ * @param Headers headers+ * @return Object+ */+function exportNodeCompatibleHeaders(headers) {+ const obj = Object.assign({ __proto__: null }, headers[MAP]);++ // http.request() only supports string as Host header. This hack makes+ // specifying custom Host header possible.+ const hostHeaderKey = find$1(headers[MAP], 'Host');+ if (hostHeaderKey !== undefined) {+ obj[hostHeaderKey] = obj[hostHeaderKey][0];+ }++ return obj;+}++/**+ * Create a Headers object from an object of headers, ignoring those that do+ * not conform to HTTP grammar productions.+ *+ * @param Object obj Object of headers+ * @return Headers+ */+function createHeadersLenient(obj) {+ const headers = new Headers();+ for (const name of Object.keys(obj)) {+ if (invalidTokenRegex.test(name)) {+ continue;+ }+ if (Array.isArray(obj[name])) {+ for (const val of obj[name]) {+ if (invalidHeaderCharRegex.test(val)) {+ continue;+ }+ if (headers[MAP][name] === undefined) {+ headers[MAP][name] = [val];+ } else {+ headers[MAP][name].push(val);+ }+ }+ } else if (!invalidHeaderCharRegex.test(obj[name])) {+ headers[MAP][name] = [obj[name]];+ }+ }+ return headers;+}++const INTERNALS$1 = Symbol('Response internals');++// fix an issue where "STATUS_CODES" aren't a named export for node <10+const STATUS_CODES = http__default['default'].STATUS_CODES;++/**+ * Response class+ *+ * @param Stream body Readable stream+ * @param Object opts Response options+ * @return Void+ */+class Response {+ constructor() {+ let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;+ let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};++ Body.call(this, body, opts);++ const status = opts.status || 200;+ const headers = new Headers(opts.headers);++ if (body != null && !headers.has('Content-Type')) {+ const contentType = extractContentType(body);+ if (contentType) {+ headers.append('Content-Type', contentType);+ }+ }++ this[INTERNALS$1] = {+ url: opts.url,+ status,+ statusText: opts.statusText || STATUS_CODES[status],+ headers,+ counter: opts.counter+ };+ }++ get url() {+ return this[INTERNALS$1].url || '';+ }++ get status() {+ return this[INTERNALS$1].status;+ }++ /**+ * Convenience property representing if the request ended normally+ */+ get ok() {+ return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;+ }++ get redirected() {+ return this[INTERNALS$1].counter > 0;+ }++ get statusText() {+ return this[INTERNALS$1].statusText;+ }++ get headers() {+ return this[INTERNALS$1].headers;+ }++ /**+ * Clone this response+ *+ * @return Response+ */+ clone() {+ return new Response(clone$1(this), {+ url: this.url,+ status: this.status,+ statusText: this.statusText,+ headers: this.headers,+ ok: this.ok,+ redirected: this.redirected+ });+ }+}++Body.mixIn(Response.prototype);++Object.defineProperties(Response.prototype, {+ url: { enumerable: true },+ status: { enumerable: true },+ ok: { enumerable: true },+ redirected: { enumerable: true },+ statusText: { enumerable: true },+ headers: { enumerable: true },+ clone: { enumerable: true }+});++Object.defineProperty(Response.prototype, Symbol.toStringTag, {+ value: 'Response',+ writable: false,+ enumerable: false,+ configurable: true+});++const INTERNALS$2 = Symbol('Request internals');++// fix an issue where "format", "parse" aren't a named export for node <10+const parse_url = Url__default['default'].parse;+const format_url = Url__default['default'].format;++const streamDestructionSupported = 'destroy' in Stream__default['default'].Readable.prototype;++/**+ * Check if a value is an instance of Request.+ *+ * @param Mixed input+ * @return Boolean+ */+function isRequest(input) {+ return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';+}++function isAbortSignal(signal) {+ const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);+ return !!(proto && proto.constructor.name === 'AbortSignal');+}++/**+ * Request class+ *+ * @param Mixed input Url or Request instance+ * @param Object init Custom options+ * @return Void+ */+class Request {+ constructor(input) {+ let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};++ let parsedURL;++ // normalize input+ if (!isRequest(input)) {+ if (input && input.href) {+ // in order to support Node.js' Url objects; though WHATWG's URL objects+ // will fall into this branch also (since their `toString()` will return+ // `href` property anyway)+ parsedURL = parse_url(input.href);+ } else {+ // coerce input to a string before attempting to parse+ parsedURL = parse_url(`${input}`);+ }+ input = {};+ } else {+ parsedURL = parse_url(input.url);+ }++ let method = init.method || input.method || 'GET';+ method = method.toUpperCase();++ if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {+ throw new TypeError('Request with GET/HEAD method cannot have body');+ }++ let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone$1(input) : null;++ Body.call(this, inputBody, {+ timeout: init.timeout || input.timeout || 0,+ size: init.size || input.size || 0+ });++ const headers = new Headers(init.headers || input.headers || {});++ if (inputBody != null && !headers.has('Content-Type')) {+ const contentType = extractContentType(inputBody);+ if (contentType) {+ headers.append('Content-Type', contentType);+ }+ }++ let signal = isRequest(input) ? input.signal : null;+ if ('signal' in init) signal = init.signal;++ if (signal != null && !isAbortSignal(signal)) {+ throw new TypeError('Expected signal to be an instanceof AbortSignal');+ }++ this[INTERNALS$2] = {+ method,+ redirect: init.redirect || input.redirect || 'follow',+ headers,+ parsedURL,+ signal+ };++ // node-fetch-only options+ this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;+ this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;+ this.counter = init.counter || input.counter || 0;+ this.agent = init.agent || input.agent;+ }++ get method() {+ return this[INTERNALS$2].method;+ }++ get url() {+ return format_url(this[INTERNALS$2].parsedURL);+ }++ get headers() {+ return this[INTERNALS$2].headers;+ }++ get redirect() {+ return this[INTERNALS$2].redirect;+ }++ get signal() {+ return this[INTERNALS$2].signal;+ }++ /**+ * Clone this request+ *+ * @return Request+ */+ clone() {+ return new Request(this);+ }+}++Body.mixIn(Request.prototype);++Object.defineProperty(Request.prototype, Symbol.toStringTag, {+ value: 'Request',+ writable: false,+ enumerable: false,+ configurable: true+});++Object.defineProperties(Request.prototype, {+ method: { enumerable: true },+ url: { enumerable: true },+ headers: { enumerable: true },+ redirect: { enumerable: true },+ clone: { enumerable: true },+ signal: { enumerable: true }+});++/**+ * Convert a Request to Node.js http request options.+ *+ * @param Request A Request instance+ * @return Object The options object to be passed to http.request+ */+function getNodeRequestOptions(request) {+ const parsedURL = request[INTERNALS$2].parsedURL;+ const headers = new Headers(request[INTERNALS$2].headers);++ // fetch step 1.3+ if (!headers.has('Accept')) {+ headers.set('Accept', '*/*');+ }++ // Basic fetch+ if (!parsedURL.protocol || !parsedURL.hostname) {+ throw new TypeError('Only absolute URLs are supported');+ }++ if (!/^https?:$/.test(parsedURL.protocol)) {+ throw new TypeError('Only HTTP(S) protocols are supported');+ }++ if (request.signal && request.body instanceof Stream__default['default'].Readable && !streamDestructionSupported) {+ throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');+ }++ // HTTP-network-or-cache fetch steps 2.4-2.7+ let contentLengthValue = null;+ if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {+ contentLengthValue = '0';+ }+ if (request.body != null) {+ const totalBytes = getTotalBytes(request);+ if (typeof totalBytes === 'number') {+ contentLengthValue = String(totalBytes);+ }+ }+ if (contentLengthValue) {+ headers.set('Content-Length', contentLengthValue);+ }++ // HTTP-network-or-cache fetch step 2.11+ if (!headers.has('User-Agent')) {+ headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');+ }++ // HTTP-network-or-cache fetch step 2.15+ if (request.compress && !headers.has('Accept-Encoding')) {+ headers.set('Accept-Encoding', 'gzip,deflate');+ }++ let agent = request.agent;+ if (typeof agent === 'function') {+ agent = agent(parsedURL);+ }++ if (!headers.has('Connection') && !agent) {+ headers.set('Connection', 'close');+ }++ // HTTP-network fetch step 4.2+ // chunked encoding is handled by Node.js++ return Object.assign({}, parsedURL, {+ method: request.method,+ headers: exportNodeCompatibleHeaders(headers),+ agent+ });+}++/**+ * abort-error.js+ *+ * AbortError interface for cancelled requests+ */++/**+ * Create AbortError instance+ *+ * @param String message Error message for human+ * @return AbortError+ */+function AbortError(message) {+ Error.call(this, message);++ this.type = 'aborted';+ this.message = message;++ // hide custom error implementation details from end-users+ Error.captureStackTrace(this, this.constructor);+}++AbortError.prototype = Object.create(Error.prototype);+AbortError.prototype.constructor = AbortError;+AbortError.prototype.name = 'AbortError';++// fix an issue where "PassThrough", "resolve" aren't a named export for node <10+const PassThrough$1$1 = Stream__default['default'].PassThrough;+const resolve_url = Url__default['default'].resolve;++/**+ * Fetch function+ *+ * @param Mixed url Absolute url or Request instance+ * @param Object opts Fetch options+ * @return Promise+ */+function fetch(url, opts) {++ // allow custom promise+ if (!fetch.Promise) {+ throw new Error('native promise missing, set fetch.Promise to your favorite alternative');+ }++ Body.Promise = fetch.Promise;++ // wrap http.request into fetch+ return new fetch.Promise(function (resolve, reject) {+ // build request object+ const request = new Request(url, opts);+ const options = getNodeRequestOptions(request);++ const send = (options.protocol === 'https:' ? https__default['default'] : http__default['default']).request;+ const signal = request.signal;++ let response = null;++ const abort = function abort() {+ let error = new AbortError('The user aborted a request.');+ reject(error);+ if (request.body && request.body instanceof Stream__default['default'].Readable) {+ request.body.destroy(error);+ }+ if (!response || !response.body) return;+ response.body.emit('error', error);+ };++ if (signal && signal.aborted) {+ abort();+ return;+ }++ const abortAndFinalize = function abortAndFinalize() {+ abort();+ finalize();+ };++ // send request+ const req = send(options);+ let reqTimeout;++ if (signal) {+ signal.addEventListener('abort', abortAndFinalize);+ }++ function finalize() {+ req.abort();+ if (signal) signal.removeEventListener('abort', abortAndFinalize);+ clearTimeout(reqTimeout);+ }++ if (request.timeout) {+ req.once('socket', function (socket) {+ reqTimeout = setTimeout(function () {+ reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));+ finalize();+ }, request.timeout);+ });+ }++ req.on('error', function (err) {+ reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));+ finalize();+ });++ req.on('response', function (res) {+ clearTimeout(reqTimeout);++ const headers = createHeadersLenient(res.headers);++ // HTTP fetch step 5+ if (fetch.isRedirect(res.statusCode)) {+ // HTTP fetch step 5.2+ const location = headers.get('Location');++ // HTTP fetch step 5.3+ const locationURL = location === null ? null : resolve_url(request.url, location);++ // HTTP fetch step 5.5+ switch (request.redirect) {+ case 'error':+ reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));+ finalize();+ return;+ case 'manual':+ // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.+ if (locationURL !== null) {+ // handle corrupted header+ try {+ headers.set('Location', locationURL);+ } catch (err) {+ // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request+ reject(err);+ }+ }+ break;+ case 'follow':+ // HTTP-redirect fetch step 2+ if (locationURL === null) {+ break;+ }++ // HTTP-redirect fetch step 5+ if (request.counter >= request.follow) {+ reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));+ finalize();+ return;+ }++ // HTTP-redirect fetch step 6 (counter increment)+ // Create a new Request object.+ const requestOpts = {+ headers: new Headers(request.headers),+ follow: request.follow,+ counter: request.counter + 1,+ agent: request.agent,+ compress: request.compress,+ method: request.method,+ body: request.body,+ signal: request.signal,+ timeout: request.timeout,+ size: request.size+ };++ // HTTP-redirect fetch step 9+ if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {+ reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));+ finalize();+ return;+ }++ // HTTP-redirect fetch step 11+ if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {+ requestOpts.method = 'GET';+ requestOpts.body = undefined;+ requestOpts.headers.delete('content-length');+ }++ // HTTP-redirect fetch step 15+ resolve(fetch(new Request(locationURL, requestOpts)));+ finalize();+ return;+ }+ }++ // prepare response+ res.once('end', function () {+ if (signal) signal.removeEventListener('abort', abortAndFinalize);+ });+ let body = res.pipe(new PassThrough$1$1());++ const response_options = {+ url: request.url,+ status: res.statusCode,+ statusText: res.statusMessage,+ headers: headers,+ size: request.size,+ timeout: request.timeout,+ counter: request.counter+ };++ // HTTP-network fetch step 12.1.1.3+ const codings = headers.get('Content-Encoding');++ // HTTP-network fetch step 12.1.1.4: handle content codings++ // in following scenarios we ignore compression support+ // 1. compression support is disabled+ // 2. HEAD request+ // 3. no Content-Encoding header+ // 4. no content response (204)+ // 5. content not modified response (304)+ if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {+ response = new Response(body, response_options);+ resolve(response);+ return;+ }++ // For Node v6++ // Be less strict when decoding compressed responses, since sometimes+ // servers send slightly invalid responses that are still accepted+ // by common browsers.+ // Always using Z_SYNC_FLUSH is what cURL does.+ const zlibOptions = {+ flush: zlib__default['default'].Z_SYNC_FLUSH,+ finishFlush: zlib__default['default'].Z_SYNC_FLUSH+ };++ // for gzip+ if (codings == 'gzip' || codings == 'x-gzip') {+ body = body.pipe(zlib__default['default'].createGunzip(zlibOptions));+ response = new Response(body, response_options);+ resolve(response);+ return;+ }++ // for deflate+ if (codings == 'deflate' || codings == 'x-deflate') {+ // handle the infamous raw deflate response from old servers+ // a hack for old IIS and Apache servers+ const raw = res.pipe(new PassThrough$1$1());+ raw.once('data', function (chunk) {+ // see http://stackoverflow.com/questions/37519828+ if ((chunk[0] & 0x0F) === 0x08) {+ body = body.pipe(zlib__default['default'].createInflate());+ } else {+ body = body.pipe(zlib__default['default'].createInflateRaw());+ }+ response = new Response(body, response_options);+ resolve(response);+ });+ return;+ }++ // for br+ if (codings == 'br' && typeof zlib__default['default'].createBrotliDecompress === 'function') {+ body = body.pipe(zlib__default['default'].createBrotliDecompress());+ response = new Response(body, response_options);+ resolve(response);+ return;+ }++ // otherwise, use response as-is+ response = new Response(body, response_options);+ resolve(response);+ });++ writeToStream(req, request);+ });+}+/**+ * Redirect code matching+ *+ * @param Number code Status code+ * @return Boolean+ */+fetch.isRedirect = function (code) {+ return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;+};++// expose Promise+fetch.Promise = global.Promise;++var lib$1 = /*#__PURE__*/Object.freeze({+ __proto__: null,+ 'default': fetch,+ Headers: Headers,+ Request: Request,+ Response: Response,+ FetchError: FetchError+});++var nodeFetch = /*@__PURE__*/getAugmentedNamespace(lib$1);++var nodePonyfill = createCommonjsModule(function (module, exports) {+var realFetch = nodeFetch.default || nodeFetch;++var fetch = function (url, options) {+ // Support schemaless URIs on the server for parity with the browser.+ // Ex: //github.com/ -> https://github.com/+ if (/^\/\//.test(url)) {+ url = 'https:' + url;+ }+ return realFetch.call(this, url, options)+};++module.exports = exports = fetch;+exports.fetch = fetch;+exports.Headers = nodeFetch.Headers;+exports.Request = nodeFetch.Request;+exports.Response = nodeFetch.Response;++// Needed for TypeScript consumers without esModuleInterop.+exports.default = fetch;+});++var isPromise_1 = isPromise$1;+var _default$1 = isPromise$1;++function isPromise$1(obj) {+ return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';+}+isPromise_1.default = _default$1;++/**+ * Copyright (c) 2019-present, GraphQL Foundation+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ *+ * + */+// A Function, which when given an Array of keys, returns a Promise of an Array+// of values or Errors.+// Optionally turn off batching or caching or provide a cache key function or a+// custom cache instance.+// If a custom cache is provided, it must be of this type (a subset of ES6 Map).++/**+ * A `DataLoader` creates a public API for loading data from a particular+ * data back-end with unique keys such as the `id` column of a SQL table or+ * document name in a MongoDB database, given a batch loading function.+ *+ * Each `DataLoader` instance contains a unique memoized cache. Use caution when+ * used in long-lived applications or those which serve many users with+ * different access permissions and consider creating a new instance per+ * web request.+ */+var DataLoader =+/*#__PURE__*/+function () {+ function DataLoader(batchLoadFn, options) {+ if (typeof batchLoadFn !== 'function') {+ throw new TypeError('DataLoader must be constructed with a function which accepts ' + ("Array<key> and returns Promise<Array<value>>, but got: " + batchLoadFn + "."));+ }++ this._batchLoadFn = batchLoadFn;+ this._maxBatchSize = getValidMaxBatchSize(options);+ this._batchScheduleFn = getValidBatchScheduleFn(options);+ this._cacheKeyFn = getValidCacheKeyFn(options);+ this._cacheMap = getValidCacheMap(options);+ this._batch = null;+ } // Private+++ var _proto = DataLoader.prototype;++ /**+ * Loads a key, returning a `Promise` for the value represented by that key.+ */+ _proto.load = function load(key) {+ if (key === null || key === undefined) {+ throw new TypeError('The loader.load() function must be called with a value,' + ("but got: " + String(key) + "."));+ }++ var batch = getCurrentBatch(this);+ var cacheMap = this._cacheMap;++ var cacheKey = this._cacheKeyFn(key); // If caching and there is a cache-hit, return cached Promise.+++ if (cacheMap) {+ var cachedPromise = cacheMap.get(cacheKey);++ if (cachedPromise) {+ var cacheHits = batch.cacheHits || (batch.cacheHits = []);+ return new Promise(function (resolve) {+ cacheHits.push(function () {+ return resolve(cachedPromise);+ });+ });+ }+ } // Otherwise, produce a new Promise for this key, and enqueue it to be+ // dispatched along with the current batch.+++ batch.keys.push(key);+ var promise = new Promise(function (resolve, reject) {+ batch.callbacks.push({+ resolve: resolve,+ reject: reject+ });+ }); // If caching, cache this promise.++ if (cacheMap) {+ cacheMap.set(cacheKey, promise);+ }++ return promise;+ }+ /**+ * Loads multiple keys, promising an array of values:+ *+ * var [ a, b ] = await myLoader.loadMany([ 'a', 'b' ]);+ *+ * This is similar to the more verbose:+ *+ * var [ a, b ] = await Promise.all([+ * myLoader.load('a'),+ * myLoader.load('b')+ * ]);+ *+ * However it is different in the case where any load fails. Where+ * Promise.all() would reject, loadMany() always resolves, however each result+ * is either a value or an Error instance.+ *+ * var [ a, b, c ] = await myLoader.loadMany([ 'a', 'b', 'badkey' ]);+ * // c instanceof Error+ *+ */+ ;++ _proto.loadMany = function loadMany(keys) {+ if (!isArrayLike(keys)) {+ throw new TypeError('The loader.loadMany() function must be called with Array<key> ' + ("but got: " + keys + "."));+ } // Support ArrayLike by using only minimal property access+++ var loadPromises = [];++ for (var i = 0; i < keys.length; i++) {+ loadPromises.push(this.load(keys[i])["catch"](function (error) {+ return error;+ }));+ }++ return Promise.all(loadPromises);+ }+ /**+ * Clears the value at `key` from the cache, if it exists. Returns itself for+ * method chaining.+ */+ ;++ _proto.clear = function clear(key) {+ var cacheMap = this._cacheMap;++ if (cacheMap) {+ var cacheKey = this._cacheKeyFn(key);++ cacheMap["delete"](cacheKey);+ }++ return this;+ }+ /**+ * Clears the entire cache. To be used when some event results in unknown+ * invalidations across this particular `DataLoader`. Returns itself for+ * method chaining.+ */+ ;++ _proto.clearAll = function clearAll() {+ var cacheMap = this._cacheMap;++ if (cacheMap) {+ cacheMap.clear();+ }++ return this;+ }+ /**+ * Adds the provided key and value to the cache. If the key already+ * exists, no change is made. Returns itself for method chaining.+ *+ * To prime the cache with an error at a key, provide an Error instance.+ */+ ;++ _proto.prime = function prime(key, value) {+ var cacheMap = this._cacheMap;++ if (cacheMap) {+ var cacheKey = this._cacheKeyFn(key); // Only add the key if it does not already exist.+++ if (cacheMap.get(cacheKey) === undefined) {+ // Cache a rejected promise if the value is an Error, in order to match+ // the behavior of load(key).+ var promise;++ if (value instanceof Error) {+ promise = Promise.reject(value); // Since this is a case where an Error is intentionally being primed+ // for a given key, we want to disable unhandled promise rejection.++ promise["catch"](function () {});+ } else {+ promise = Promise.resolve(value);+ }++ cacheMap.set(cacheKey, promise);+ }+ }++ return this;+ };++ return DataLoader;+}(); // Private: Enqueue a Job to be executed after all "PromiseJobs" Jobs.+//+// ES6 JavaScript uses the concepts Job and JobQueue to schedule work to occur+// after the current execution context has completed:+// http://www.ecma-international.org/ecma-262/6.0/#sec-jobs-and-job-queues+//+// Node.js uses the `process.nextTick` mechanism to implement the concept of a+// Job, maintaining a global FIFO JobQueue for all Jobs, which is flushed after+// the current call stack ends.+//+// When calling `then` on a Promise, it enqueues a Job on a specific+// "PromiseJobs" JobQueue which is flushed in Node as a single Job on the+// global JobQueue.+//+// DataLoader batches all loads which occur in a single frame of execution, but+// should include in the batch all loads which occur during the flushing of the+// "PromiseJobs" JobQueue after that same execution frame.+//+// In order to avoid the DataLoader dispatch Job occuring before "PromiseJobs",+// A Promise Job is created with the sole purpose of enqueuing a global Job,+// ensuring that it always occurs after "PromiseJobs" ends.+//+// Node.js's job queue is unique. Browsers do not have an equivalent mechanism+// for enqueuing a job to be performed after promise microtasks and before the+// next macrotask. For browser environments, a macrotask is used (via+// setImmediate or setTimeout) at a potential performance penalty.+++var enqueuePostPromiseJob = typeof process === 'object' && typeof process.nextTick === 'function' ? function (fn) {+ if (!resolvedPromise) {+ resolvedPromise = Promise.resolve();+ }++ resolvedPromise.then(function () {+ return process.nextTick(fn);+ });+} : setImmediate || setTimeout; // Private: cached resolved Promise instance++var resolvedPromise; // Private: Describes a batch of requests++// Private: Either returns the current batch, or creates and schedules a+// dispatch of a new batch for the given loader.+function getCurrentBatch(loader) {+ // If there is an existing batch which has not yet dispatched and is within+ // the limit of the batch size, then return it.+ var existingBatch = loader._batch;++ if (existingBatch !== null && !existingBatch.hasDispatched && existingBatch.keys.length < loader._maxBatchSize && (!existingBatch.cacheHits || existingBatch.cacheHits.length < loader._maxBatchSize)) {+ return existingBatch;+ } // Otherwise, create a new batch for this loader.+++ var newBatch = {+ hasDispatched: false,+ keys: [],+ callbacks: []+ }; // Store it on the loader so it may be reused.++ loader._batch = newBatch; // Then schedule a task to dispatch this batch of requests.++ loader._batchScheduleFn(function () {+ return dispatchBatch(loader, newBatch);+ });++ return newBatch;+}++function dispatchBatch(loader, batch) {+ // Mark this batch as having been dispatched.+ batch.hasDispatched = true; // If there's nothing to load, resolve any cache hits and return early.++ if (batch.keys.length === 0) {+ resolveCacheHits(batch);+ return;+ } // Call the provided batchLoadFn for this loader with the batch's keys and+ // with the loader as the `this` context.+++ var batchPromise = loader._batchLoadFn(batch.keys); // Assert the expected response from batchLoadFn+++ if (!batchPromise || typeof batchPromise.then !== 'function') {+ return failedDispatch(loader, batch, new TypeError('DataLoader must be constructed with a function which accepts ' + 'Array<key> and returns Promise<Array<value>>, but the function did ' + ("not return a Promise: " + String(batchPromise) + ".")));+ } // Await the resolution of the call to batchLoadFn.+++ batchPromise.then(function (values) {+ // Assert the expected resolution from batchLoadFn.+ if (!isArrayLike(values)) {+ throw new TypeError('DataLoader must be constructed with a function which accepts ' + 'Array<key> and returns Promise<Array<value>>, but the function did ' + ("not return a Promise of an Array: " + String(values) + "."));+ }++ if (values.length !== batch.keys.length) {+ throw new TypeError('DataLoader must be constructed with a function which accepts ' + 'Array<key> and returns Promise<Array<value>>, but the function did ' + 'not return a Promise of an Array of the same length as the Array ' + 'of keys.' + ("\n\nKeys:\n" + String(batch.keys)) + ("\n\nValues:\n" + String(values)));+ } // Resolve all cache hits in the same micro-task as freshly loaded values.+++ resolveCacheHits(batch); // Step through values, resolving or rejecting each Promise in the batch.++ for (var i = 0; i < batch.callbacks.length; i++) {+ var value = values[i];++ if (value instanceof Error) {+ batch.callbacks[i].reject(value);+ } else {+ batch.callbacks[i].resolve(value);+ }+ }+ })["catch"](function (error) {+ return failedDispatch(loader, batch, error);+ });+} // Private: do not cache individual loads if the entire batch dispatch fails,+// but still reject each request so they do not hang.+++function failedDispatch(loader, batch, error) {+ // Cache hits are resolved, even though the batch failed.+ resolveCacheHits(batch);++ for (var i = 0; i < batch.keys.length; i++) {+ loader.clear(batch.keys[i]);+ batch.callbacks[i].reject(error);+ }+} // Private: Resolves the Promises for any cache hits in this batch.+++function resolveCacheHits(batch) {+ if (batch.cacheHits) {+ for (var i = 0; i < batch.cacheHits.length; i++) {+ batch.cacheHits[i]();+ }+ }+} // Private: given the DataLoader's options, produce a valid max batch size.+++function getValidMaxBatchSize(options) {+ var shouldBatch = !options || options.batch !== false;++ if (!shouldBatch) {+ return 1;+ }++ var maxBatchSize = options && options.maxBatchSize;++ if (maxBatchSize === undefined) {+ return Infinity;+ }++ if (typeof maxBatchSize !== 'number' || maxBatchSize < 1) {+ throw new TypeError("maxBatchSize must be a positive number: " + maxBatchSize);+ }++ return maxBatchSize;+} // Private+++function getValidBatchScheduleFn(options) {+ var batchScheduleFn = options && options.batchScheduleFn;++ if (batchScheduleFn === undefined) {+ return enqueuePostPromiseJob;+ }++ if (typeof batchScheduleFn !== 'function') {+ throw new TypeError("batchScheduleFn must be a function: " + batchScheduleFn);+ }++ return batchScheduleFn;+} // Private: given the DataLoader's options, produce a cache key function.+++function getValidCacheKeyFn(options) {+ var cacheKeyFn = options && options.cacheKeyFn;++ if (cacheKeyFn === undefined) {+ return function (key) {+ return key;+ };+ }++ if (typeof cacheKeyFn !== 'function') {+ throw new TypeError("cacheKeyFn must be a function: " + cacheKeyFn);+ }++ return cacheKeyFn;+} // Private: given the DataLoader's options, produce a CacheMap to be used.+++function getValidCacheMap(options) {+ var shouldCache = !options || options.cache !== false;++ if (!shouldCache) {+ return null;+ }++ var cacheMap = options && options.cacheMap;++ if (cacheMap === undefined) {+ return new Map();+ }++ if (cacheMap !== null) {+ var cacheFunctions = ['get', 'set', 'delete', 'clear'];+ var missingFunctions = cacheFunctions.filter(function (fnName) {+ return cacheMap && typeof cacheMap[fnName] !== 'function';+ });++ if (missingFunctions.length !== 0) {+ throw new TypeError('Custom cacheMap missing methods: ' + missingFunctions.join(', '));+ }+ }++ return cacheMap;+} // Private+++function isArrayLike(x) {+ return typeof x === 'object' && x !== null && typeof x.length === 'number' && (x.length === 0 || x.length > 0 && Object.prototype.hasOwnProperty.call(x, x.length - 1));+}++var dataloader = DataLoader;++const OBJECT_SUBSCHEMA_SYMBOL = Symbol('initialSubschema');+const FIELD_SUBSCHEMA_MAP_SYMBOL = Symbol('subschemaMap');++function getSubschema(result, responseKey) {+ const subschema = result[FIELD_SUBSCHEMA_MAP_SYMBOL] && result[FIELD_SUBSCHEMA_MAP_SYMBOL][responseKey];+ return subschema || result[OBJECT_SUBSCHEMA_SYMBOL];+}+function setObjectSubschema(result, subschema) {+ result[OBJECT_SUBSCHEMA_SYMBOL] = subschema;+}+function isSubschemaConfig(value) {+ return Boolean(value.schema && value.permutations === undefined);+}++function getDelegatingOperation(parentType, schema) {+ if (parentType === schema.getMutationType()) {+ return 'mutation';+ }+ else if (parentType === schema.getSubscriptionType()) {+ return 'subscription';+ }+ return 'query';+}+function createRequestFromInfo({ info, operationName, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, selectionSet, fieldNodes = info.fieldNodes, }) {+ return createRequest({+ sourceSchema: info.schema,+ sourceParentType: info.parentType,+ sourceFieldName: info.fieldName,+ fragments: info.fragments,+ variableDefinitions: info.operation.variableDefinitions,+ variableValues: info.variableValues,+ targetOperationName: operationName,+ targetOperation: operation,+ targetFieldName: fieldName,+ selectionSet,+ fieldNodes,+ });+}+function createRequest({ sourceSchema, sourceParentType, sourceFieldName, fragments, variableDefinitions, variableValues, targetOperationName, targetOperation, targetFieldName, selectionSet, fieldNodes, }) {+ var _a;+ let newSelectionSet;+ let argumentNodeMap;+ if (selectionSet != null) {+ newSelectionSet = selectionSet;+ argumentNodeMap = Object.create(null);+ }+ else {+ const selections = fieldNodes.reduce((acc, fieldNode) => (fieldNode.selectionSet != null ? acc.concat(fieldNode.selectionSet.selections) : acc), []);+ newSelectionSet = selections.length+ ? {+ kind: Kind.SELECTION_SET,+ selections,+ }+ : undefined;+ argumentNodeMap = {};+ const args = (_a = fieldNodes[0]) === null || _a === void 0 ? void 0 : _a.arguments;+ if (args) {+ argumentNodeMap = args.reduce((prev, curr) => ({+ ...prev,+ [curr.name.value]: curr,+ }), argumentNodeMap);+ }+ }+ const newVariables = Object.create(null);+ const variableDefinitionMap = Object.create(null);+ if (sourceSchema != null && variableDefinitions != null) {+ variableDefinitions.forEach(def => {+ const varName = def.variable.name.value;+ variableDefinitionMap[varName] = def;+ const varType = typeFromAST(sourceSchema, def.type);+ const serializedValue = serializeInputValue(varType, variableValues[varName]);+ if (serializedValue !== undefined) {+ newVariables[varName] = serializedValue;+ }+ });+ }+ if (sourceParentType != null) {+ updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, newVariables);+ }+ const rootfieldNode = {+ kind: Kind.FIELD,+ arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),+ name: {+ kind: Kind.NAME,+ value: targetFieldName || fieldNodes[0].name.value,+ },+ selectionSet: newSelectionSet,+ };+ const operationName = targetOperationName+ ? {+ kind: Kind.NAME,+ value: targetOperationName,+ }+ : undefined;+ const operationDefinition = {+ kind: Kind.OPERATION_DEFINITION,+ name: operationName,+ operation: targetOperation,+ variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),+ selectionSet: {+ kind: Kind.SELECTION_SET,+ selections: [rootfieldNode],+ },+ };+ let definitions = [operationDefinition];+ if (fragments != null) {+ definitions = definitions.concat(Object.keys(fragments).map(fragmentName => fragments[fragmentName]));+ }+ const document = {+ kind: Kind.DOCUMENT,+ definitions,+ };+ return {+ document,+ variables: newVariables,+ };+}+function updateArgumentsWithDefaults(sourceParentType, sourceFieldName, argumentNodeMap, variableDefinitionMap, variableValues) {+ const sourceField = sourceParentType.getFields()[sourceFieldName];+ sourceField.args.forEach((argument) => {+ const argName = argument.name;+ const sourceArgType = argument.type;+ if (argumentNodeMap[argName] === undefined) {+ const defaultValue = argument.defaultValue;+ if (defaultValue !== undefined) {+ updateArgument(argName, sourceArgType, argumentNodeMap, variableDefinitionMap, variableValues, serializeInputValue(sourceArgType, defaultValue));+ }+ }+ });+}++function memoizeInfoAnd2Objects(fn) {+ let cache1;+ function memoized(a1, a2, a3) {+ if (!cache1) {+ cache1 = new WeakMap();+ const cache2 = new WeakMap();+ cache1.set(a1.fieldNodes, cache2);+ const cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const newValue = fn(a1, a2, a3);+ cache3.set(a3, newValue);+ return newValue;+ }+ let cache2 = cache1.get(a1.fieldNodes);+ if (!cache2) {+ cache2 = new WeakMap();+ cache1.set(a1.fieldNodes, cache2);+ const cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const newValue = fn(a1, a2, a3);+ cache3.set(a3, newValue);+ return newValue;+ }+ let cache3 = cache2.get(a2);+ if (!cache3) {+ cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const newValue = fn(a1, a2, a3);+ cache3.set(a3, newValue);+ return newValue;+ }+ const cachedValue = cache3.get(a3);+ if (cachedValue === undefined) {+ const newValue = fn(a1, a2, a3);+ cache3.set(a3, newValue);+ return newValue;+ }+ return cachedValue;+ }+ return memoized;+}+function memoize4(fn) {+ let cache1;+ function memoized(a1, a2, a3, a4) {+ if (!cache1) {+ cache1 = new WeakMap();+ const cache2 = new WeakMap();+ cache1.set(a1, cache2);+ const cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const cache4 = new WeakMap();+ cache3.set(a3, cache4);+ const newValue = fn(a1, a2, a3, a4);+ cache4.set(a4, newValue);+ return newValue;+ }+ let cache2 = cache1.get(a1);+ if (!cache2) {+ cache2 = new WeakMap();+ cache1.set(a1, cache2);+ const cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const cache4 = new WeakMap();+ cache3.set(a3, cache4);+ const newValue = fn(a1, a2, a3, a4);+ cache4.set(a4, newValue);+ return newValue;+ }+ let cache3 = cache2.get(a2);+ if (!cache3) {+ cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const cache4 = new WeakMap();+ cache3.set(a3, cache4);+ const newValue = fn(a1, a2, a3, a4);+ cache4.set(a4, newValue);+ return newValue;+ }+ const cache4 = cache3.get(a3);+ if (!cache4) {+ const cache4 = new WeakMap();+ cache3.set(a3, cache4);+ const newValue = fn(a1, a2, a3, a4);+ cache4.set(a4, newValue);+ return newValue;+ }+ const cachedValue = cache4.get(a4);+ if (cachedValue === undefined) {+ const newValue = fn(a1, a2, a3, a4);+ cache4.set(a4, newValue);+ return newValue;+ }+ return cachedValue;+ }+ return memoized;+}+function memoize3$1(fn) {+ let cache1;+ function memoized(a1, a2, a3) {+ if (!cache1) {+ cache1 = new WeakMap();+ const cache2 = new WeakMap();+ cache1.set(a1, cache2);+ const cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const newValue = fn(a1, a2, a3);+ cache3.set(a3, newValue);+ return newValue;+ }+ let cache2 = cache1.get(a1);+ if (!cache2) {+ cache2 = new WeakMap();+ cache1.set(a1, cache2);+ const cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const newValue = fn(a1, a2, a3);+ cache3.set(a3, newValue);+ return newValue;+ }+ let cache3 = cache2.get(a2);+ if (!cache3) {+ cache3 = new WeakMap();+ cache2.set(a2, cache3);+ const newValue = fn(a1, a2, a3);+ cache3.set(a3, newValue);+ return newValue;+ }+ const cachedValue = cache3.get(a3);+ if (cachedValue === undefined) {+ const newValue = fn(a1, a2, a3);+ cache3.set(a3, newValue);+ return newValue;+ }+ return cachedValue;+ }+ return memoized;+}+function memoize2(fn) {+ let cache1;+ function memoized(a1, a2) {+ if (!cache1) {+ cache1 = new WeakMap();+ const cache2 = new WeakMap();+ cache1.set(a1, cache2);+ const newValue = fn(a1, a2);+ cache2.set(a2, newValue);+ return newValue;+ }+ let cache2 = cache1.get(a1);+ if (!cache2) {+ cache2 = new WeakMap();+ cache1.set(a1, cache2);+ const newValue = fn(a1, a2);+ cache2.set(a2, newValue);+ return newValue;+ }+ const cachedValue = cache2.get(a2);+ if (cachedValue === undefined) {+ const newValue = fn(a1, a2);+ cache2.set(a2, newValue);+ return newValue;+ }+ return cachedValue;+ }+ return memoized;+}+function memoize2of3(fn) {+ let cache1;+ function memoized(a1, a2, a3) {+ if (!cache1) {+ cache1 = new WeakMap();+ const cache2 = new WeakMap();+ cache1.set(a1, cache2);+ const newValue = fn(a1, a2, a3);+ cache2.set(a2, newValue);+ return newValue;+ }+ let cache2 = cache1.get(a1);+ if (!cache2) {+ cache2 = new WeakMap();+ cache1.set(a1, cache2);+ const newValue = fn(a1, a2, a3);+ cache2.set(a2, newValue);+ return newValue;+ }+ const cachedValue = cache2.get(a2);+ if (cachedValue === undefined) {+ const newValue = fn(a1, a2, a3);+ cache2.set(a2, newValue);+ return newValue;+ }+ return cachedValue;+ }+ return memoized;+}++class VisitSelectionSets {+ constructor(schema, initialType, visitor) {+ this.schema = schema;+ this.initialType = initialType;+ this.visitor = visitor;+ }+ transformRequest(originalRequest) {+ const document = visitSelectionSets(originalRequest, this.schema, this.initialType, this.visitor);+ return {+ ...originalRequest,+ document,+ };+ }+}+function visitSelectionSets(request, schema, initialType, visitor) {+ const { document, variables } = request;+ const operations = [];+ const fragments = Object.create(null);+ document.definitions.forEach(def => {+ if (def.kind === Kind.OPERATION_DEFINITION) {+ operations.push(def);+ }+ else if (def.kind === Kind.FRAGMENT_DEFINITION) {+ fragments[def.name.value] = def;+ }+ });+ const partialExecutionContext = {+ schema,+ variableValues: variables,+ fragments,+ };+ const typeInfo = new TypeInfo(schema, undefined, initialType);+ const newDefinitions = operations.map(operation => {+ const type = operation.operation === 'query'+ ? schema.getQueryType()+ : operation.operation === 'mutation'+ ? schema.getMutationType()+ : schema.getSubscriptionType();+ const fields = collectFields$1(partialExecutionContext, type, operation.selectionSet, Object.create(null), Object.create(null));+ const newSelections = [];+ Object.keys(fields).forEach(responseKey => {+ const fieldNodes = fields[responseKey];+ fieldNodes.forEach(fieldNode => {+ const selectionSet = fieldNode.selectionSet;+ if (selectionSet == null) {+ newSelections.push(fieldNode);+ return;+ }+ const newSelectionSet = visit(selectionSet, visitWithTypeInfo(typeInfo, {+ [Kind.SELECTION_SET]: node => visitor(node, typeInfo),+ }));+ if (newSelectionSet === selectionSet) {+ newSelections.push(fieldNode);+ return;+ }+ newSelections.push({+ ...fieldNode,+ selectionSet: newSelectionSet,+ });+ });+ });+ return {+ ...operation,+ selectionSet: {+ kind: Kind.SELECTION_SET,+ selections: newSelections,+ },+ };+ });+ Object.values(fragments).forEach(fragment => {+ newDefinitions.push(visit(fragment, visitWithTypeInfo(typeInfo, {+ [Kind.SELECTION_SET]: node => visitor(node, typeInfo),+ })));+ });+ return {+ ...document,+ definitions: newDefinitions,+ };+}++class AddSelectionSets {+ constructor(sourceSchema, initialType, selectionSetsByType, selectionSetsByField, dynamicSelectionSetsByField) {+ this.transformer = new VisitSelectionSets(sourceSchema, initialType, (node, typeInfo) => visitSelectionSet(node, typeInfo, selectionSetsByType, selectionSetsByField, dynamicSelectionSetsByField));+ }+ transformRequest(originalRequest) {+ return this.transformer.transformRequest(originalRequest);+ }+}+function visitSelectionSet(node, typeInfo, selectionSetsByType, selectionSetsByField, dynamicSelectionSetsByField) {+ const parentType = typeInfo.getParentType();+ const newSelections = new Map();+ if (parentType != null) {+ const parentTypeName = parentType.name;+ addSelectionsToMap(newSelections, node);+ if (parentTypeName in selectionSetsByType) {+ const selectionSet = selectionSetsByType[parentTypeName];+ addSelectionsToMap(newSelections, selectionSet);+ }+ if (parentTypeName in selectionSetsByField) {+ node.selections.forEach(selection => {+ if (selection.kind === Kind.FIELD) {+ const name = selection.name.value;+ const selectionSet = selectionSetsByField[parentTypeName][name];+ if (selectionSet != null) {+ addSelectionsToMap(newSelections, selectionSet);+ }+ }+ });+ }+ if (parentTypeName in dynamicSelectionSetsByField) {+ node.selections.forEach(selection => {+ if (selection.kind === Kind.FIELD) {+ const name = selection.name.value;+ const dynamicSelectionSets = dynamicSelectionSetsByField[parentTypeName][name];+ if (dynamicSelectionSets != null) {+ dynamicSelectionSets.forEach(selectionSetFn => {+ const selectionSet = selectionSetFn(selection);+ if (selectionSet != null) {+ addSelectionsToMap(newSelections, selectionSet);+ }+ });+ }+ }+ });+ }+ return {+ ...node,+ selections: Array.from(newSelections.values()),+ };+ }+}+const addSelectionsToMap = memoize2(function (map, selectionSet) {+ selectionSet.selections.forEach(selection => {+ map.set(print(selection), selection);+ });+});++class ExpandAbstractTypes {+ constructor(sourceSchema, targetSchema) {+ this.targetSchema = targetSchema;+ const { possibleTypesMap, interfaceExtensionsMap } = extractPossibleTypes(sourceSchema, targetSchema);+ this.possibleTypesMap = possibleTypesMap;+ this.reversePossibleTypesMap = flipMapping(this.possibleTypesMap);+ this.interfaceExtensionsMap = interfaceExtensionsMap;+ }+ transformRequest(originalRequest) {+ const document = expandAbstractTypes(this.targetSchema, this.possibleTypesMap, this.reversePossibleTypesMap, this.interfaceExtensionsMap, originalRequest.document);+ return {+ ...originalRequest,+ document,+ };+ }+}+function extractPossibleTypes(sourceSchema, targetSchema) {+ const typeMap = sourceSchema.getTypeMap();+ const possibleTypesMap = Object.create(null);+ const interfaceExtensionsMap = Object.create(null);+ Object.keys(typeMap).forEach(typeName => {+ const type = typeMap[typeName];+ if (isAbstractType(type)) {+ const targetType = targetSchema.getType(typeName);+ if (isInterfaceType(type) && isInterfaceType(targetType)) {+ const targetTypeFields = targetType.getFields();+ const extensionFields = Object.create(null);+ Object.keys(type.getFields()).forEach((fieldName) => {+ if (!targetTypeFields[fieldName]) {+ extensionFields[fieldName] = true;+ }+ });+ if (Object.keys(extensionFields).length) {+ interfaceExtensionsMap[typeName] = extensionFields;+ }+ }+ if (!isAbstractType(targetType) || typeName in interfaceExtensionsMap) {+ const implementations = sourceSchema.getPossibleTypes(type);+ possibleTypesMap[typeName] = implementations+ .filter(impl => targetSchema.getType(impl.name))+ .map(impl => impl.name);+ }+ }+ });+ return { possibleTypesMap, interfaceExtensionsMap };+}+function flipMapping(mapping) {+ const result = Object.create(null);+ Object.keys(mapping).forEach(typeName => {+ const toTypeNames = mapping[typeName];+ toTypeNames.forEach(toTypeName => {+ if (!(toTypeName in result)) {+ result[toTypeName] = [];+ }+ result[toTypeName].push(typeName);+ });+ });+ return result;+}+function expandAbstractTypes(targetSchema, possibleTypesMap, reversePossibleTypesMap, interfaceExtensionsMap, document) {+ const operations = document.definitions.filter(def => def.kind === Kind.OPERATION_DEFINITION);+ const fragments = document.definitions.filter(def => def.kind === Kind.FRAGMENT_DEFINITION);+ const existingFragmentNames = fragments.map(fragment => fragment.name.value);+ let fragmentCounter = 0;+ const generateFragmentName = (typeName) => {+ let fragmentName;+ do {+ fragmentName = `_${typeName}_Fragment${fragmentCounter.toString()}`;+ fragmentCounter++;+ } while (existingFragmentNames.indexOf(fragmentName) !== -1);+ return fragmentName;+ };+ const generateInlineFragment = (typeName, selectionSet) => {+ return {+ kind: Kind.INLINE_FRAGMENT,+ typeCondition: {+ kind: Kind.NAMED_TYPE,+ name: {+ kind: Kind.NAME,+ value: typeName,+ },+ },+ selectionSet,+ };+ };+ const newFragments = [];+ const fragmentReplacements = Object.create(null);+ fragments.forEach((fragment) => {+ newFragments.push(fragment);+ const possibleTypes = possibleTypesMap[fragment.typeCondition.name.value];+ if (possibleTypes != null) {+ fragmentReplacements[fragment.name.value] = [];+ possibleTypes.forEach(possibleTypeName => {+ const name = generateFragmentName(possibleTypeName);+ existingFragmentNames.push(name);+ const newFragment = {+ kind: Kind.FRAGMENT_DEFINITION,+ name: {+ kind: Kind.NAME,+ value: name,+ },+ typeCondition: {+ kind: Kind.NAMED_TYPE,+ name: {+ kind: Kind.NAME,+ value: possibleTypeName,+ },+ },+ selectionSet: fragment.selectionSet,+ };+ newFragments.push(newFragment);+ fragmentReplacements[fragment.name.value].push({+ fragmentName: name,+ typeName: possibleTypeName,+ });+ });+ }+ });+ const newDocument = {+ ...document,+ definitions: [...operations, ...newFragments],+ };+ const typeInfo = new TypeInfo(targetSchema);+ return visit(newDocument, visitWithTypeInfo(typeInfo, {+ [Kind.SELECTION_SET](node) {+ let newSelections = node.selections;+ const addedSelections = [];+ const maybeType = typeInfo.getParentType();+ if (maybeType != null) {+ const parentType = getNamedType(maybeType);+ const interfaceExtension = interfaceExtensionsMap[parentType.name];+ const interfaceExtensionFields = [];+ node.selections.forEach((selection) => {+ if (selection.kind === Kind.INLINE_FRAGMENT) {+ if (selection.typeCondition != null) {+ const possibleTypes = possibleTypesMap[selection.typeCondition.name.value];+ if (possibleTypes != null) {+ possibleTypes.forEach(possibleType => {+ const maybePossibleType = targetSchema.getType(possibleType);+ if (maybePossibleType != null &&+ implementsAbstractType(targetSchema, parentType, maybePossibleType)) {+ addedSelections.push(generateInlineFragment(possibleType, selection.selectionSet));+ }+ });+ }+ }+ }+ else if (selection.kind === Kind.FRAGMENT_SPREAD) {+ const fragmentName = selection.name.value;+ if (fragmentName in fragmentReplacements) {+ fragmentReplacements[fragmentName].forEach(replacement => {+ const typeName = replacement.typeName;+ const maybeReplacementType = targetSchema.getType(typeName);+ if (maybeReplacementType != null && implementsAbstractType(targetSchema, parentType, maybeType)) {+ addedSelections.push({+ kind: Kind.FRAGMENT_SPREAD,+ name: {+ kind: Kind.NAME,+ value: replacement.fragmentName,+ },+ });+ }+ });+ }+ }+ else if (interfaceExtension != null &&+ interfaceExtension[selection.name.value] &&+ selection.kind === Kind.FIELD) {+ interfaceExtensionFields.push(selection);+ }+ });+ if (parentType.name in reversePossibleTypesMap) {+ addedSelections.push({+ kind: Kind.FIELD,+ name: {+ kind: Kind.NAME,+ value: '__typename',+ },+ });+ }+ if (interfaceExtensionFields.length) {+ const possibleTypes = possibleTypesMap[parentType.name];+ if (possibleTypes != null) {+ possibleTypes.forEach(possibleType => {+ addedSelections.push(generateInlineFragment(possibleType, {+ kind: Kind.SELECTION_SET,+ selections: interfaceExtensionFields,+ }));+ });+ newSelections = newSelections.filter((selection) => !(selection.kind === Kind.FIELD && interfaceExtension[selection.name.value]));+ }+ }+ }+ if (addedSelections.length) {+ return {+ ...node,+ selections: newSelections.concat(addedSelections),+ };+ }+ },+ }));+}++// For motivation, see https://github.com/ardatan/graphql-tools/issues/751+class WrapConcreteTypes {+ constructor(returnType, targetSchema) {+ this.returnType = returnType;+ this.targetSchema = targetSchema;+ }+ transformRequest(originalRequest) {+ const document = wrapConcreteTypes(this.returnType, this.targetSchema, originalRequest.document);+ return {+ ...originalRequest,+ document,+ };+ }+}+function wrapConcreteTypes(returnType, targetSchema, document) {+ const namedType = getNamedType(returnType);+ if (!isObjectType(namedType)) {+ return document;+ }+ const queryRootType = targetSchema.getQueryType();+ const mutationRootType = targetSchema.getMutationType();+ const subscriptionRootType = targetSchema.getSubscriptionType();+ const typeInfo = new TypeInfo(targetSchema);+ const newDocument = visit(document, visitWithTypeInfo(typeInfo, {+ [Kind.FIELD](node) {+ const maybeType = typeInfo.getParentType();+ if (maybeType == null) {+ return false;+ }+ const parentType = getNamedType(maybeType);+ if (parentType !== queryRootType && parentType !== mutationRootType && parentType !== subscriptionRootType) {+ return false;+ }+ if (!isAbstractType(getNamedType(typeInfo.getType()))) {+ return false;+ }+ return {+ ...node,+ selectionSet: {+ kind: Kind.SELECTION_SET,+ selections: [+ {+ kind: Kind.INLINE_FRAGMENT,+ typeCondition: {+ kind: Kind.NAMED_TYPE,+ name: {+ kind: Kind.NAME,+ value: namedType.name,+ },+ },+ selectionSet: node.selectionSet,+ },+ ],+ },+ };+ },+ }));+ return newDocument;+}++class FilterToSchema {+ constructor(targetSchema) {+ this.targetSchema = targetSchema;+ }+ transformRequest(originalRequest) {+ return {+ ...originalRequest,+ ...filterToSchema(this.targetSchema, originalRequest.document, originalRequest.variables),+ };+ }+}+function filterToSchema(targetSchema, document, variables) {+ const operations = document.definitions.filter(def => def.kind === Kind.OPERATION_DEFINITION);+ const fragments = document.definitions.filter(def => def.kind === Kind.FRAGMENT_DEFINITION);+ let usedVariables = [];+ let usedFragments = [];+ const newOperations = [];+ let newFragments = [];+ const validFragments = fragments.filter((fragment) => {+ const typeName = fragment.typeCondition.name.value;+ return Boolean(targetSchema.getType(typeName));+ });+ const validFragmentsWithType = validFragments.reduce((prev, fragment) => ({+ ...prev,+ [fragment.name.value]: targetSchema.getType(fragment.typeCondition.name.value),+ }), {});+ let fragmentSet = Object.create(null);+ operations.forEach((operation) => {+ let type;+ if (operation.operation === 'subscription') {+ type = targetSchema.getSubscriptionType();+ }+ else if (operation.operation === 'mutation') {+ type = targetSchema.getMutationType();+ }+ else {+ type = targetSchema.getQueryType();+ }+ const { selectionSet, usedFragments: operationUsedFragments, usedVariables: operationUsedVariables, } = filterSelectionSet(targetSchema, type, validFragmentsWithType, operation.selectionSet);+ usedFragments = union(usedFragments, operationUsedFragments);+ const { usedVariables: collectedUsedVariables, newFragments: collectedNewFragments, fragmentSet: collectedFragmentSet, } = collectFragmentVariables(targetSchema, fragmentSet, validFragments, validFragmentsWithType, usedFragments);+ const operationOrFragmentVariables = union(operationUsedVariables, collectedUsedVariables);+ usedVariables = union(usedVariables, operationOrFragmentVariables);+ newFragments = collectedNewFragments;+ fragmentSet = collectedFragmentSet;+ const variableDefinitions = operation.variableDefinitions.filter((variable) => operationOrFragmentVariables.indexOf(variable.variable.name.value) !== -1);+ newOperations.push({+ kind: Kind.OPERATION_DEFINITION,+ operation: operation.operation,+ name: operation.name,+ directives: operation.directives,+ variableDefinitions,+ selectionSet,+ });+ });+ const newVariables = usedVariables.reduce((acc, variableName) => {+ const variableValue = variables[variableName];+ if (variableValue !== undefined) {+ acc[variableName] = variableValue;+ }+ return acc;+ }, {});+ return {+ document: {+ kind: Kind.DOCUMENT,+ definitions: [...newOperations, ...newFragments],+ },+ variables: newVariables,+ };+}+function collectFragmentVariables(targetSchema, fragmentSet, validFragments, validFragmentsWithType, usedFragments) {+ let remainingFragments = usedFragments.slice();+ let usedVariables = [];+ const newFragments = [];+ while (remainingFragments.length !== 0) {+ const nextFragmentName = remainingFragments.pop();+ const fragment = validFragments.find(fr => fr.name.value === nextFragmentName);+ if (fragment != null) {+ const name = nextFragmentName;+ const typeName = fragment.typeCondition.name.value;+ const type = targetSchema.getType(typeName);+ const { selectionSet, usedFragments: fragmentUsedFragments, usedVariables: fragmentUsedVariables, } = filterSelectionSet(targetSchema, type, validFragmentsWithType, fragment.selectionSet);+ remainingFragments = union(remainingFragments, fragmentUsedFragments);+ usedVariables = union(usedVariables, fragmentUsedVariables);+ if (!(name in fragmentSet)) {+ fragmentSet[name] = true;+ newFragments.push({+ kind: Kind.FRAGMENT_DEFINITION,+ name: {+ kind: Kind.NAME,+ value: name,+ },+ typeCondition: fragment.typeCondition,+ selectionSet,+ });+ }+ }+ }+ return {+ usedVariables,+ newFragments,+ fragmentSet,+ };+}+function filterSelectionSet(schema, type, validFragments, selectionSet) {+ const usedFragments = [];+ const usedVariables = [];+ const typeInfo = new TypeInfo(schema, undefined, type);+ const filteredSelectionSet = visit(selectionSet, visitWithTypeInfo(typeInfo, {+ [Kind.FIELD]: {+ enter(node) {+ const parentType = typeInfo.getParentType();+ if (isObjectType(parentType) || isInterfaceType(parentType)) {+ const fields = parentType.getFields();+ const field = node.name.value === '__typename' ? TypeNameMetaFieldDef : fields[node.name.value];+ if (!field) {+ return null;+ }+ const argNames = (field.args != null ? field.args : []).map(arg => arg.name);+ if (node.arguments != null) {+ const args = node.arguments.filter((arg) => argNames.indexOf(arg.name.value) !== -1);+ if (args.length !== node.arguments.length) {+ return {+ ...node,+ arguments: args,+ };+ }+ }+ }+ },+ leave(node) {+ const resolvedType = getNamedType(typeInfo.getType());+ if (isObjectType(resolvedType) || isInterfaceType(resolvedType)) {+ const selections = node.selectionSet != null ? node.selectionSet.selections : null;+ if (selections == null || selections.length === 0) {+ // need to remove any added variables. Is there a better way to do this?+ visit(node, {+ [Kind.VARIABLE](variableNode) {+ const index = usedVariables.indexOf(variableNode.name.value);+ if (index !== -1) {+ usedVariables.splice(index, 1);+ }+ },+ });+ return null;+ }+ }+ },+ },+ [Kind.FRAGMENT_SPREAD](node) {+ if (node.name.value in validFragments) {+ const parentType = typeInfo.getParentType();+ const innerType = validFragments[node.name.value];+ if (!implementsAbstractType(schema, parentType, innerType)) {+ return null;+ }+ usedFragments.push(node.name.value);+ return;+ }+ return null;+ },+ [Kind.INLINE_FRAGMENT]: {+ enter(node) {+ if (node.typeCondition != null) {+ const parentType = typeInfo.getParentType();+ const innerType = schema.getType(node.typeCondition.name.value);+ if (!implementsAbstractType(schema, parentType, innerType)) {+ return null;+ }+ }+ },+ },+ [Kind.VARIABLE](node) {+ usedVariables.push(node.name.value);+ },+ }));+ return {+ selectionSet: filteredSelectionSet,+ usedFragments,+ usedVariables,+ };+}+function union(...arrays) {+ const cache = Object.create(null);+ const result = [];+ arrays.forEach(array => {+ array.forEach(item => {+ if (!(item in cache)) {+ cache[item] = true;+ result.push(item);+ }+ });+ });+ return result;+}++class AddFragmentsByField {+ constructor(targetSchema, mapping) {+ this.targetSchema = targetSchema;+ this.mapping = mapping;+ }+ transformRequest(originalRequest) {+ const document = addFragmentsByField(this.targetSchema, originalRequest.document, this.mapping);+ return {+ ...originalRequest,+ document,+ };+ }+}+function addFragmentsByField(targetSchema, document, mapping) {+ const typeInfo = new TypeInfo(targetSchema);+ return visit(document, visitWithTypeInfo(typeInfo, {+ [Kind.SELECTION_SET](node) {+ const parentType = typeInfo.getParentType();+ if (parentType != null) {+ const parentTypeName = parentType.name;+ let selections = node.selections;+ if (parentTypeName in mapping) {+ node.selections.forEach(selection => {+ if (selection.kind === Kind.FIELD) {+ const name = selection.name.value;+ const fragment = mapping[parentTypeName][name];+ if (fragment != null) {+ selections = selections.concat(fragment);+ }+ }+ });+ }+ if (selections !== node.selections) {+ return {+ ...node,+ selections,+ };+ }+ }+ },+ }));+}++class AddTypenameToAbstract {+ constructor(targetSchema) {+ this.targetSchema = targetSchema;+ }+ transformRequest(originalRequest) {+ const document = addTypenameToAbstract(this.targetSchema, originalRequest.document);+ return {+ ...originalRequest,+ document,+ };+ }+}+function addTypenameToAbstract(targetSchema, document) {+ const typeInfo = new TypeInfo(targetSchema);+ return visit(document, visitWithTypeInfo(typeInfo, {+ [Kind.SELECTION_SET](node) {+ const parentType = typeInfo.getParentType();+ let selections = node.selections;+ if (parentType != null && isAbstractType(parentType)) {+ selections = selections.concat({+ kind: Kind.FIELD,+ name: {+ kind: Kind.NAME,+ value: '__typename',+ },+ });+ }+ if (selections !== node.selections) {+ return {+ ...node,+ selections,+ };+ }+ },+ }));+}++function handleNull(errors) {+ if (errors.length) {+ if (errors.some(error => !error.path || error.path.length < 2)) {+ if (errors.length > 1) {+ const combinedError = new AggregateError(errors);+ return combinedError;+ }+ const error = errors[0];+ return error.originalError || relocatedError(error, null);+ }+ else if (errors.some(error => typeof error.path[1] === 'string')) {+ const childErrors = getErrorsByPathSegment(errors);+ const result = {};+ Object.keys(childErrors).forEach(pathSegment => {+ result[pathSegment] = handleNull(childErrors[pathSegment]);+ });+ return result;+ }+ const childErrors = getErrorsByPathSegment(errors);+ const result = [];+ Object.keys(childErrors).forEach(pathSegment => {+ result.push(handleNull(childErrors[pathSegment]));+ });+ return result;+ }+ return null;+}++function mergeProxiedResults(target, ...sources) {+ const results = [];+ const errors = [];+ sources.forEach(source => {+ if (source instanceof Error) {+ errors.push(source);+ }+ else {+ results.push(source);+ errors.push(source[ERROR_SYMBOL]);+ }+ });+ const fieldSubschemaMap = results.reduce((acc, source) => {+ const subschema = source[OBJECT_SUBSCHEMA_SYMBOL];+ Object.keys(source).forEach(key => {+ acc[key] = subschema;+ });+ return acc;+ }, {});+ const result = results.reduce(mergeDeep, target);+ result[FIELD_SUBSCHEMA_MAP_SYMBOL] = target[FIELD_SUBSCHEMA_MAP_SYMBOL]+ ? Object.assign({}, target[FIELD_SUBSCHEMA_MAP_SYMBOL], fieldSubschemaMap)+ : fieldSubschemaMap;+ result[ERROR_SYMBOL] = target[ERROR_SYMBOL].concat(...errors);+ return result;+}++const sortSubschemasByProxiability = memoize4(function (mergedTypeInfo, sourceSubschemaOrSourceSubschemas, targetSubschemas, fieldNodes) {+ // 1. calculate if possible to delegate to given subschema+ const proxiableSubschemas = [];+ const nonProxiableSubschemas = [];+ targetSubschemas.forEach(t => {+ const selectionSet = mergedTypeInfo.selectionSets.get(t);+ const fieldSelectionSets = mergedTypeInfo.fieldSelectionSets.get(t);+ if (selectionSet != null &&+ !subschemaTypesContainSelectionSet(mergedTypeInfo, sourceSubschemaOrSourceSubschemas, selectionSet)) {+ nonProxiableSubschemas.push(t);+ }+ else {+ if (fieldSelectionSets == null ||+ fieldNodes.every(fieldNode => {+ const fieldName = fieldNode.name.value;+ const fieldSelectionSet = fieldSelectionSets[fieldName];+ return (fieldSelectionSet == null ||+ subschemaTypesContainSelectionSet(mergedTypeInfo, sourceSubschemaOrSourceSubschemas, fieldSelectionSet));+ })) {+ proxiableSubschemas.push(t);+ }+ else {+ nonProxiableSubschemas.push(t);+ }+ }+ });+ return {+ proxiableSubschemas,+ nonProxiableSubschemas,+ };+});+const buildDelegationPlan = memoize3$1(function (mergedTypeInfo, fieldNodes, proxiableSubschemas) {+ const { uniqueFields, nonUniqueFields } = mergedTypeInfo;+ const unproxiableFieldNodes = [];+ // 2. for each selection:+ const delegationMap = new Map();+ fieldNodes.forEach(fieldNode => {+ if (fieldNode.name.value === '__typename') {+ return;+ }+ // 2a. use uniqueFields map to assign fields to subschema if one of possible subschemas+ const uniqueSubschema = uniqueFields[fieldNode.name.value];+ if (uniqueSubschema != null) {+ if (!proxiableSubschemas.includes(uniqueSubschema)) {+ unproxiableFieldNodes.push(fieldNode);+ return;+ }+ const existingSubschema = delegationMap.get(uniqueSubschema);+ if (existingSubschema != null) {+ existingSubschema.push(fieldNode);+ }+ else {+ delegationMap.set(uniqueSubschema, [fieldNode]);+ }+ return;+ }+ // 2b. use nonUniqueFields to assign to a possible subschema,+ // preferring one of the subschemas already targets of delegation+ let nonUniqueSubschemas = nonUniqueFields[fieldNode.name.value];+ if (nonUniqueSubschemas == null) {+ unproxiableFieldNodes.push(fieldNode);+ return;+ }+ nonUniqueSubschemas = nonUniqueSubschemas.filter(s => proxiableSubschemas.includes(s));+ if (nonUniqueSubschemas == null) {+ unproxiableFieldNodes.push(fieldNode);+ return;+ }+ const subschemas = Array.from(delegationMap.keys());+ const existingSubschema = nonUniqueSubschemas.find(s => subschemas.includes(s));+ if (existingSubschema != null) {+ delegationMap.get(existingSubschema).push(fieldNode);+ }+ else {+ delegationMap.set(nonUniqueSubschemas[0], [fieldNode]);+ }+ });+ const finalDelegationMap = new Map();+ delegationMap.forEach((selections, subschema) => {+ finalDelegationMap.set(subschema, {+ kind: Kind.SELECTION_SET,+ selections,+ });+ });+ return {+ delegationMap: finalDelegationMap,+ unproxiableFieldNodes,+ };+});+const combineSubschemas = memoize2(function (subschemaOrSubschemas, additionalSubschemas) {+ return Array.isArray(subschemaOrSubschemas)+ ? subschemaOrSubschemas.concat(additionalSubschemas)+ : [subschemaOrSubschemas].concat(additionalSubschemas);+});+function mergeFields$2(mergedTypeInfo, typeName, object, fieldNodes, sourceSubschemaOrSourceSubschemas, targetSubschemas, context, info) {+ if (!fieldNodes.length) {+ return object;+ }+ const { proxiableSubschemas, nonProxiableSubschemas } = sortSubschemasByProxiability(mergedTypeInfo, sourceSubschemaOrSourceSubschemas, targetSubschemas, fieldNodes);+ const { delegationMap, unproxiableFieldNodes } = buildDelegationPlan(mergedTypeInfo, fieldNodes, proxiableSubschemas);+ if (!delegationMap.size) {+ return object;+ }+ let containsPromises = false;+ const maybePromises = [];+ delegationMap.forEach((selectionSet, s) => {+ const maybePromise = s.merge[typeName].resolve(object, context, info, s, selectionSet);+ maybePromises.push(maybePromise);+ if (!containsPromises && isPromise_1(maybePromise)) {+ containsPromises = true;+ }+ });+ return containsPromises+ ? Promise.all(maybePromises).then(results => mergeFields$2(mergedTypeInfo, typeName, mergeProxiedResults(object, ...results), unproxiableFieldNodes, combineSubschemas(sourceSubschemaOrSourceSubschemas, proxiableSubschemas), nonProxiableSubschemas, context, info))+ : mergeFields$2(mergedTypeInfo, typeName, mergeProxiedResults(object, ...maybePromises), unproxiableFieldNodes, combineSubschemas(sourceSubschemaOrSourceSubschemas, proxiableSubschemas), nonProxiableSubschemas, context, info);+}+const subschemaTypesContainSelectionSet = memoize3$1(function (mergedTypeInfo, sourceSubschemaOrSourceSubschemas, selectionSet) {+ if (Array.isArray(sourceSubschemaOrSourceSubschemas)) {+ return typesContainSelectionSet(sourceSubschemaOrSourceSubschemas.map(sourceSubschema => sourceSubschema.schema.getType(mergedTypeInfo.typeName)), selectionSet);+ }+ return typesContainSelectionSet([sourceSubschemaOrSourceSubschemas.schema.getType(mergedTypeInfo.typeName)], selectionSet);+});++function collectSubFields(info, typeName) {+ let subFieldNodes = Object.create(null);+ const visitedFragmentNames = Object.create(null);+ const type = info.schema.getType(typeName);+ const partialExecutionContext = {+ schema: info.schema,+ variableValues: info.variableValues,+ fragments: info.fragments,+ };+ info.fieldNodes.forEach(fieldNode => {+ subFieldNodes = collectFields$1(partialExecutionContext, type, fieldNode.selectionSet, subFieldNodes, visitedFragmentNames);+ });+ const stitchingInfo = info.schema.extensions.stitchingInfo;+ const selectionSetsByField = stitchingInfo.selectionSetsByField;+ Object.keys(subFieldNodes).forEach(responseName => {+ var _a;+ const fieldName = subFieldNodes[responseName][0].name.value;+ const fieldSelectionSet = (_a = selectionSetsByField === null || selectionSetsByField === void 0 ? void 0 : selectionSetsByField[typeName]) === null || _a === void 0 ? void 0 : _a[fieldName];+ if (fieldSelectionSet != null) {+ subFieldNodes = collectFields$1(partialExecutionContext, type, fieldSelectionSet, subFieldNodes, visitedFragmentNames);+ }+ });+ return subFieldNodes;+}+const getFieldsNotInSubschema = memoizeInfoAnd2Objects(function (info, subschema, mergedTypeInfo) {+ const typeMap = isSubschemaConfig(subschema) ? mergedTypeInfo.typeMaps.get(subschema) : subschema.getTypeMap();+ const typeName = mergedTypeInfo.typeName;+ const fields = typeMap[typeName].getFields();+ const subFieldNodes = collectSubFields(info, typeName);+ let fieldsNotInSchema = [];+ Object.keys(subFieldNodes).forEach(responseName => {+ const fieldName = subFieldNodes[responseName][0].name.value;+ if (!(fieldName in fields)) {+ fieldsNotInSchema = fieldsNotInSchema.concat(subFieldNodes[responseName]);+ }+ });+ return fieldsNotInSchema;+});++function handleObject(type, object, errors, subschema, context, info, skipTypeMerging) {+ var _a;+ const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;+ setErrors(object, errors.map(error => slicedError(error)));+ setObjectSubschema(object, subschema);+ if (skipTypeMerging || !stitchingInfo) {+ return object;+ }+ const typeName = isAbstractType(type) ? info.schema.getTypeMap()[object.__typename].name : type.name;+ const mergedTypeInfo = stitchingInfo.mergedTypes[typeName];+ let targetSubschemas;+ if (mergedTypeInfo != null) {+ targetSubschemas = mergedTypeInfo.targetSubschemas.get(subschema);+ }+ if (!targetSubschemas) {+ return object;+ }+ const fieldNodes = getFieldsNotInSubschema(info, subschema, mergedTypeInfo);+ return mergeFields$2(mergedTypeInfo, typeName, object, fieldNodes, subschema, targetSubschemas, context, info);+}++function handleList(type, list, errors, subschema, context, info, skipTypeMerging) {+ const childErrors = getErrorsByPathSegment(errors);+ return list.map((listMember, index) => handleListMember(getNullableType(type.ofType), listMember, index in childErrors ? childErrors[index] : [], subschema, context, info, skipTypeMerging));+}+function handleListMember(type, listMember, errors, subschema, context, info, skipTypeMerging) {+ if (listMember == null) {+ return handleNull(errors);+ }+ if (isLeafType(type)) {+ return type.parseValue(listMember);+ }+ else if (isCompositeType(type)) {+ return handleObject(type, listMember, errors, subschema, context, info, skipTypeMerging);+ }+ else if (isListType(type)) {+ return handleList(type, listMember, errors, subschema, context, info, skipTypeMerging);+ }+}++function handleResult(result, errors, subschema, context, info, returnType = info.returnType, skipTypeMerging) {+ const type = getNullableType(returnType);+ if (result == null) {+ return handleNull(errors);+ }+ if (isLeafType(type)) {+ return type.parseValue(result);+ }+ else if (isCompositeType(type)) {+ return handleObject(type, result, errors, subschema, context, info, skipTypeMerging);+ }+ else if (isListType(type)) {+ return handleList(type, result, errors, subschema, context, info, skipTypeMerging);+ }+}++class CheckResultAndHandleErrors {+ constructor(info, fieldName, subschema, context, returnType = info.returnType, typeMerge) {+ this.context = context;+ this.info = info;+ this.fieldName = fieldName;+ this.subschema = subschema;+ this.returnType = returnType;+ this.typeMerge = typeMerge;+ }+ transformResult(result) {+ return checkResultAndHandleErrors(result, this.context != null ? this.context : {}, this.info, this.fieldName, this.subschema, this.returnType, this.typeMerge);+ }+}+function checkResultAndHandleErrors(result, context, info, responseKey = getResponseKeyFromInfo(info), subschema, returnType = info.returnType, skipTypeMerging) {+ const errors = result.errors != null ? result.errors : [];+ const data = result.data != null ? result.data[responseKey] : undefined;+ return handleResult(data, errors, subschema, context, info, returnType, skipTypeMerging);+}++class AddArgumentsAsVariables {+ constructor(targetSchema, args) {+ this.targetSchema = targetSchema;+ this.args = Object.entries(args).reduce((prev, [key, val]) => ({+ ...prev,+ [key]: val,+ }), {});+ }+ transformRequest(originalRequest) {+ const { document, variables } = addVariablesToRootField(this.targetSchema, originalRequest, this.args);+ return {+ ...originalRequest,+ document,+ variables,+ };+ }+}+function addVariablesToRootField(targetSchema, originalRequest, args) {+ const document = originalRequest.document;+ const variableValues = originalRequest.variables;+ const operations = document.definitions.filter(def => def.kind === Kind.OPERATION_DEFINITION);+ const fragments = document.definitions.filter(def => def.kind === Kind.FRAGMENT_DEFINITION);+ const newOperations = operations.map((operation) => {+ const variableDefinitionMap = operation.variableDefinitions.reduce((prev, def) => ({+ ...prev,+ [def.variable.name.value]: def,+ }), {});+ let type;+ if (operation.operation === 'subscription') {+ type = targetSchema.getSubscriptionType();+ }+ else if (operation.operation === 'mutation') {+ type = targetSchema.getMutationType();+ }+ else {+ type = targetSchema.getQueryType();+ }+ const newSelectionSet = [];+ operation.selectionSet.selections.forEach((selection) => {+ if (selection.kind === Kind.FIELD) {+ const argumentNodes = selection.arguments;+ const argumentNodeMap = argumentNodes.reduce((prev, argument) => ({+ ...prev,+ [argument.name.value]: argument,+ }), {});+ const targetField = type.getFields()[selection.name.value];+ // excludes __typename+ if (targetField != null) {+ updateArguments(targetField, argumentNodeMap, variableDefinitionMap, variableValues, args);+ }+ newSelectionSet.push({+ ...selection,+ arguments: Object.keys(argumentNodeMap).map(argName => argumentNodeMap[argName]),+ });+ }+ else {+ newSelectionSet.push(selection);+ }+ });+ return {+ ...operation,+ variableDefinitions: Object.keys(variableDefinitionMap).map(varName => variableDefinitionMap[varName]),+ selectionSet: {+ kind: Kind.SELECTION_SET,+ selections: newSelectionSet,+ },+ };+ });+ return {+ document: {+ ...document,+ definitions: [...newOperations, ...fragments],+ },+ variables: variableValues,+ };+}+function updateArguments(targetField, argumentNodeMap, variableDefinitionMap, variableValues, newArgs) {+ targetField.args.forEach((argument) => {+ const argName = argument.name;+ const argType = argument.type;+ if (argName in newArgs) {+ updateArgument(argName, argType, argumentNodeMap, variableDefinitionMap, variableValues, serializeInputValue(argType, newArgs[argName]));+ }+ });+}++function defaultDelegationBinding(delegationContext) {+ var _a;+ const { subschema: schemaOrSubschemaConfig, targetSchema, fieldName, args, context, info, returnType, transforms = [], skipTypeMerging, } = delegationContext;+ const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;+ let transformedSchema = stitchingInfo === null || stitchingInfo === void 0 ? void 0 : stitchingInfo.transformedSchemas.get(schemaOrSubschemaConfig);+ if (transformedSchema != null) {+ delegationContext.transformedSchema = transformedSchema;+ }+ else {+ transformedSchema = delegationContext.transformedSchema;+ }+ let delegationTransforms = [+ new CheckResultAndHandleErrors(info, fieldName, schemaOrSubschemaConfig, context, returnType, skipTypeMerging),+ ];+ if (stitchingInfo != null) {+ delegationTransforms = delegationTransforms.concat([+ new AddSelectionSets(info.schema, returnType, {}, stitchingInfo.selectionSetsByField, stitchingInfo.dynamicSelectionSetsByField),+ new WrapConcreteTypes(returnType, transformedSchema),+ new ExpandAbstractTypes(info.schema, transformedSchema),+ ]);+ }+ else if (info != null) {+ delegationTransforms = delegationTransforms.concat([+ new WrapConcreteTypes(returnType, transformedSchema),+ new ExpandAbstractTypes(info.schema, transformedSchema),+ ]);+ }+ else {+ delegationTransforms.push(new WrapConcreteTypes(returnType, transformedSchema));+ }+ delegationTransforms = delegationTransforms.concat(transforms.slice().reverse());+ if (stitchingInfo != null) {+ delegationTransforms.push(new AddFragmentsByField(targetSchema, stitchingInfo.fragmentsByField));+ }+ if (args != null) {+ delegationTransforms.push(new AddArgumentsAsVariables(targetSchema, args));+ }+ delegationTransforms = delegationTransforms.concat([+ new FilterToSchema(targetSchema),+ new AddTypenameToAbstract(targetSchema),+ ]);+ return delegationTransforms;+}++class Transformer {+ constructor(context, binding = defaultDelegationBinding) {+ this.transformations = [];+ this.delegationContext = context;+ const delegationTransforms = binding(this.delegationContext);+ delegationTransforms.forEach(transform => this.addTransform(transform, {}));+ }+ addTransform(transform, context = {}) {+ this.transformations.push({ transform, context });+ }+ transformRequest(originalRequest) {+ return this.transformations.reduce((request, transformation) => transformation.transform.transformRequest != null+ ? transformation.transform.transformRequest(request, this.delegationContext, transformation.context)+ : request, originalRequest);+ }+ transformResult(originalResult) {+ return this.transformations.reduceRight((result, transformation) => transformation.transform.transformResult != null+ ? transformation.transform.transformResult(result, this.delegationContext, transformation.context)+ : result, originalResult);+ }+}++// adapted from https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js+function createPrefix(index) {+ return `graphqlTools${index}_`;+}+function parseKey(prefixedKey) {+ const match = /^graphqlTools([\d]+)_(.*)$/.exec(prefixedKey);+ if (match && match.length === 3 && !isNaN(Number(match[1])) && match[2]) {+ return { index: Number(match[1]), originalKey: match[2] };+ }+ return null;+}++// adapted from https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js+/**+ * Merge multiple queries into a single query in such a way that query results+ * can be split and transformed as if they were obtained by running original queries.+ *+ * Merging algorithm involves several transformations:+ * 1. Replace top-level fragment spreads with inline fragments (... on Query {})+ * 2. Add unique aliases to all top-level query fields (including those on inline fragments)+ * 3. Prefix all variable definitions and variable usages+ * 4. Prefix names (and spreads) of fragments+ *+ * i.e transform:+ * [+ * `query Foo($id: ID!) { foo, bar(id: $id), ...FooQuery }+ * fragment FooQuery on Query { baz }`,+ *+ * `query Bar($id: ID!) { foo: baz, bar(id: $id), ... on Query { baz } }`+ * ]+ * to:+ * query (+ * $graphqlTools1_id: ID!+ * $graphqlTools2_id: ID!+ * ) {+ * graphqlTools1_foo: foo,+ * graphqlTools1_bar: bar(id: $graphqlTools1_id)+ * ... on Query {+ * graphqlTools1__baz: baz+ * }+ * graphqlTools1__foo: baz+ * graphqlTools1__bar: bar(id: $graphqlTools1__id)+ * ... on Query {+ * graphqlTools1__baz: baz+ * }+ * }+ */+function mergeExecutionParams(execs, extensionsReducer) {+ const mergedVariables = Object.create(null);+ const mergedVariableDefinitions = [];+ const mergedSelections = [];+ const mergedFragmentDefinitions = [];+ let mergedExtensions = Object.create(null);+ let operation;+ execs.forEach((executionParams, index) => {+ const prefixedExecutionParams = prefixExecutionParams(createPrefix(index), executionParams);+ prefixedExecutionParams.document.definitions.forEach(def => {+ var _a;+ if (isOperationDefinition(def)) {+ operation = def.operation;+ mergedSelections.push(...def.selectionSet.selections);+ mergedVariableDefinitions.push(...((_a = def.variableDefinitions) !== null && _a !== void 0 ? _a : []));+ }+ if (isFragmentDefinition(def)) {+ mergedFragmentDefinitions.push(def);+ }+ });+ Object.assign(mergedVariables, prefixedExecutionParams.variables);+ mergedExtensions = extensionsReducer(mergedExtensions, executionParams);+ });+ const mergedOperationDefinition = {+ kind: Kind.OPERATION_DEFINITION,+ operation,+ variableDefinitions: mergedVariableDefinitions,+ selectionSet: {+ kind: Kind.SELECTION_SET,+ selections: mergedSelections,+ },+ };+ return {+ document: {+ kind: Kind.DOCUMENT,+ definitions: [mergedOperationDefinition, ...mergedFragmentDefinitions],+ },+ variables: mergedVariables,+ extensions: mergedExtensions,+ context: execs[0].context,+ info: execs[0].info,+ };+}+function prefixExecutionParams(prefix, executionParams) {+ let document = aliasTopLevelFields(prefix, executionParams.document);+ const variableNames = Object.keys(executionParams.variables);+ if (variableNames.length === 0) {+ return { ...executionParams, document };+ }+ document = visit(document, {+ [Kind.VARIABLE]: (node) => prefixNodeName(node, prefix),+ [Kind.FRAGMENT_DEFINITION]: (node) => prefixNodeName(node, prefix),+ [Kind.FRAGMENT_SPREAD]: (node) => prefixNodeName(node, prefix),+ });+ const prefixedVariables = variableNames.reduce((acc, name) => {+ acc[prefix + name] = executionParams.variables[name];+ return acc;+ }, Object.create(null));+ return {+ document,+ variables: prefixedVariables,+ };+}+/**+ * Adds prefixed aliases to top-level fields of the query.+ *+ * @see aliasFieldsInSelection for implementation details+ */+function aliasTopLevelFields(prefix, document) {+ const transformer = {+ [Kind.OPERATION_DEFINITION]: (def) => {+ const { selections } = def.selectionSet;+ return {+ ...def,+ selectionSet: {+ ...def.selectionSet,+ selections: aliasFieldsInSelection(prefix, selections, document),+ },+ };+ },+ };+ return visit(document, transformer, { [Kind.DOCUMENT]: [`definitions`] });+}+/**+ * Add aliases to fields of the selection, including top-level fields of inline fragments.+ * Fragment spreads are converted to inline fragments and their top-level fields are also aliased.+ *+ * Note that this method is shallow. It adds aliases only to the top-level fields and doesn't+ * descend to field sub-selections.+ *+ * For example, transforms:+ * {+ * foo+ * ... on Query { foo }+ * ...FragmentWithBarField+ * }+ * To:+ * {+ * graphqlTools1_foo: foo+ * ... on Query { graphqlTools1_foo: foo }+ * ... on Query { graphqlTools1_bar: bar }+ * }+ */+function aliasFieldsInSelection(prefix, selections, document) {+ return selections.map(selection => {+ switch (selection.kind) {+ case Kind.INLINE_FRAGMENT:+ return aliasFieldsInInlineFragment(prefix, selection, document);+ case Kind.FRAGMENT_SPREAD: {+ const inlineFragment = inlineFragmentSpread(selection, document);+ return aliasFieldsInInlineFragment(prefix, inlineFragment, document);+ }+ case Kind.FIELD:+ default:+ return aliasField(selection, prefix);+ }+ });+}+/**+ * Add aliases to top-level fields of the inline fragment.+ * Returns new inline fragment node.+ *+ * For Example, transforms:+ * ... on Query { foo, ... on Query { bar: foo } }+ * To+ * ... on Query { graphqlTools1_foo: foo, ... on Query { graphqlTools1_bar: foo } }+ */+function aliasFieldsInInlineFragment(prefix, fragment, document) {+ const { selections } = fragment.selectionSet;+ return {+ ...fragment,+ selectionSet: {+ ...fragment.selectionSet,+ selections: aliasFieldsInSelection(prefix, selections, document),+ },+ };+}+/**+ * Replaces fragment spread with inline fragment+ *+ * Example:+ * query { ...Spread }+ * fragment Spread on Query { bar }+ *+ * Transforms to:+ * query { ... on Query { bar } }+ */+function inlineFragmentSpread(spread, document) {+ const fragment = document.definitions.find(def => isFragmentDefinition(def) && def.name.value === spread.name.value);+ if (!fragment) {+ throw new Error(`Fragment ${spread.name.value} does not exist`);+ }+ const { typeCondition, selectionSet } = fragment;+ return {+ kind: Kind.INLINE_FRAGMENT,+ typeCondition,+ selectionSet,+ directives: spread.directives,+ };+}+function prefixNodeName(namedNode, prefix) {+ return {+ ...namedNode,+ name: {+ ...namedNode.name,+ value: prefix + namedNode.name.value,+ },+ };+}+/**+ * Returns a new FieldNode with prefixed alias+ *+ * Example. Given prefix === "graphqlTools1_" transforms:+ * { foo } -> { graphqlTools1_foo: foo }+ * { foo: bar } -> { graphqlTools1_foo: bar }+ */+function aliasField(field, aliasPrefix) {+ const aliasNode = field.alias ? field.alias : field.name;+ return {+ ...field,+ alias: {+ ...aliasNode,+ value: aliasPrefix + aliasNode.value,+ },+ };+}+function isOperationDefinition(def) {+ return def.kind === Kind.OPERATION_DEFINITION;+}+function isFragmentDefinition(def) {+ return def.kind === Kind.FRAGMENT_DEFINITION;+}++// adapted from https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js+/**+ * Split and transform result of the query produced by the `merge` function+ */+function splitResult(mergedResult, numResults) {+ const splitResults = [];+ for (let i = 0; i < numResults; i++) {+ splitResults.push({});+ }+ const data = mergedResult.data;+ if (data) {+ Object.keys(data).forEach(prefixedKey => {+ const { index, originalKey } = parseKey(prefixedKey);+ if (!splitResults[index].data) {+ splitResults[index].data = { [originalKey]: data[prefixedKey] };+ }+ else {+ splitResults[index].data[originalKey] = data[prefixedKey];+ }+ });+ }+ const errors = mergedResult.errors;+ if (errors) {+ const newErrors = Object.create(null);+ errors.forEach(error => {+ if (error.path) {+ const parsedKey = parseKey(error.path[0]);+ if (parsedKey) {+ const { index, originalKey } = parsedKey;+ const newError = relocatedError(error, [originalKey, ...error.path.slice(1)]);+ if (!newErrors[index]) {+ newErrors[index] = [newError];+ }+ else {+ newErrors[index].push(newError);+ }+ return;+ }+ }+ splitResults.forEach((_splitResult, index) => {+ if (!newErrors[index]) {+ newErrors[index] = [error];+ }+ else {+ newErrors[index].push(error);+ }+ });+ });+ Object.keys(newErrors).forEach(index => {+ splitResults[index].errors = newErrors[index];+ });+ }+ return splitResults;+}++const getBatchingExecutor = memoize2of3(function (_context, endpoint, executor) {+ var _a, _b, _c;+ const loader = new dataloader(createLoadFn(executor !== null && executor !== void 0 ? executor : endpoint.executor, (_b = (_a = endpoint.batchingOptions) === null || _a === void 0 ? void 0 : _a.extensionsReducer) !== null && _b !== void 0 ? _b : defaultExtensionsReducer), (_c = endpoint.batchingOptions) === null || _c === void 0 ? void 0 : _c.dataLoaderOptions);+ return (executionParams) => loader.load(executionParams);+});+function createLoadFn(executor, extensionsReducer) {+ return async (execs) => {+ const execBatches = [];+ let index = 0;+ const exec = execs[index];+ let currentBatch = [exec];+ execBatches.push(currentBatch);+ const operationType = getOperationAST(exec.document, undefined).operation;+ while (++index < execs.length) {+ const currentOperationType = getOperationAST(execs[index].document, undefined).operation;+ if (operationType === currentOperationType) {+ currentBatch.push(execs[index]);+ }+ else {+ currentBatch = [execs[index]];+ execBatches.push(currentBatch);+ }+ }+ let containsPromises = false;+ const executionResults = [];+ execBatches.forEach(execBatch => {+ const mergedExecutionParams = mergeExecutionParams(execBatch, extensionsReducer);+ const executionResult = executor(mergedExecutionParams);+ if (isPromise_1(executionResult)) {+ containsPromises = true;+ }+ executionResults.push(executionResult);+ });+ if (containsPromises) {+ return Promise.all(executionResults).then(resultBatches => {+ let results = [];+ resultBatches.forEach((resultBatch, index) => {+ results = results.concat(splitResult(resultBatch, execBatches[index].length));+ });+ return results;+ });+ }+ let results = [];+ executionResults.forEach((resultBatch, index) => {+ results = results.concat(splitResult(resultBatch, execBatches[index].length));+ });+ return results;+ };+}+function defaultExtensionsReducer(mergedExtensions, executionParams) {+ const newExtensions = executionParams.extensions;+ if (newExtensions != null) {+ Object.assign(mergedExtensions, newExtensions);+ }+ return mergedExtensions;+}++function delegateToSchema(options) {+ if (isSchema(options)) {+ throw new Error('Passing positional arguments to delegateToSchema is deprecated. ' + 'Please pass named parameters instead.');+ }+ const { info, operationName, operation = getDelegatingOperation(info.parentType, info.schema), fieldName = info.fieldName, returnType = info.returnType, selectionSet, fieldNodes, } = options;+ const request = createRequestFromInfo({+ info,+ operation,+ fieldName,+ selectionSet,+ fieldNodes,+ operationName,+ });+ return delegateRequest({+ ...options,+ request,+ operation,+ fieldName,+ returnType,+ });+}+function getDelegationReturnType(targetSchema, operation, fieldName) {+ let rootType;+ if (operation === 'query') {+ rootType = targetSchema.getQueryType();+ }+ else if (operation === 'mutation') {+ rootType = targetSchema.getMutationType();+ }+ else {+ rootType = targetSchema.getSubscriptionType();+ }+ return rootType.getFields()[fieldName].type;+}+function delegateRequest({ request, schema: subschemaOrSubschemaConfig, rootValue, info, operation, fieldName, args, returnType, context, transforms = [], transformedSchema, skipValidation, skipTypeMerging, binding, }) {+ var _a, _b, _c;+ let operationDefinition;+ let targetOperation;+ let targetFieldName;+ if (operation == null) {+ operationDefinition = getOperationAST(request.document, undefined);+ targetOperation = operationDefinition.operation;+ }+ else {+ targetOperation = operation;+ }+ if (fieldName == null) {+ operationDefinition = operationDefinition !== null && operationDefinition !== void 0 ? operationDefinition : getOperationAST(request.document, undefined);+ targetFieldName = operationDefinition.selectionSet.selections[0].name.value;+ }+ else {+ targetFieldName = fieldName;+ }+ let targetSchema;+ let targetRootValue;+ let subschemaConfig;+ let endpoint;+ let allTransforms;+ if (isSubschemaConfig(subschemaOrSubschemaConfig)) {+ const stitchingInfo = (_a = info === null || info === void 0 ? void 0 : info.schema.extensions) === null || _a === void 0 ? void 0 : _a.stitchingInfo;+ if (stitchingInfo) {+ const processedSubschema = stitchingInfo.transformedSubschemaConfigs.get(subschemaOrSubschemaConfig);+ subschemaConfig = processedSubschema != null ? processedSubschema : subschemaOrSubschemaConfig;+ }+ else {+ subschemaConfig = subschemaOrSubschemaConfig;+ }+ targetSchema = subschemaConfig.schema;+ allTransforms = subschemaConfig.transforms != null ? subschemaConfig.transforms.concat(transforms) : transforms;+ if (subschemaConfig.endpoint != null) {+ endpoint = subschemaConfig.endpoint;+ }+ else {+ endpoint = subschemaConfig;+ }+ targetRootValue = (_b = rootValue !== null && rootValue !== void 0 ? rootValue : endpoint === null || endpoint === void 0 ? void 0 : endpoint.rootValue) !== null && _b !== void 0 ? _b : info === null || info === void 0 ? void 0 : info.rootValue;+ }+ else {+ targetSchema = subschemaOrSubschemaConfig;+ targetRootValue = rootValue !== null && rootValue !== void 0 ? rootValue : info === null || info === void 0 ? void 0 : info.rootValue;+ allTransforms = transforms;+ }+ const delegationContext = {+ subschema: subschemaOrSubschemaConfig,+ targetSchema,+ operation: targetOperation,+ fieldName: targetFieldName,+ args,+ context,+ info,+ returnType: (_c = returnType !== null && returnType !== void 0 ? returnType : info === null || info === void 0 ? void 0 : info.returnType) !== null && _c !== void 0 ? _c : getDelegationReturnType(targetSchema, targetOperation, targetFieldName),+ transforms: allTransforms,+ transformedSchema: transformedSchema !== null && transformedSchema !== void 0 ? transformedSchema : targetSchema,+ skipTypeMerging,+ };+ const transformer = new Transformer(delegationContext, binding);+ const processedRequest = transformer.transformRequest(request);+ if (!skipValidation) {+ validateRequest(targetSchema, processedRequest.document);+ }+ if (targetOperation === 'query' || targetOperation === 'mutation') {+ let executor = (endpoint === null || endpoint === void 0 ? void 0 : endpoint.executor) || createDefaultExecutor(targetSchema, (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) || targetRootValue);+ if (endpoint === null || endpoint === void 0 ? void 0 : endpoint.batch) {+ executor = getBatchingExecutor(context, endpoint, executor);+ }+ const executionResult = executor({+ ...processedRequest,+ context,+ info,+ });+ if (isPromise_1(executionResult)) {+ return executionResult.then(originalResult => transformer.transformResult(originalResult));+ }+ return transformer.transformResult(executionResult);+ }+ const subscriber = (endpoint === null || endpoint === void 0 ? void 0 : endpoint.subscriber) || createDefaultSubscriber(targetSchema, (subschemaConfig === null || subschemaConfig === void 0 ? void 0 : subschemaConfig.rootValue) || targetRootValue);+ return subscriber({+ ...processedRequest,+ context,+ info,+ }).then((subscriptionResult) => {+ if (Symbol.asyncIterator in subscriptionResult) {+ // "subscribe" to the subscription result and map the result through the transforms+ return mapAsyncIterator$1(subscriptionResult, originalResult => ({+ [targetFieldName]: transformer.transformResult(originalResult),+ }));+ }+ return transformer.transformResult(subscriptionResult);+ });+}+function validateRequest(targetSchema, document) {+ const errors = validate(targetSchema, document);+ if (errors.length > 0) {+ if (errors.length > 1) {+ const combinedError = new AggregateError(errors);+ throw combinedError;+ }+ const error = errors[0];+ throw error.originalError || error;+ }+}+function createDefaultExecutor(schema, rootValue) {+ return ({ document, context, variables, info }) => execute({+ schema,+ document,+ contextValue: context,+ variableValues: variables,+ rootValue: rootValue !== null && rootValue !== void 0 ? rootValue : info === null || info === void 0 ? void 0 : info.rootValue,+ });+}+function createDefaultSubscriber(schema, rootValue) {+ return ({ document, context, variables, info }) => subscribe({+ schema,+ document,+ contextValue: context,+ variableValues: variables,+ rootValue: rootValue !== null && rootValue !== void 0 ? rootValue : info === null || info === void 0 ? void 0 : info.rootValue,+ });+}++/**+ * Resolver that knows how to:+ * a) handle aliases for proxied schemas+ * b) handle errors from proxied schemas+ * c) handle external to internal enum coversion+ */+function defaultMergedResolver(parent, args, context, info) {+ if (!parent) {+ return null;+ }+ const responseKey = getResponseKeyFromInfo(info);+ const errors = getErrors(parent, responseKey);+ // check to see if parent is not a proxied result, i.e. if parent resolver was manually overwritten+ // See https://github.com/apollographql/graphql-tools/issues/967+ if (!errors) {+ return defaultFieldResolver(parent, args, context, info);+ }+ const result = parent[responseKey];+ const subschema = getSubschema(parent, responseKey);+ return handleResult(result, errors, subschema, context, info);+}++function generateProxyingResolvers(subschemaOrSubschemaConfig, transforms) {+ var _a;+ let targetSchema;+ let schemaTransforms = [];+ let createProxyingResolver;+ if (isSubschemaConfig(subschemaOrSubschemaConfig)) {+ targetSchema = subschemaOrSubschemaConfig.schema;+ createProxyingResolver = (_a = subschemaOrSubschemaConfig.createProxyingResolver) !== null && _a !== void 0 ? _a : defaultCreateProxyingResolver;+ if (subschemaOrSubschemaConfig.transforms != null) {+ schemaTransforms = schemaTransforms.concat(subschemaOrSubschemaConfig.transforms);+ }+ }+ else {+ targetSchema = subschemaOrSubschemaConfig;+ createProxyingResolver = defaultCreateProxyingResolver;+ }+ if (transforms != null) {+ schemaTransforms = schemaTransforms.concat(transforms);+ }+ const transformedSchema = applySchemaTransforms(targetSchema, schemaTransforms);+ const operationTypes = {+ query: targetSchema.getQueryType(),+ mutation: targetSchema.getMutationType(),+ subscription: targetSchema.getSubscriptionType(),+ };+ const resolvers = {};+ Object.keys(operationTypes).forEach((operation) => {+ const rootType = operationTypes[operation];+ if (rootType != null) {+ const typeName = rootType.name;+ const fields = rootType.getFields();+ resolvers[typeName] = {};+ Object.keys(fields).forEach(fieldName => {+ const proxyingResolver = createProxyingResolver({+ schema: subschemaOrSubschemaConfig,+ transforms,+ transformedSchema,+ operation,+ fieldName,+ });+ const finalResolver = createPossiblyNestedProxyingResolver(subschemaOrSubschemaConfig, proxyingResolver);+ if (operation === 'subscription') {+ resolvers[typeName][fieldName] = {+ subscribe: finalResolver,+ resolve: (payload, _, __, { fieldName: targetFieldName }) => payload[targetFieldName],+ };+ }+ else {+ resolvers[typeName][fieldName] = {+ resolve: finalResolver,+ };+ }+ });+ }+ });+ return resolvers;+}+function createPossiblyNestedProxyingResolver(subschemaOrSubschemaConfig, proxyingResolver) {+ return (parent, args, context, info) => {+ if (parent != null) {+ const responseKey = getResponseKeyFromInfo(info);+ const errors = getErrors(parent, responseKey);+ // Check to see if the parent contains a proxied result+ if (errors != null) {+ const subschema = getSubschema(parent, responseKey);+ // If there is a proxied result from this subschema, return it+ // This can happen even for a root field when the root type ia+ // also nested as a field within a different type.+ if (subschemaOrSubschemaConfig === subschema && parent[responseKey] !== undefined) {+ return handleResult(parent[responseKey], errors, subschema, context, info);+ }+ }+ }+ return proxyingResolver(parent, args, context, info);+ };+}+function defaultCreateProxyingResolver({ schema, operation, transforms, transformedSchema, }) {+ return (_parent, _args, context, info) => delegateToSchema({+ schema,+ operation,+ context,+ info,+ transforms,+ transformedSchema,+ });+}++function wrapSchema(subschemaOrSubschemaConfig, transforms) {+ let targetSchema;+ let schemaTransforms = [];+ if (isSubschemaConfig(subschemaOrSubschemaConfig)) {+ targetSchema = subschemaOrSubschemaConfig.schema;+ if (subschemaOrSubschemaConfig.transforms != null) {+ schemaTransforms = schemaTransforms.concat(subschemaOrSubschemaConfig.transforms);+ }+ }+ else {+ targetSchema = subschemaOrSubschemaConfig;+ }+ if (transforms != null) {+ schemaTransforms = schemaTransforms.concat(transforms);+ }+ const proxyingResolvers = generateProxyingResolvers(subschemaOrSubschemaConfig, transforms);+ const schema = createWrappingSchema(targetSchema, proxyingResolvers);+ return applySchemaTransforms(schema, schemaTransforms);+}+function createWrappingSchema(schema, proxyingResolvers) {+ return mapSchema(schema, {+ [MapperKind.ROOT_OBJECT]: type => {+ const config = type.toConfig();+ const fieldConfigMap = config.fields;+ Object.keys(fieldConfigMap).forEach(fieldName => {+ fieldConfigMap[fieldName] = {+ ...fieldConfigMap[fieldName],+ ...proxyingResolvers[type.name][fieldName],+ };+ });+ return new GraphQLObjectType(config);+ },+ [MapperKind.OBJECT_TYPE]: type => {+ const config = type.toConfig();+ config.isTypeOf = undefined;+ Object.keys(config.fields).forEach(fieldName => {+ config.fields[fieldName].resolve = defaultMergedResolver;+ config.fields[fieldName].subscribe = null;+ });+ return new GraphQLObjectType(config);+ },+ [MapperKind.INTERFACE_TYPE]: type => {+ const config = type.toConfig();+ delete config.resolveType;+ return new GraphQLInterfaceType(config);+ },+ [MapperKind.UNION_TYPE]: type => {+ const config = type.toConfig();+ delete config.resolveType;+ return new GraphQLUnionType(config);+ },+ });+}++var cleanInternalStack$1 = function (stack) { return stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); };++/** +Escape RegExp special characters. +You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class. +@example +``` +import escapeStringRegexp = require('escape-string-regexp'); +const escapedString = escapeStringRegexp('How much $ for a 🦄?'); +//=> 'How much \\$ for a 🦄\\?' +new RegExp(escapedString); +``` +*/ +var escapeStringRegexp$1 = function (string) { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + return string + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + .replace(/-/g, '\\x2d'); +};++var extractPathRegex$1 = /\s+at.*[(\s](.*)\)?/; +var pathRegex$1 = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; +/** +Clean up error stack traces. Removes the mostly unhelpful internal Node.js entries. +@param stack - The `stack` property of an `Error`. +@example +``` +import cleanStack = require('clean-stack'); +const error = new Error('Missing unicorn'); +console.log(error.stack); +// Error: Missing unicorn +// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15) +// at Module._compile (module.js:409:26) +// at Object.Module._extensions..js (module.js:416:10) +// at Module.load (module.js:343:32) +// at Function.Module._load (module.js:300:12) +// at Function.Module.runMain (module.js:441:10) +// at startup (node.js:139:18) +console.log(cleanStack(error.stack)); +// Error: Missing unicorn +// at Object.<anonymous> (/Users/sindresorhus/dev/clean-stack/unicorn.js:2:15) +``` +*/ +var cleanStack$1 = function (stack, basePath) { + var basePathRegex = basePath && new RegExp("(at | \\()" + escapeStringRegexp$1(basePath), 'g'); + return stack.replace(/\\/g, '/') + .split('\n') + .filter(function (line) { + var pathMatches = line.match(extractPathRegex$1); + if (pathMatches === null || !pathMatches[1]) { + return true; + } + var match = pathMatches[1]; + // Electron + if (match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar')) { + return false; + } + return !pathRegex$1.test(match); + }) + .filter(function (line) { return line.trim() !== ''; }) + .map(function (line) { + if (basePathRegex) { + line = line.replace(basePathRegex, '$1'); + } + return line; + }) + .join('\n'); +};++/** +Indent each line in a string. +@param string - The string to indent. +@param count - How many times you want `options.indent` repeated. Default: `1`. +@example +``` +import indentString = require('indent-string'); +indentString('Unicorns\nRainbows', 4); +//=> ' Unicorns\n Rainbows' +indentString('Unicorns\nRainbows', 4, {indent: '♥'}); +//=> '♥♥♥♥Unicorns\n♥♥♥♥Rainbows' +``` +*/ +var indentString$1 = function (string, count, options) { + if (count === void 0) { count = 1; } + options = Object.assign({ + indent: ' ', + includeEmptyLines: false, + }, options); + if (typeof string !== 'string') { + throw new TypeError("Expected `input` to be a `string`, got `" + typeof string + "`"); + } + if (typeof count !== 'number') { + throw new TypeError("Expected `count` to be a `number`, got `" + typeof count + "`"); + } + if (count < 0) { + throw new RangeError("Expected `count` to be at least 0, got `" + count + "`"); + } + if (typeof options.indent !== 'string') { + throw new TypeError("Expected `options.indent` to be a `string`, got `" + typeof options.indent + "`"); + } + if (count === 0) { + return string; + } + var regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + return string.replace(regex, options.indent.repeat(count)); +};++var AggregateError$1 = /** @class */ (function (_super) { + __extends(AggregateError, _super); + function AggregateError(errors) { + var _this = this; + if (!Array.isArray(errors)) { + throw new TypeError("Expected input to be an Array, got " + typeof errors); + } + var normalizedErrors = errors.map(function (error) { + if (error instanceof Error) { + return error; + } + if (error !== null && typeof error === 'object') { + // Handle plain error objects with message property and/or possibly other metadata + return Object.assign(new Error(error.message), error); + } + return new Error(error); + }); + var message = normalizedErrors + .map(function (error) { + // The `stack` property is not standardized, so we can't assume it exists + return typeof error.stack === 'string' ? cleanInternalStack$1(cleanStack$1(error.stack)) : String(error); + }) + .join('\n'); + message = '\n' + indentString$1(message, 4); + _this = _super.call(this, message) || this; + _this.name = 'AggregateError'; + Object.defineProperty(_this, Symbol.iterator, { + get: function () { return function () { return normalizedErrors[Symbol.iterator](); }; }, + }); + return _this; + } + return AggregateError; +}(Error));++function getSchemaFromIntrospection(introspectionResult) {+ var _a, _b;+ if ((_a = introspectionResult === null || introspectionResult === void 0 ? void 0 : introspectionResult.data) === null || _a === void 0 ? void 0 : _a.__schema) {+ return buildClientSchema(introspectionResult.data);+ }+ else if ((_b = introspectionResult === null || introspectionResult === void 0 ? void 0 : introspectionResult.errors) === null || _b === void 0 ? void 0 : _b.length) {+ if (introspectionResult.errors.length > 1) {+ const combinedError = new AggregateError$1(introspectionResult.errors);+ throw combinedError;+ }+ const error = introspectionResult.errors[0];+ throw error.originalError || error;+ }+ else {+ throw new Error('Could not obtain introspection result, received: ' + JSON.stringify(introspectionResult));+ }+}+async function introspectSchema(executor, context, options) {+ const parsedIntrospectionQuery = parse(getIntrospectionQuery(options));+ const introspectionResult = await executor({+ document: parsedIntrospectionQuery,+ context,+ });+ return getSchemaFromIntrospection(introspectionResult);+}++/**+ * Expose `Backoff`.+ */++var backo2 = Backoff;++/**+ * Initialize backoff timer with `opts`.+ *+ * - `min` initial timeout in milliseconds [100]+ * - `max` max timeout [10000]+ * - `jitter` [0]+ * - `factor` [2]+ *+ * @param {Object} opts+ * @api public+ */++function Backoff(opts) {+ opts = opts || {};+ this.ms = opts.min || 100;+ this.max = opts.max || 10000;+ this.factor = opts.factor || 2;+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;+ this.attempts = 0;+}++/**+ * Return the backoff duration.+ *+ * @return {Number}+ * @api public+ */++Backoff.prototype.duration = function(){+ var ms = this.ms * Math.pow(this.factor, this.attempts++);+ if (this.jitter) {+ var rand = Math.random();+ var deviation = Math.floor(rand * this.jitter * ms);+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;+ }+ return Math.min(ms, this.max) | 0;+};++/**+ * Reset the number of attempts.+ *+ * @api public+ */++Backoff.prototype.reset = function(){+ this.attempts = 0;+};++/**+ * Set the minimum duration+ *+ * @api public+ */++Backoff.prototype.setMin = function(min){+ this.ms = min;+};++/**+ * Set the maximum duration+ *+ * @api public+ */++Backoff.prototype.setMax = function(max){+ this.max = max;+};++/**+ * Set the jitter+ *+ * @api public+ */++Backoff.prototype.setJitter = function(jitter){+ this.jitter = jitter;+};++var eventemitter3 = createCommonjsModule(function (module) {++var has = Object.prototype.hasOwnProperty+ , prefix = '~';++/**+ * Constructor to create a storage for our `EE` objects.+ * An `Events` instance is a plain object whose properties are event names.+ *+ * @constructor+ * @private+ */+function Events() {}++//+// We try to not inherit from `Object.prototype`. In some engines creating an+// instance in this way is faster than calling `Object.create(null)` directly.+// If `Object.create(null)` is not supported we prefix the event names with a+// character to make sure that the built-in object properties are not+// overridden or used as an attack vector.+//+if (Object.create) {+ Events.prototype = Object.create(null);++ //+ // This hack is needed because the `__proto__` property is still inherited in+ // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.+ //+ if (!new Events().__proto__) prefix = false;+}++/**+ * Representation of a single event listener.+ *+ * @param {Function} fn The listener function.+ * @param {*} context The context to invoke the listener with.+ * @param {Boolean} [once=false] Specify if the listener is a one-time listener.+ * @constructor+ * @private+ */+function EE(fn, context, once) {+ this.fn = fn;+ this.context = context;+ this.once = once || false;+}++/**+ * Add a listener for a given event.+ *+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.+ * @param {(String|Symbol)} event The event name.+ * @param {Function} fn The listener function.+ * @param {*} context The context to invoke the listener with.+ * @param {Boolean} once Specify if the listener is a one-time listener.+ * @returns {EventEmitter}+ * @private+ */+function addListener(emitter, event, fn, context, once) {+ if (typeof fn !== 'function') {+ throw new TypeError('The listener must be a function');+ }++ var listener = new EE(fn, context || emitter, once)+ , evt = prefix ? prefix + event : event;++ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);+ else emitter._events[evt] = [emitter._events[evt], listener];++ return emitter;+}++/**+ * Clear event by name.+ *+ * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.+ * @param {(String|Symbol)} evt The Event name.+ * @private+ */+function clearEvent(emitter, evt) {+ if (--emitter._eventsCount === 0) emitter._events = new Events();+ else delete emitter._events[evt];+}++/**+ * Minimal `EventEmitter` interface that is molded against the Node.js+ * `EventEmitter` interface.+ *+ * @constructor+ * @public+ */+function EventEmitter() {+ this._events = new Events();+ this._eventsCount = 0;+}++/**+ * Return an array listing the events for which the emitter has registered+ * listeners.+ *+ * @returns {Array}+ * @public+ */+EventEmitter.prototype.eventNames = function eventNames() {+ var names = []+ , events+ , name;++ if (this._eventsCount === 0) return names;++ for (name in (events = this._events)) {+ if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);+ }++ if (Object.getOwnPropertySymbols) {+ return names.concat(Object.getOwnPropertySymbols(events));+ }++ return names;+};++/**+ * Return the listeners registered for a given event.+ *+ * @param {(String|Symbol)} event The event name.+ * @returns {Array} The registered listeners.+ * @public+ */+EventEmitter.prototype.listeners = function listeners(event) {+ var evt = prefix ? prefix + event : event+ , handlers = this._events[evt];++ if (!handlers) return [];+ if (handlers.fn) return [handlers.fn];++ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {+ ee[i] = handlers[i].fn;+ }++ return ee;+};++/**+ * Return the number of listeners listening to a given event.+ *+ * @param {(String|Symbol)} event The event name.+ * @returns {Number} The number of listeners.+ * @public+ */+EventEmitter.prototype.listenerCount = function listenerCount(event) {+ var evt = prefix ? prefix + event : event+ , listeners = this._events[evt];++ if (!listeners) return 0;+ if (listeners.fn) return 1;+ return listeners.length;+};++/**+ * Calls each of the listeners registered for a given event.+ *+ * @param {(String|Symbol)} event The event name.+ * @returns {Boolean} `true` if the event had listeners, else `false`.+ * @public+ */+EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {+ var evt = prefix ? prefix + event : event;++ if (!this._events[evt]) return false;++ var listeners = this._events[evt]+ , len = arguments.length+ , args+ , i;++ if (listeners.fn) {+ if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);++ switch (len) {+ case 1: return listeners.fn.call(listeners.context), true;+ case 2: return listeners.fn.call(listeners.context, a1), true;+ case 3: return listeners.fn.call(listeners.context, a1, a2), true;+ case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;+ case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;+ case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;+ }++ for (i = 1, args = new Array(len -1); i < len; i++) {+ args[i - 1] = arguments[i];+ }++ listeners.fn.apply(listeners.context, args);+ } else {+ var length = listeners.length+ , j;++ for (i = 0; i < length; i++) {+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);++ switch (len) {+ case 1: listeners[i].fn.call(listeners[i].context); break;+ case 2: listeners[i].fn.call(listeners[i].context, a1); break;+ case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;+ case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;+ default:+ if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {+ args[j - 1] = arguments[j];+ }++ listeners[i].fn.apply(listeners[i].context, args);+ }+ }+ }++ return true;+};++/**+ * Add a listener for a given event.+ *+ * @param {(String|Symbol)} event The event name.+ * @param {Function} fn The listener function.+ * @param {*} [context=this] The context to invoke the listener with.+ * @returns {EventEmitter} `this`.+ * @public+ */+EventEmitter.prototype.on = function on(event, fn, context) {+ return addListener(this, event, fn, context, false);+};++/**+ * Add a one-time listener for a given event.+ *+ * @param {(String|Symbol)} event The event name.+ * @param {Function} fn The listener function.+ * @param {*} [context=this] The context to invoke the listener with.+ * @returns {EventEmitter} `this`.+ * @public+ */+EventEmitter.prototype.once = function once(event, fn, context) {+ return addListener(this, event, fn, context, true);+};++/**+ * Remove the listeners of a given event.+ *+ * @param {(String|Symbol)} event The event name.+ * @param {Function} fn Only remove the listeners that match this function.+ * @param {*} context Only remove the listeners that have this context.+ * @param {Boolean} once Only remove one-time listeners.+ * @returns {EventEmitter} `this`.+ * @public+ */+EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {+ var evt = prefix ? prefix + event : event;++ if (!this._events[evt]) return this;+ if (!fn) {+ clearEvent(this, evt);+ return this;+ }++ var listeners = this._events[evt];++ if (listeners.fn) {+ if (+ listeners.fn === fn &&+ (!once || listeners.once) &&+ (!context || listeners.context === context)+ ) {+ clearEvent(this, evt);+ }+ } else {+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {+ if (+ listeners[i].fn !== fn ||+ (once && !listeners[i].once) ||+ (context && listeners[i].context !== context)+ ) {+ events.push(listeners[i]);+ }+ }++ //+ // Reset the array, or remove it completely if we have no more listeners.+ //+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;+ else clearEvent(this, evt);+ }++ return this;+};++/**+ * Remove all listeners, or those of the specified event.+ *+ * @param {(String|Symbol)} [event] The event name.+ * @returns {EventEmitter} `this`.+ * @public+ */+EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {+ var evt;++ if (event) {+ evt = prefix ? prefix + event : event;+ if (this._events[evt]) clearEvent(this, evt);+ } else {+ this._events = new Events();+ this._eventsCount = 0;+ }++ return this;+};++//+// Alias methods names because people roll like that.+//+EventEmitter.prototype.off = EventEmitter.prototype.removeListener;+EventEmitter.prototype.addListener = EventEmitter.prototype.on;++//+// Expose the prefix.+//+EventEmitter.prefixed = prefix;++//+// Allow `EventEmitter` to be imported as module namespace.+//+EventEmitter.EventEmitter = EventEmitter;++//+// Expose the module.+//+{+ module.exports = EventEmitter;+}+});++var isString_1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true });+function isString(value) {+ return typeof value === 'string';+}+exports.default = isString;++});++var isObject_1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true });+function isObject(value) {+ return ((value !== null) && (typeof value === 'object'));+}+exports.default = isObject;++});++function symbolObservablePonyfill(root) {+ var result;+ var Symbol = root.Symbol;++ if (typeof Symbol === 'function') {+ if (Symbol.observable) {+ result = Symbol.observable;+ } else {+ result = Symbol('observable');+ Symbol.observable = result;+ }+ } else {+ result = '@@observable';+ }++ return result;+}++/* global window */++var root;++if (typeof self !== 'undefined') {+ root = self;+} else if (typeof window !== 'undefined') {+ root = window;+} else if (typeof global !== 'undefined') {+ root = global;+} else if (typeof module !== 'undefined') {+ root = module;+} else {+ root = Function('return this')();+}++var result = symbolObservablePonyfill(root);++var es = /*#__PURE__*/Object.freeze({+ __proto__: null,+ 'default': result+});++var protocol = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true });+exports.GRAPHQL_SUBSCRIPTIONS = exports.GRAPHQL_WS = void 0;+var GRAPHQL_WS = 'graphql-ws';+exports.GRAPHQL_WS = GRAPHQL_WS;+var GRAPHQL_SUBSCRIPTIONS = 'graphql-subscriptions';+exports.GRAPHQL_SUBSCRIPTIONS = GRAPHQL_SUBSCRIPTIONS;++});++var defaults$1 = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true });+exports.WS_TIMEOUT = exports.MIN_WS_TIMEOUT = void 0;+var MIN_WS_TIMEOUT = 1000;+exports.MIN_WS_TIMEOUT = MIN_WS_TIMEOUT;+var WS_TIMEOUT = 30000;+exports.WS_TIMEOUT = WS_TIMEOUT;++});++var messageTypes = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true });+var MessageTypes = (function () {+ function MessageTypes() {+ throw new Error('Static Class');+ }+ MessageTypes.GQL_CONNECTION_INIT = 'connection_init';+ MessageTypes.GQL_CONNECTION_ACK = 'connection_ack';+ MessageTypes.GQL_CONNECTION_ERROR = 'connection_error';+ MessageTypes.GQL_CONNECTION_KEEP_ALIVE = 'ka';+ MessageTypes.GQL_CONNECTION_TERMINATE = 'connection_terminate';+ MessageTypes.GQL_START = 'start';+ MessageTypes.GQL_DATA = 'data';+ MessageTypes.GQL_ERROR = 'error';+ MessageTypes.GQL_COMPLETE = 'complete';+ MessageTypes.GQL_STOP = 'stop';+ MessageTypes.SUBSCRIPTION_START = 'subscription_start';+ MessageTypes.SUBSCRIPTION_DATA = 'subscription_data';+ MessageTypes.SUBSCRIPTION_SUCCESS = 'subscription_success';+ MessageTypes.SUBSCRIPTION_FAIL = 'subscription_fail';+ MessageTypes.SUBSCRIPTION_END = 'subscription_end';+ MessageTypes.INIT = 'init';+ MessageTypes.INIT_SUCCESS = 'init_success';+ MessageTypes.INIT_FAIL = 'init_fail';+ MessageTypes.KEEP_ALIVE = 'keepalive';+ return MessageTypes;+}());+exports.default = MessageTypes;++});++var printer_1 = /*@__PURE__*/getAugmentedNamespace(printer);++var getOperationAST_1 = /*@__PURE__*/getAugmentedNamespace(getOperationAST$1);++var symbol_observable_1 = /*@__PURE__*/getAugmentedNamespace(es);++var client = createCommonjsModule(function (module, exports) {+var __assign = (commonjsGlobal && commonjsGlobal.__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 __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }+ return new (P || (P = Promise))(function (resolve, reject) {+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }+ step((generator = generator.apply(thisArg, _arguments || [])).next());+ });+};+var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;+ function verb(n) { return function (v) { return step([n, v]); }; }+ function step(op) {+ if (f) throw new TypeError("Generator is already executing.");+ while (_) try {+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;+ if (y = 0, t) op = [op[0] & 2, t.value];+ switch (op[0]) {+ case 0: case 1: t = op; break;+ case 4: _.label++; return { value: op[1], done: false };+ case 5: _.label++; y = op[1]; op = [0]; continue;+ case 7: op = _.ops.pop(); _.trys.pop(); continue;+ default:+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }+ if (t[2]) _.ops.pop();+ _.trys.pop(); continue;+ }+ op = body.call(thisArg, _);+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };+ }+};+var __spreadArrays = (commonjsGlobal && commonjsGlobal.__spreadArrays) || function () {+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;+ for (var r = Array(s), k = 0, i = 0; i < il; i++)+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)+ r[k] = a[j];+ return r;+};+Object.defineProperty(exports, "__esModule", { value: true });+exports.SubscriptionClient = void 0;+var _global = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : (typeof window !== 'undefined' ? window : {});+var NativeWebSocket = _global.WebSocket || _global.MozWebSocket;+++++++++++var SubscriptionClient = (function () {+ function SubscriptionClient(url, options, webSocketImpl, webSocketProtocols) {+ var _a = (options || {}), _b = _a.connectionCallback, connectionCallback = _b === void 0 ? undefined : _b, _c = _a.connectionParams, connectionParams = _c === void 0 ? {} : _c, _d = _a.minTimeout, minTimeout = _d === void 0 ? defaults$1.MIN_WS_TIMEOUT : _d, _e = _a.timeout, timeout = _e === void 0 ? defaults$1.WS_TIMEOUT : _e, _f = _a.reconnect, reconnect = _f === void 0 ? false : _f, _g = _a.reconnectionAttempts, reconnectionAttempts = _g === void 0 ? Infinity : _g, _h = _a.lazy, lazy = _h === void 0 ? false : _h, _j = _a.inactivityTimeout, inactivityTimeout = _j === void 0 ? 0 : _j, _k = _a.wsOptionArguments, wsOptionArguments = _k === void 0 ? [] : _k;+ this.wsImpl = webSocketImpl || NativeWebSocket;+ if (!this.wsImpl) {+ throw new Error('Unable to find native implementation, or alternative implementation for WebSocket!');+ }+ this.wsProtocols = webSocketProtocols || protocol.GRAPHQL_WS;+ this.connectionCallback = connectionCallback;+ this.url = url;+ this.operations = {};+ this.nextOperationId = 0;+ this.minWsTimeout = minTimeout;+ this.wsTimeout = timeout;+ this.unsentMessagesQueue = [];+ this.reconnect = reconnect;+ this.reconnecting = false;+ this.reconnectionAttempts = reconnectionAttempts;+ this.lazy = !!lazy;+ this.inactivityTimeout = inactivityTimeout;+ this.closedByUser = false;+ this.backoff = new backo2({ jitter: 0.5 });+ this.eventEmitter = new eventemitter3.EventEmitter();+ this.middlewares = [];+ this.client = null;+ this.maxConnectTimeGenerator = this.createMaxConnectTimeGenerator();+ this.connectionParams = this.getConnectionParams(connectionParams);+ this.wsOptionArguments = wsOptionArguments;+ if (!this.lazy) {+ this.connect();+ }+ }+ Object.defineProperty(SubscriptionClient.prototype, "status", {+ get: function () {+ if (this.client === null) {+ return this.wsImpl.CLOSED;+ }+ return this.client.readyState;+ },+ enumerable: false,+ configurable: true+ });+ SubscriptionClient.prototype.close = function (isForced, closedByUser) {+ if (isForced === void 0) { isForced = true; }+ if (closedByUser === void 0) { closedByUser = true; }+ this.clearInactivityTimeout();+ if (this.client !== null) {+ this.closedByUser = closedByUser;+ if (isForced) {+ this.clearCheckConnectionInterval();+ this.clearMaxConnectTimeout();+ this.clearTryReconnectTimeout();+ this.unsubscribeAll();+ this.sendMessage(undefined, messageTypes.default.GQL_CONNECTION_TERMINATE, null);+ }+ this.client.close();+ this.client.onopen = null;+ this.client.onclose = null;+ this.client.onerror = null;+ this.client.onmessage = null;+ this.client = null;+ this.eventEmitter.emit('disconnected');+ if (!isForced) {+ this.tryReconnect();+ }+ }+ };+ SubscriptionClient.prototype.request = function (request) {+ var _a;+ var getObserver = this.getObserver.bind(this);+ var executeOperation = this.executeOperation.bind(this);+ var unsubscribe = this.unsubscribe.bind(this);+ var opId;+ this.clearInactivityTimeout();+ return _a = {},+ _a[symbol_observable_1.default] = function () {+ return this;+ },+ _a.subscribe = function (observerOrNext, onError, onComplete) {+ var observer = getObserver(observerOrNext, onError, onComplete);+ opId = executeOperation(request, function (error, result) {+ if (error === null && result === null) {+ if (observer.complete) {+ observer.complete();+ }+ }+ else if (error) {+ if (observer.error) {+ observer.error(error[0]);+ }+ }+ else {+ if (observer.next) {+ observer.next(result);+ }+ }+ });+ return {+ unsubscribe: function () {+ if (opId) {+ unsubscribe(opId);+ opId = null;+ }+ },+ };+ },+ _a;+ };+ SubscriptionClient.prototype.on = function (eventName, callback, context) {+ var handler = this.eventEmitter.on(eventName, callback, context);+ return function () {+ handler.off(eventName, callback, context);+ };+ };+ SubscriptionClient.prototype.onConnected = function (callback, context) {+ return this.on('connected', callback, context);+ };+ SubscriptionClient.prototype.onConnecting = function (callback, context) {+ return this.on('connecting', callback, context);+ };+ SubscriptionClient.prototype.onDisconnected = function (callback, context) {+ return this.on('disconnected', callback, context);+ };+ SubscriptionClient.prototype.onReconnected = function (callback, context) {+ return this.on('reconnected', callback, context);+ };+ SubscriptionClient.prototype.onReconnecting = function (callback, context) {+ return this.on('reconnecting', callback, context);+ };+ SubscriptionClient.prototype.onError = function (callback, context) {+ return this.on('error', callback, context);+ };+ SubscriptionClient.prototype.unsubscribeAll = function () {+ var _this = this;+ Object.keys(this.operations).forEach(function (subId) {+ _this.unsubscribe(subId);+ });+ };+ SubscriptionClient.prototype.applyMiddlewares = function (options) {+ var _this = this;+ return new Promise(function (resolve, reject) {+ var queue = function (funcs, scope) {+ var next = function (error) {+ if (error) {+ reject(error);+ }+ else {+ if (funcs.length > 0) {+ var f = funcs.shift();+ if (f) {+ f.applyMiddleware.apply(scope, [options, next]);+ }+ }+ else {+ resolve(options);+ }+ }+ };+ next();+ };+ queue(__spreadArrays(_this.middlewares), _this);+ });+ };+ SubscriptionClient.prototype.use = function (middlewares) {+ var _this = this;+ middlewares.map(function (middleware) {+ if (typeof middleware.applyMiddleware === 'function') {+ _this.middlewares.push(middleware);+ }+ else {+ throw new Error('Middleware must implement the applyMiddleware function.');+ }+ });+ return this;+ };+ SubscriptionClient.prototype.getConnectionParams = function (connectionParams) {+ return function () { return new Promise(function (resolve, reject) {+ if (typeof connectionParams === 'function') {+ try {+ return resolve(connectionParams.call(null));+ }+ catch (error) {+ return reject(error);+ }+ }+ resolve(connectionParams);+ }); };+ };+ SubscriptionClient.prototype.executeOperation = function (options, handler) {+ var _this = this;+ if (this.client === null) {+ this.connect();+ }+ var opId = this.generateOperationId();+ this.operations[opId] = { options: options, handler: handler };+ this.applyMiddlewares(options)+ .then(function (processedOptions) {+ _this.checkOperationOptions(processedOptions, handler);+ if (_this.operations[opId]) {+ _this.operations[opId] = { options: processedOptions, handler: handler };+ _this.sendMessage(opId, messageTypes.default.GQL_START, processedOptions);+ }+ })+ .catch(function (error) {+ _this.unsubscribe(opId);+ handler(_this.formatErrors(error));+ });+ return opId;+ };+ SubscriptionClient.prototype.getObserver = function (observerOrNext, error, complete) {+ if (typeof observerOrNext === 'function') {+ return {+ next: function (v) { return observerOrNext(v); },+ error: function (e) { return error && error(e); },+ complete: function () { return complete && complete(); },+ };+ }+ return observerOrNext;+ };+ SubscriptionClient.prototype.createMaxConnectTimeGenerator = function () {+ var minValue = this.minWsTimeout;+ var maxValue = this.wsTimeout;+ return new backo2({+ min: minValue,+ max: maxValue,+ factor: 1.2,+ });+ };+ SubscriptionClient.prototype.clearCheckConnectionInterval = function () {+ if (this.checkConnectionIntervalId) {+ clearInterval(this.checkConnectionIntervalId);+ this.checkConnectionIntervalId = null;+ }+ };+ SubscriptionClient.prototype.clearMaxConnectTimeout = function () {+ if (this.maxConnectTimeoutId) {+ clearTimeout(this.maxConnectTimeoutId);+ this.maxConnectTimeoutId = null;+ }+ };+ SubscriptionClient.prototype.clearTryReconnectTimeout = function () {+ if (this.tryReconnectTimeoutId) {+ clearTimeout(this.tryReconnectTimeoutId);+ this.tryReconnectTimeoutId = null;+ }+ };+ SubscriptionClient.prototype.clearInactivityTimeout = function () {+ if (this.inactivityTimeoutId) {+ clearTimeout(this.inactivityTimeoutId);+ this.inactivityTimeoutId = null;+ }+ };+ SubscriptionClient.prototype.setInactivityTimeout = function () {+ var _this = this;+ if (this.inactivityTimeout > 0 && Object.keys(this.operations).length === 0) {+ this.inactivityTimeoutId = setTimeout(function () {+ if (Object.keys(_this.operations).length === 0) {+ _this.close();+ }+ }, this.inactivityTimeout);+ }+ };+ SubscriptionClient.prototype.checkOperationOptions = function (options, handler) {+ var query = options.query, variables = options.variables, operationName = options.operationName;+ if (!query) {+ throw new Error('Must provide a query.');+ }+ if (!handler) {+ throw new Error('Must provide an handler.');+ }+ if ((!isString_1.default(query) && !getOperationAST_1.getOperationAST(query, operationName)) ||+ (operationName && !isString_1.default(operationName)) ||+ (variables && !isObject_1.default(variables))) {+ throw new Error('Incorrect option types. query must be a string or a document,' ++ '`operationName` must be a string, and `variables` must be an object.');+ }+ };+ SubscriptionClient.prototype.buildMessage = function (id, type, payload) {+ var payloadToReturn = payload && payload.query ? __assign(__assign({}, payload), { query: typeof payload.query === 'string' ? payload.query : printer_1.print(payload.query) }) :+ payload;+ return {+ id: id,+ type: type,+ payload: payloadToReturn,+ };+ };+ SubscriptionClient.prototype.formatErrors = function (errors) {+ if (Array.isArray(errors)) {+ return errors;+ }+ if (errors && errors.errors) {+ return this.formatErrors(errors.errors);+ }+ if (errors && errors.message) {+ return [errors];+ }+ return [{+ name: 'FormatedError',+ message: 'Unknown error',+ originalError: errors,+ }];+ };+ SubscriptionClient.prototype.sendMessage = function (id, type, payload) {+ this.sendMessageRaw(this.buildMessage(id, type, payload));+ };+ SubscriptionClient.prototype.sendMessageRaw = function (message) {+ switch (this.status) {+ case this.wsImpl.OPEN:+ var serializedMessage = JSON.stringify(message);+ try {+ JSON.parse(serializedMessage);+ }+ catch (e) {+ this.eventEmitter.emit('error', new Error("Message must be JSON-serializable. Got: " + message));+ }+ this.client.send(serializedMessage);+ break;+ case this.wsImpl.CONNECTING:+ this.unsentMessagesQueue.push(message);+ break;+ default:+ if (!this.reconnecting) {+ this.eventEmitter.emit('error', new Error('A message was not sent because socket is not connected, is closing or ' ++ 'is already closed. Message was: ' + JSON.stringify(message)));+ }+ }+ };+ SubscriptionClient.prototype.generateOperationId = function () {+ return String(++this.nextOperationId);+ };+ SubscriptionClient.prototype.tryReconnect = function () {+ var _this = this;+ if (!this.reconnect || this.backoff.attempts >= this.reconnectionAttempts) {+ return;+ }+ if (!this.reconnecting) {+ Object.keys(this.operations).forEach(function (key) {+ _this.unsentMessagesQueue.push(_this.buildMessage(key, messageTypes.default.GQL_START, _this.operations[key].options));+ });+ this.reconnecting = true;+ }+ this.clearTryReconnectTimeout();+ var delay = this.backoff.duration();+ this.tryReconnectTimeoutId = setTimeout(function () {+ _this.connect();+ }, delay);+ };+ SubscriptionClient.prototype.flushUnsentMessagesQueue = function () {+ var _this = this;+ this.unsentMessagesQueue.forEach(function (message) {+ _this.sendMessageRaw(message);+ });+ this.unsentMessagesQueue = [];+ };+ SubscriptionClient.prototype.checkConnection = function () {+ if (this.wasKeepAliveReceived) {+ this.wasKeepAliveReceived = false;+ return;+ }+ if (!this.reconnecting) {+ this.close(false, true);+ }+ };+ SubscriptionClient.prototype.checkMaxConnectTimeout = function () {+ var _this = this;+ this.clearMaxConnectTimeout();+ this.maxConnectTimeoutId = setTimeout(function () {+ if (_this.status !== _this.wsImpl.OPEN) {+ _this.reconnecting = true;+ _this.close(false, true);+ }+ }, this.maxConnectTimeGenerator.duration());+ };+ SubscriptionClient.prototype.connect = function () {+ var _a;+ var _this = this;+ this.client = new ((_a = this.wsImpl).bind.apply(_a, __spreadArrays([void 0, this.url, this.wsProtocols], this.wsOptionArguments)))();+ this.checkMaxConnectTimeout();+ this.client.onopen = function () { return __awaiter(_this, void 0, void 0, function () {+ var connectionParams, error_1;+ return __generator(this, function (_a) {+ switch (_a.label) {+ case 0:+ if (!(this.status === this.wsImpl.OPEN)) return [3, 4];+ this.clearMaxConnectTimeout();+ this.closedByUser = false;+ this.eventEmitter.emit(this.reconnecting ? 'reconnecting' : 'connecting');+ _a.label = 1;+ case 1:+ _a.trys.push([1, 3, , 4]);+ return [4, this.connectionParams()];+ case 2:+ connectionParams = _a.sent();+ this.sendMessage(undefined, messageTypes.default.GQL_CONNECTION_INIT, connectionParams);+ this.flushUnsentMessagesQueue();+ return [3, 4];+ case 3:+ error_1 = _a.sent();+ this.sendMessage(undefined, messageTypes.default.GQL_CONNECTION_ERROR, error_1);+ this.flushUnsentMessagesQueue();+ return [3, 4];+ case 4: return [2];+ }+ });+ }); };+ this.client.onclose = function () {+ if (!_this.closedByUser) {+ _this.close(false, false);+ }+ };+ this.client.onerror = function (err) {+ _this.eventEmitter.emit('error', err);+ };+ this.client.onmessage = function (_a) {+ var data = _a.data;+ _this.processReceivedData(data);+ };+ };+ SubscriptionClient.prototype.processReceivedData = function (receivedData) {+ var parsedMessage;+ var opId;+ try {+ parsedMessage = JSON.parse(receivedData);+ opId = parsedMessage.id;+ }+ catch (e) {+ throw new Error("Message must be JSON-parseable. Got: " + receivedData);+ }+ if ([messageTypes.default.GQL_DATA,+ messageTypes.default.GQL_COMPLETE,+ messageTypes.default.GQL_ERROR,+ ].indexOf(parsedMessage.type) !== -1 && !this.operations[opId]) {+ this.unsubscribe(opId);+ return;+ }+ switch (parsedMessage.type) {+ case messageTypes.default.GQL_CONNECTION_ERROR:+ if (this.connectionCallback) {+ this.connectionCallback(parsedMessage.payload);+ }+ break;+ case messageTypes.default.GQL_CONNECTION_ACK:+ this.eventEmitter.emit(this.reconnecting ? 'reconnected' : 'connected', parsedMessage.payload);+ this.reconnecting = false;+ this.backoff.reset();+ this.maxConnectTimeGenerator.reset();+ if (this.connectionCallback) {+ this.connectionCallback();+ }+ break;+ case messageTypes.default.GQL_COMPLETE:+ var handler = this.operations[opId].handler;+ delete this.operations[opId];+ handler.call(this, null, null);+ break;+ case messageTypes.default.GQL_ERROR:+ this.operations[opId].handler(this.formatErrors(parsedMessage.payload), null);+ delete this.operations[opId];+ break;+ case messageTypes.default.GQL_DATA:+ var parsedPayload = !parsedMessage.payload.errors ?+ parsedMessage.payload : __assign(__assign({}, parsedMessage.payload), { errors: this.formatErrors(parsedMessage.payload.errors) });+ this.operations[opId].handler(null, parsedPayload);+ break;+ case messageTypes.default.GQL_CONNECTION_KEEP_ALIVE:+ var firstKA = typeof this.wasKeepAliveReceived === 'undefined';+ this.wasKeepAliveReceived = true;+ if (firstKA) {+ this.checkConnection();+ }+ if (this.checkConnectionIntervalId) {+ clearInterval(this.checkConnectionIntervalId);+ this.checkConnection();+ }+ this.checkConnectionIntervalId = setInterval(this.checkConnection.bind(this), this.wsTimeout);+ break;+ default:+ throw new Error('Invalid message type!');+ }+ };+ SubscriptionClient.prototype.unsubscribe = function (opId) {+ if (this.operations[opId]) {+ delete this.operations[opId];+ this.setInactivityTimeout();+ this.sendMessage(opId, messageTypes.default.GQL_STOP, undefined);+ }+ };+ return SubscriptionClient;+}());+exports.SubscriptionClient = SubscriptionClient;++});++function Queue(options) {+ if (!(this instanceof Queue)) {+ return new Queue(options);+ }++ options = options || {};+ this.concurrency = options.concurrency || Infinity;+ this.pending = 0;+ this.jobs = [];+ this.cbs = [];+ this._done = done.bind(this);+}++var arrayAddMethods = [+ 'push',+ 'unshift',+ 'splice'+];++arrayAddMethods.forEach(function(method) {+ Queue.prototype[method] = function() {+ var methodResult = Array.prototype[method].apply(this.jobs, arguments);+ this._run();+ return methodResult;+ };+});++Object.defineProperty(Queue.prototype, 'length', {+ get: function() {+ return this.pending + this.jobs.length;+ }+});++Queue.prototype._run = function() {+ if (this.pending === this.concurrency) {+ return;+ }+ if (this.jobs.length) {+ var job = this.jobs.shift();+ this.pending++;+ job(this._done);+ this._run();+ }++ if (this.pending === 0) {+ while (this.cbs.length !== 0) {+ var cb = this.cbs.pop();+ process.nextTick(cb);+ }+ }+};++Queue.prototype.onDone = function(cb) {+ if (typeof cb === 'function') {+ this.cbs.push(cb);+ this._run();+ }+};++function done() {+ this.pending--;+ this._run();+}++var asyncLimiter = Queue;++var bufferUtil = createCommonjsModule(function (module) {++/**+ * Merges an array of buffers into a new buffer.+ *+ * @param {Buffer[]} list The array of buffers to concat+ * @param {Number} totalLength The total length of buffers in the list+ * @return {Buffer} The resulting buffer+ * @public+ */+function concat (list, totalLength) {+ const target = Buffer.allocUnsafe(totalLength);+ var offset = 0;++ for (var i = 0; i < list.length; i++) {+ const buf = list[i];+ buf.copy(target, offset);+ offset += buf.length;+ }++ return target;+}++/**+ * Masks a buffer using the given mask.+ *+ * @param {Buffer} source The buffer to mask+ * @param {Buffer} mask The mask to use+ * @param {Buffer} output The buffer where to store the result+ * @param {Number} offset The offset at which to start writing+ * @param {Number} length The number of bytes to mask.+ * @public+ */+function _mask (source, mask, output, offset, length) {+ for (var i = 0; i < length; i++) {+ output[offset + i] = source[i] ^ mask[i & 3];+ }+}++/**+ * Unmasks a buffer using the given mask.+ *+ * @param {Buffer} buffer The buffer to unmask+ * @param {Buffer} mask The mask to use+ * @public+ */+function _unmask (buffer, mask) {+ // Required until https://github.com/nodejs/node/issues/9006 is resolved.+ const length = buffer.length;+ for (var i = 0; i < length; i++) {+ buffer[i] ^= mask[i & 3];+ }+}++try {+ const bufferUtil = require('bufferutil');+ const bu = bufferUtil.BufferUtil || bufferUtil;++ module.exports = {+ mask (source, mask, output, offset, length) {+ if (length < 48) _mask(source, mask, output, offset, length);+ else bu.mask(source, mask, output, offset, length);+ },+ unmask (buffer, mask) {+ if (buffer.length < 32) _unmask(buffer, mask);+ else bu.unmask(buffer, mask);+ },+ concat+ };+} catch (e) /* istanbul ignore next */ {+ module.exports = { concat, mask: _mask, unmask: _unmask };+}+});++var constants$3 = {+ BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],+ GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',+ kStatusCode: Symbol('status-code'),+ kWebSocket: Symbol('websocket'),+ EMPTY_BUFFER: Buffer.alloc(0),+ NOOP: () => {}+};++const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);+const EMPTY_BLOCK = Buffer.from([0x00]);++const kPerMessageDeflate = Symbol('permessage-deflate');+const kWriteInProgress = Symbol('write-in-progress');+const kPendingClose = Symbol('pending-close');+const kTotalLength = Symbol('total-length');+const kCallback = Symbol('callback');+const kBuffers = Symbol('buffers');+const kError = Symbol('error');++//+// We limit zlib concurrency, which prevents severe memory fragmentation+// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913+// and https://github.com/websockets/ws/issues/1202+//+// Intentionally global; it's the global thread pool that's an issue.+//+let zlibLimiter;++/**+ * permessage-deflate implementation.+ */+class PerMessageDeflate {+ /**+ * Creates a PerMessageDeflate instance.+ *+ * @param {Object} options Configuration options+ * @param {Boolean} options.serverNoContextTakeover Request/accept disabling+ * of server context takeover+ * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge+ * disabling of client context takeover+ * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the+ * use of a custom server window size+ * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support+ * for, or request, a custom client window size+ * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate+ * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate+ * @param {Number} options.threshold Size (in bytes) below which messages+ * should not be compressed+ * @param {Number} options.concurrencyLimit The number of concurrent calls to+ * zlib+ * @param {Boolean} isServer Create the instance in either server or client+ * mode+ * @param {Number} maxPayload The maximum allowed message length+ */+ constructor (options, isServer, maxPayload) {+ this._maxPayload = maxPayload | 0;+ this._options = options || {};+ this._threshold = this._options.threshold !== undefined+ ? this._options.threshold+ : 1024;+ this._isServer = !!isServer;+ this._deflate = null;+ this._inflate = null;++ this.params = null;++ if (!zlibLimiter) {+ const concurrency = this._options.concurrencyLimit !== undefined+ ? this._options.concurrencyLimit+ : 10;+ zlibLimiter = new asyncLimiter({ concurrency });+ }+ }++ /**+ * @type {String}+ */+ static get extensionName () {+ return 'permessage-deflate';+ }++ /**+ * Create an extension negotiation offer.+ *+ * @return {Object} Extension parameters+ * @public+ */+ offer () {+ const params = {};++ if (this._options.serverNoContextTakeover) {+ params.server_no_context_takeover = true;+ }+ if (this._options.clientNoContextTakeover) {+ params.client_no_context_takeover = true;+ }+ if (this._options.serverMaxWindowBits) {+ params.server_max_window_bits = this._options.serverMaxWindowBits;+ }+ if (this._options.clientMaxWindowBits) {+ params.client_max_window_bits = this._options.clientMaxWindowBits;+ } else if (this._options.clientMaxWindowBits == null) {+ params.client_max_window_bits = true;+ }++ return params;+ }++ /**+ * Accept an extension negotiation offer/response.+ *+ * @param {Array} configurations The extension negotiation offers/reponse+ * @return {Object} Accepted configuration+ * @public+ */+ accept (configurations) {+ configurations = this.normalizeParams(configurations);++ this.params = this._isServer+ ? this.acceptAsServer(configurations)+ : this.acceptAsClient(configurations);++ return this.params;+ }++ /**+ * Releases all resources used by the extension.+ *+ * @public+ */+ cleanup () {+ if (this._inflate) {+ if (this._inflate[kWriteInProgress]) {+ this._inflate[kPendingClose] = true;+ } else {+ this._inflate.close();+ this._inflate = null;+ }+ }+ if (this._deflate) {+ if (this._deflate[kWriteInProgress]) {+ this._deflate[kPendingClose] = true;+ } else {+ this._deflate.close();+ this._deflate = null;+ }+ }+ }++ /**+ * Accept an extension negotiation offer.+ *+ * @param {Array} offers The extension negotiation offers+ * @return {Object} Accepted configuration+ * @private+ */+ acceptAsServer (offers) {+ const opts = this._options;+ const accepted = offers.find((params) => {+ if (+ (opts.serverNoContextTakeover === false &&+ params.server_no_context_takeover) ||+ (params.server_max_window_bits &&+ (opts.serverMaxWindowBits === false ||+ (typeof opts.serverMaxWindowBits === 'number' &&+ opts.serverMaxWindowBits > params.server_max_window_bits))) ||+ (typeof opts.clientMaxWindowBits === 'number' &&+ !params.client_max_window_bits)+ ) {+ return false;+ }++ return true;+ });++ if (!accepted) {+ throw new Error('None of the extension offers can be accepted');+ }++ if (opts.serverNoContextTakeover) {+ accepted.server_no_context_takeover = true;+ }+ if (opts.clientNoContextTakeover) {+ accepted.client_no_context_takeover = true;+ }+ if (typeof opts.serverMaxWindowBits === 'number') {+ accepted.server_max_window_bits = opts.serverMaxWindowBits;+ }+ if (typeof opts.clientMaxWindowBits === 'number') {+ accepted.client_max_window_bits = opts.clientMaxWindowBits;+ } else if (+ accepted.client_max_window_bits === true ||+ opts.clientMaxWindowBits === false+ ) {+ delete accepted.client_max_window_bits;+ }++ return accepted;+ }++ /**+ * Accept the extension negotiation response.+ *+ * @param {Array} response The extension negotiation response+ * @return {Object} Accepted configuration+ * @private+ */+ acceptAsClient (response) {+ const params = response[0];++ if (+ this._options.clientNoContextTakeover === false &&+ params.client_no_context_takeover+ ) {+ throw new Error('Unexpected parameter "client_no_context_takeover"');+ }++ if (!params.client_max_window_bits) {+ if (typeof this._options.clientMaxWindowBits === 'number') {+ params.client_max_window_bits = this._options.clientMaxWindowBits;+ }+ } else if (+ this._options.clientMaxWindowBits === false ||+ (typeof this._options.clientMaxWindowBits === 'number' &&+ params.client_max_window_bits > this._options.clientMaxWindowBits)+ ) {+ throw new Error(+ 'Unexpected or invalid parameter "client_max_window_bits"'+ );+ }++ return params;+ }++ /**+ * Normalize parameters.+ *+ * @param {Array} configurations The extension negotiation offers/reponse+ * @return {Array} The offers/response with normalized parameters+ * @private+ */+ normalizeParams (configurations) {+ configurations.forEach((params) => {+ Object.keys(params).forEach((key) => {+ var value = params[key];++ if (value.length > 1) {+ throw new Error(`Parameter "${key}" must have only a single value`);+ }++ value = value[0];++ if (key === 'client_max_window_bits') {+ if (value !== true) {+ const num = +value;+ if (!Number.isInteger(num) || num < 8 || num > 15) {+ throw new TypeError(+ `Invalid value for parameter "${key}": ${value}`+ );+ }+ value = num;+ } else if (!this._isServer) {+ throw new TypeError(+ `Invalid value for parameter "${key}": ${value}`+ );+ }+ } else if (key === 'server_max_window_bits') {+ const num = +value;+ if (!Number.isInteger(num) || num < 8 || num > 15) {+ throw new TypeError(+ `Invalid value for parameter "${key}": ${value}`+ );+ }+ value = num;+ } else if (+ key === 'client_no_context_takeover' ||+ key === 'server_no_context_takeover'+ ) {+ if (value !== true) {+ throw new TypeError(+ `Invalid value for parameter "${key}": ${value}`+ );+ }+ } else {+ throw new Error(`Unknown parameter "${key}"`);+ }++ params[key] = value;+ });+ });++ return configurations;+ }++ /**+ * Decompress data. Concurrency limited by async-limiter.+ *+ * @param {Buffer} data Compressed data+ * @param {Boolean} fin Specifies whether or not this is the last fragment+ * @param {Function} callback Callback+ * @public+ */+ decompress (data, fin, callback) {+ zlibLimiter.push((done) => {+ this._decompress(data, fin, (err, result) => {+ done();+ callback(err, result);+ });+ });+ }++ /**+ * Compress data. Concurrency limited by async-limiter.+ *+ * @param {Buffer} data Data to compress+ * @param {Boolean} fin Specifies whether or not this is the last fragment+ * @param {Function} callback Callback+ * @public+ */+ compress (data, fin, callback) {+ zlibLimiter.push((done) => {+ this._compress(data, fin, (err, result) => {+ done();+ callback(err, result);+ });+ });+ }++ /**+ * Decompress data.+ *+ * @param {Buffer} data Compressed data+ * @param {Boolean} fin Specifies whether or not this is the last fragment+ * @param {Function} callback Callback+ * @private+ */+ _decompress (data, fin, callback) {+ const endpoint = this._isServer ? 'client' : 'server';++ if (!this._inflate) {+ const key = `${endpoint}_max_window_bits`;+ const windowBits = typeof this.params[key] !== 'number'+ ? zlib__default['default'].Z_DEFAULT_WINDOWBITS+ : this.params[key];++ this._inflate = zlib__default['default'].createInflateRaw(+ Object.assign({}, this._options.zlibInflateOptions, { windowBits })+ );+ this._inflate[kPerMessageDeflate] = this;+ this._inflate[kTotalLength] = 0;+ this._inflate[kBuffers] = [];+ this._inflate.on('error', inflateOnError);+ this._inflate.on('data', inflateOnData);+ }++ this._inflate[kCallback] = callback;+ this._inflate[kWriteInProgress] = true;++ this._inflate.write(data);+ if (fin) this._inflate.write(TRAILER);++ this._inflate.flush(() => {+ const err = this._inflate[kError];++ if (err) {+ this._inflate.close();+ this._inflate = null;+ callback(err);+ return;+ }++ const data = bufferUtil.concat(+ this._inflate[kBuffers],+ this._inflate[kTotalLength]+ );++ if (+ (fin && this.params[`${endpoint}_no_context_takeover`]) ||+ this._inflate[kPendingClose]+ ) {+ this._inflate.close();+ this._inflate = null;+ } else {+ this._inflate[kWriteInProgress] = false;+ this._inflate[kTotalLength] = 0;+ this._inflate[kBuffers] = [];+ }++ callback(null, data);+ });+ }++ /**+ * Compress data.+ *+ * @param {Buffer} data Data to compress+ * @param {Boolean} fin Specifies whether or not this is the last fragment+ * @param {Function} callback Callback+ * @private+ */+ _compress (data, fin, callback) {+ if (!data || data.length === 0) {+ process.nextTick(callback, null, EMPTY_BLOCK);+ return;+ }++ const endpoint = this._isServer ? 'server' : 'client';++ if (!this._deflate) {+ const key = `${endpoint}_max_window_bits`;+ const windowBits = typeof this.params[key] !== 'number'+ ? zlib__default['default'].Z_DEFAULT_WINDOWBITS+ : this.params[key];++ this._deflate = zlib__default['default'].createDeflateRaw(+ Object.assign(+ // TODO deprecate memLevel/level and recommend zlibDeflateOptions instead+ {+ memLevel: this._options.memLevel,+ level: this._options.level+ },+ this._options.zlibDeflateOptions,+ { windowBits }+ )+ );++ this._deflate[kTotalLength] = 0;+ this._deflate[kBuffers] = [];++ //+ // `zlib.DeflateRaw` emits an `'error'` event only when an attempt to use+ // it is made after it has already been closed. This cannot happen here,+ // so we only add a listener for the `'data'` event.+ //+ this._deflate.on('data', deflateOnData);+ }++ this._deflate[kWriteInProgress] = true;++ this._deflate.write(data);+ this._deflate.flush(zlib__default['default'].Z_SYNC_FLUSH, () => {+ var data = bufferUtil.concat(+ this._deflate[kBuffers],+ this._deflate[kTotalLength]+ );++ if (fin) data = data.slice(0, data.length - 4);++ if (+ (fin && this.params[`${endpoint}_no_context_takeover`]) ||+ this._deflate[kPendingClose]+ ) {+ this._deflate.close();+ this._deflate = null;+ } else {+ this._deflate[kWriteInProgress] = false;+ this._deflate[kTotalLength] = 0;+ this._deflate[kBuffers] = [];+ }++ callback(null, data);+ });+ }+}++var permessageDeflate = PerMessageDeflate;++/**+ * The listener of the `zlib.DeflateRaw` stream `'data'` event.+ *+ * @param {Buffer} chunk A chunk of data+ * @private+ */+function deflateOnData (chunk) {+ this[kBuffers].push(chunk);+ this[kTotalLength] += chunk.length;+}++/**+ * The listener of the `zlib.InflateRaw` stream `'data'` event.+ *+ * @param {Buffer} chunk A chunk of data+ * @private+ */+function inflateOnData (chunk) {+ this[kTotalLength] += chunk.length;++ if (+ this[kPerMessageDeflate]._maxPayload < 1 ||+ this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload+ ) {+ this[kBuffers].push(chunk);+ return;+ }++ this[kError] = new RangeError('Max payload size exceeded');+ this[kError][constants$3.kStatusCode] = 1009;+ this.removeListener('data', inflateOnData);+ this.reset();+}++/**+ * The listener of the `zlib.InflateRaw` stream `'error'` event.+ *+ * @param {Error} err The emitted error+ * @private+ */+function inflateOnError (err) {+ //+ // There is no need to call `Zlib#close()` as the handle is automatically+ // closed when an error is emitted.+ //+ this[kPerMessageDeflate]._inflate = null;+ err[constants$3.kStatusCode] = 1007;+ this[kCallback](err);+}++/**+ * Class representing an event.+ *+ * @private+ */+class Event {+ /**+ * Create a new `Event`.+ *+ * @param {String} type The name of the event+ * @param {Object} target A reference to the target to which the event was dispatched+ */+ constructor (type, target) {+ this.target = target;+ this.type = type;+ }+}++/**+ * Class representing a message event.+ *+ * @extends Event+ * @private+ */+class MessageEvent extends Event {+ /**+ * Create a new `MessageEvent`.+ *+ * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data+ * @param {WebSocket} target A reference to the target to which the event was dispatched+ */+ constructor (data, target) {+ super('message', target);++ this.data = data;+ }+}++/**+ * Class representing a close event.+ *+ * @extends Event+ * @private+ */+class CloseEvent extends Event {+ /**+ * Create a new `CloseEvent`.+ *+ * @param {Number} code The status code explaining why the connection is being closed+ * @param {String} reason A human-readable string explaining why the connection is closing+ * @param {WebSocket} target A reference to the target to which the event was dispatched+ */+ constructor (code, reason, target) {+ super('close', target);++ this.wasClean = target._closeFrameReceived && target._closeFrameSent;+ this.reason = reason;+ this.code = code;+ }+}++/**+ * Class representing an open event.+ *+ * @extends Event+ * @private+ */+class OpenEvent extends Event {+ /**+ * Create a new `OpenEvent`.+ *+ * @param {WebSocket} target A reference to the target to which the event was dispatched+ */+ constructor (target) {+ super('open', target);+ }+}++/**+ * Class representing an error event.+ *+ * @extends Event+ * @private+ */+class ErrorEvent extends Event {+ /**+ * Create a new `ErrorEvent`.+ *+ * @param {Object} error The error that generated this event+ * @param {WebSocket} target A reference to the target to which the event was dispatched+ */+ constructor (error, target) {+ super('error', target);++ this.message = error.message;+ this.error = error;+ }+}++/**+ * This provides methods for emulating the `EventTarget` interface. It's not+ * meant to be used directly.+ *+ * @mixin+ */+const EventTarget = {+ /**+ * Register an event listener.+ *+ * @param {String} method A string representing the event type to listen for+ * @param {Function} listener The listener to add+ * @public+ */+ addEventListener (method, listener) {+ if (typeof listener !== 'function') return;++ function onMessage (data) {+ listener.call(this, new MessageEvent(data, this));+ }++ function onClose (code, message) {+ listener.call(this, new CloseEvent(code, message, this));+ }++ function onError (error) {+ listener.call(this, new ErrorEvent(error, this));+ }++ function onOpen () {+ listener.call(this, new OpenEvent(this));+ }++ if (method === 'message') {+ onMessage._listener = listener;+ this.on(method, onMessage);+ } else if (method === 'close') {+ onClose._listener = listener;+ this.on(method, onClose);+ } else if (method === 'error') {+ onError._listener = listener;+ this.on(method, onError);+ } else if (method === 'open') {+ onOpen._listener = listener;+ this.on(method, onOpen);+ } else {+ this.on(method, listener);+ }+ },++ /**+ * Remove an event listener.+ *+ * @param {String} method A string representing the event type to remove+ * @param {Function} listener The listener to remove+ * @public+ */+ removeEventListener (method, listener) {+ const listeners = this.listeners(method);++ for (var i = 0; i < listeners.length; i++) {+ if (listeners[i] === listener || listeners[i]._listener === listener) {+ this.removeListener(method, listeners[i]);+ }+ }+ }+};++var eventTarget = EventTarget;++//+// Allowed token characters:+//+// '!', '#', '$', '%', '&', ''', '*', '+', '-',+// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'+//+// tokenChars[32] === 0 // ' '+// tokenChars[33] === 1 // '!'+// tokenChars[34] === 0 // '"'+// ...+//+const tokenChars = [+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31+ 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127+];++/**+ * Adds an offer to the map of extension offers or a parameter to the map of+ * parameters.+ *+ * @param {Object} dest The map of extension offers or parameters+ * @param {String} name The extension or parameter name+ * @param {(Object|Boolean|String)} elem The extension parameters or the+ * parameter value+ * @private+ */+function push (dest, name, elem) {+ if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem);+ else dest[name] = [elem];+}++/**+ * Parses the `Sec-WebSocket-Extensions` header into an object.+ *+ * @param {String} header The field value of the header+ * @return {Object} The parsed object+ * @public+ */+function parse$3 (header) {+ const offers = {};++ if (header === undefined || header === '') return offers;++ var params = {};+ var mustUnescape = false;+ var isEscaping = false;+ var inQuotes = false;+ var extensionName;+ var paramName;+ var start = -1;+ var end = -1;++ for (var i = 0; i < header.length; i++) {+ const code = header.charCodeAt(i);++ if (extensionName === undefined) {+ if (end === -1 && tokenChars[code] === 1) {+ if (start === -1) start = i;+ } else if (code === 0x20/* ' ' */|| code === 0x09/* '\t' */) {+ if (end === -1 && start !== -1) end = i;+ } else if (code === 0x3b/* ';' */ || code === 0x2c/* ',' */) {+ if (start === -1) {+ throw new SyntaxError(`Unexpected character at index ${i}`);+ }++ if (end === -1) end = i;+ const name = header.slice(start, end);+ if (code === 0x2c) {+ push(offers, name, params);+ params = {};+ } else {+ extensionName = name;+ }++ start = end = -1;+ } else {+ throw new SyntaxError(`Unexpected character at index ${i}`);+ }+ } else if (paramName === undefined) {+ if (end === -1 && tokenChars[code] === 1) {+ if (start === -1) start = i;+ } else if (code === 0x20 || code === 0x09) {+ if (end === -1 && start !== -1) end = i;+ } else if (code === 0x3b || code === 0x2c) {+ if (start === -1) {+ throw new SyntaxError(`Unexpected character at index ${i}`);+ }++ if (end === -1) end = i;+ push(params, header.slice(start, end), true);+ if (code === 0x2c) {+ push(offers, extensionName, params);+ params = {};+ extensionName = undefined;+ }++ start = end = -1;+ } else if (code === 0x3d/* '=' */&& start !== -1 && end === -1) {+ paramName = header.slice(start, i);+ start = end = -1;+ } else {+ throw new SyntaxError(`Unexpected character at index ${i}`);+ }+ } else {+ //+ // The value of a quoted-string after unescaping must conform to the+ // token ABNF, so only token characters are valid.+ // Ref: https://tools.ietf.org/html/rfc6455#section-9.1+ //+ if (isEscaping) {+ if (tokenChars[code] !== 1) {+ throw new SyntaxError(`Unexpected character at index ${i}`);+ }+ if (start === -1) start = i;+ else if (!mustUnescape) mustUnescape = true;+ isEscaping = false;+ } else if (inQuotes) {+ if (tokenChars[code] === 1) {+ if (start === -1) start = i;+ } else if (code === 0x22/* '"' */ && start !== -1) {+ inQuotes = false;+ end = i;+ } else if (code === 0x5c/* '\' */) {+ isEscaping = true;+ } else {+ throw new SyntaxError(`Unexpected character at index ${i}`);+ }+ } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {+ inQuotes = true;+ } else if (end === -1 && tokenChars[code] === 1) {+ if (start === -1) start = i;+ } else if (start !== -1 && (code === 0x20 || code === 0x09)) {+ if (end === -1) end = i;+ } else if (code === 0x3b || code === 0x2c) {+ if (start === -1) {+ throw new SyntaxError(`Unexpected character at index ${i}`);+ }++ if (end === -1) end = i;+ var value = header.slice(start, end);+ if (mustUnescape) {+ value = value.replace(/\\/g, '');+ mustUnescape = false;+ }+ push(params, paramName, value);+ if (code === 0x2c) {+ push(offers, extensionName, params);+ params = {};+ extensionName = undefined;+ }++ paramName = undefined;+ start = end = -1;+ } else {+ throw new SyntaxError(`Unexpected character at index ${i}`);+ }+ }+ }++ if (start === -1 || inQuotes) {+ throw new SyntaxError('Unexpected end of input');+ }++ if (end === -1) end = i;+ const token = header.slice(start, end);+ if (extensionName === undefined) {+ push(offers, token, {});+ } else {+ if (paramName === undefined) {+ push(params, token, true);+ } else if (mustUnescape) {+ push(params, paramName, token.replace(/\\/g, ''));+ } else {+ push(params, paramName, token);+ }+ push(offers, extensionName, params);+ }++ return offers;+}++/**+ * Builds the `Sec-WebSocket-Extensions` header field value.+ *+ * @param {Object} extensions The map of extensions and parameters to format+ * @return {String} A string representing the given object+ * @public+ */+function format (extensions) {+ return Object.keys(extensions).map((extension) => {+ var configurations = extensions[extension];+ if (!Array.isArray(configurations)) configurations = [configurations];+ return configurations.map((params) => {+ return [extension].concat(Object.keys(params).map((k) => {+ var values = params[k];+ if (!Array.isArray(values)) values = [values];+ return values.map((v) => v === true ? k : `${k}=${v}`).join('; ');+ })).join('; ');+ }).join(', ');+ }).join(', ');+}++var extension = { format, parse: parse$3 };++var validation = createCommonjsModule(function (module, exports) {++try {+ const isValidUTF8 = require('utf-8-validate');++ exports.isValidUTF8 = typeof isValidUTF8 === 'object'+ ? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0+ : isValidUTF8;+} catch (e) /* istanbul ignore next */ {+ exports.isValidUTF8 = () => true;+}++/**+ * Checks if a status code is allowed in a close frame.+ *+ * @param {Number} code The status code+ * @return {Boolean} `true` if the status code is valid, else `false`+ * @public+ */+exports.isValidStatusCode = (code) => {+ return (+ (code >= 1000 &&+ code <= 1013 &&+ code !== 1004 &&+ code !== 1005 &&+ code !== 1006) ||+ (code >= 3000 && code <= 4999)+ );+};+});++const GET_INFO = 0;+const GET_PAYLOAD_LENGTH_16 = 1;+const GET_PAYLOAD_LENGTH_64 = 2;+const GET_MASK = 3;+const GET_DATA = 4;+const INFLATING = 5;++/**+ * HyBi Receiver implementation.+ *+ * @extends stream.Writable+ */+class Receiver extends Stream__default['default'].Writable {+ /**+ * Creates a Receiver instance.+ *+ * @param {String} binaryType The type for binary data+ * @param {Object} extensions An object containing the negotiated extensions+ * @param {Number} maxPayload The maximum allowed message length+ */+ constructor (binaryType, extensions, maxPayload) {+ super();++ this._binaryType = binaryType || constants$3.BINARY_TYPES[0];+ this[constants$3.kWebSocket] = undefined;+ this._extensions = extensions || {};+ this._maxPayload = maxPayload | 0;++ this._bufferedBytes = 0;+ this._buffers = [];++ this._compressed = false;+ this._payloadLength = 0;+ this._mask = undefined;+ this._fragmented = 0;+ this._masked = false;+ this._fin = false;+ this._opcode = 0;++ this._totalPayloadLength = 0;+ this._messageLength = 0;+ this._fragments = [];++ this._state = GET_INFO;+ this._loop = false;+ }++ /**+ * Implements `Writable.prototype._write()`.+ *+ * @param {Buffer} chunk The chunk of data to write+ * @param {String} encoding The character encoding of `chunk`+ * @param {Function} cb Callback+ */+ _write (chunk, encoding, cb) {+ if (this._opcode === 0x08) return cb();++ this._bufferedBytes += chunk.length;+ this._buffers.push(chunk);+ this.startLoop(cb);+ }++ /**+ * Consumes `n` bytes from the buffered data.+ *+ * @param {Number} n The number of bytes to consume+ * @return {Buffer} The consumed bytes+ * @private+ */+ consume (n) {+ this._bufferedBytes -= n;++ if (n === this._buffers[0].length) return this._buffers.shift();++ if (n < this._buffers[0].length) {+ const buf = this._buffers[0];+ this._buffers[0] = buf.slice(n);+ return buf.slice(0, n);+ }++ const dst = Buffer.allocUnsafe(n);++ do {+ const buf = this._buffers[0];++ if (n >= buf.length) {+ this._buffers.shift().copy(dst, dst.length - n);+ } else {+ buf.copy(dst, dst.length - n, 0, n);+ this._buffers[0] = buf.slice(n);+ }++ n -= buf.length;+ } while (n > 0);++ return dst;+ }++ /**+ * Starts the parsing loop.+ *+ * @param {Function} cb Callback+ * @private+ */+ startLoop (cb) {+ var err;+ this._loop = true;++ do {+ switch (this._state) {+ case GET_INFO:+ err = this.getInfo();+ break;+ case GET_PAYLOAD_LENGTH_16:+ err = this.getPayloadLength16();+ break;+ case GET_PAYLOAD_LENGTH_64:+ err = this.getPayloadLength64();+ break;+ case GET_MASK:+ this.getMask();+ break;+ case GET_DATA:+ err = this.getData(cb);+ break;+ default: // `INFLATING`+ this._loop = false;+ return;+ }+ } while (this._loop);++ cb(err);+ }++ /**+ * Reads the first two bytes of a frame.+ *+ * @return {(RangeError|undefined)} A possible error+ * @private+ */+ getInfo () {+ if (this._bufferedBytes < 2) {+ this._loop = false;+ return;+ }++ const buf = this.consume(2);++ if ((buf[0] & 0x30) !== 0x00) {+ this._loop = false;+ return error$1(RangeError, 'RSV2 and RSV3 must be clear', true, 1002);+ }++ const compressed = (buf[0] & 0x40) === 0x40;++ if (compressed && !this._extensions[permessageDeflate.extensionName]) {+ this._loop = false;+ return error$1(RangeError, 'RSV1 must be clear', true, 1002);+ }++ this._fin = (buf[0] & 0x80) === 0x80;+ this._opcode = buf[0] & 0x0f;+ this._payloadLength = buf[1] & 0x7f;++ if (this._opcode === 0x00) {+ if (compressed) {+ this._loop = false;+ return error$1(RangeError, 'RSV1 must be clear', true, 1002);+ }++ if (!this._fragmented) {+ this._loop = false;+ return error$1(RangeError, 'invalid opcode 0', true, 1002);+ }++ this._opcode = this._fragmented;+ } else if (this._opcode === 0x01 || this._opcode === 0x02) {+ if (this._fragmented) {+ this._loop = false;+ return error$1(RangeError, `invalid opcode ${this._opcode}`, true, 1002);+ }++ this._compressed = compressed;+ } else if (this._opcode > 0x07 && this._opcode < 0x0b) {+ if (!this._fin) {+ this._loop = false;+ return error$1(RangeError, 'FIN must be set', true, 1002);+ }++ if (compressed) {+ this._loop = false;+ return error$1(RangeError, 'RSV1 must be clear', true, 1002);+ }++ if (this._payloadLength > 0x7d) {+ this._loop = false;+ return error$1(+ RangeError,+ `invalid payload length ${this._payloadLength}`,+ true,+ 1002+ );+ }+ } else {+ this._loop = false;+ return error$1(RangeError, `invalid opcode ${this._opcode}`, true, 1002);+ }++ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;+ this._masked = (buf[1] & 0x80) === 0x80;++ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;+ else return this.haveLength();+ }++ /**+ * Gets extended payload length (7+16).+ *+ * @return {(RangeError|undefined)} A possible error+ * @private+ */+ getPayloadLength16 () {+ if (this._bufferedBytes < 2) {+ this._loop = false;+ return;+ }++ this._payloadLength = this.consume(2).readUInt16BE(0);+ return this.haveLength();+ }++ /**+ * Gets extended payload length (7+64).+ *+ * @return {(RangeError|undefined)} A possible error+ * @private+ */+ getPayloadLength64 () {+ if (this._bufferedBytes < 8) {+ this._loop = false;+ return;+ }++ const buf = this.consume(8);+ const num = buf.readUInt32BE(0);++ //+ // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned+ // if payload length is greater than this number.+ //+ if (num > Math.pow(2, 53 - 32) - 1) {+ this._loop = false;+ return error$1(+ RangeError,+ 'Unsupported WebSocket frame: payload length > 2^53 - 1',+ false,+ 1009+ );+ }++ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);+ return this.haveLength();+ }++ /**+ * Payload length has been read.+ *+ * @return {(RangeError|undefined)} A possible error+ * @private+ */+ haveLength () {+ if (this._payloadLength && this._opcode < 0x08) {+ this._totalPayloadLength += this._payloadLength;+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {+ this._loop = false;+ return error$1(RangeError, 'Max payload size exceeded', false, 1009);+ }+ }++ if (this._masked) this._state = GET_MASK;+ else this._state = GET_DATA;+ }++ /**+ * Reads mask bytes.+ *+ * @private+ */+ getMask () {+ if (this._bufferedBytes < 4) {+ this._loop = false;+ return;+ }++ this._mask = this.consume(4);+ this._state = GET_DATA;+ }++ /**+ * Reads data bytes.+ *+ * @param {Function} cb Callback+ * @return {(Error|RangeError|undefined)} A possible error+ * @private+ */+ getData (cb) {+ var data = constants$3.EMPTY_BUFFER;++ if (this._payloadLength) {+ if (this._bufferedBytes < this._payloadLength) {+ this._loop = false;+ return;+ }++ data = this.consume(this._payloadLength);+ if (this._masked) bufferUtil.unmask(data, this._mask);+ }++ if (this._opcode > 0x07) return this.controlMessage(data);++ if (this._compressed) {+ this._state = INFLATING;+ this.decompress(data, cb);+ return;+ }++ if (data.length) {+ //+ // This message is not compressed so its lenght is the sum of the payload+ // length of all fragments.+ //+ this._messageLength = this._totalPayloadLength;+ this._fragments.push(data);+ }++ return this.dataMessage();+ }++ /**+ * Decompresses data.+ *+ * @param {Buffer} data Compressed data+ * @param {Function} cb Callback+ * @private+ */+ decompress (data, cb) {+ const perMessageDeflate = this._extensions[permessageDeflate.extensionName];++ perMessageDeflate.decompress(data, this._fin, (err, buf) => {+ if (err) return cb(err);++ if (buf.length) {+ this._messageLength += buf.length;+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {+ return cb(error$1(RangeError, 'Max payload size exceeded', false, 1009));+ }++ this._fragments.push(buf);+ }++ const er = this.dataMessage();+ if (er) return cb(er);++ this.startLoop(cb);+ });+ }++ /**+ * Handles a data message.+ *+ * @return {(Error|undefined)} A possible error+ * @private+ */+ dataMessage () {+ if (this._fin) {+ const messageLength = this._messageLength;+ const fragments = this._fragments;++ this._totalPayloadLength = 0;+ this._messageLength = 0;+ this._fragmented = 0;+ this._fragments = [];++ if (this._opcode === 2) {+ var data;++ if (this._binaryType === 'nodebuffer') {+ data = toBuffer(fragments, messageLength);+ } else if (this._binaryType === 'arraybuffer') {+ data = toArrayBuffer(toBuffer(fragments, messageLength));+ } else {+ data = fragments;+ }++ this.emit('message', data);+ } else {+ const buf = toBuffer(fragments, messageLength);++ if (!validation.isValidUTF8(buf)) {+ this._loop = false;+ return error$1(Error, 'invalid UTF-8 sequence', true, 1007);+ }++ this.emit('message', buf.toString());+ }+ }++ this._state = GET_INFO;+ }++ /**+ * Handles a control message.+ *+ * @param {Buffer} data Data to handle+ * @return {(Error|RangeError|undefined)} A possible error+ * @private+ */+ controlMessage (data) {+ if (this._opcode === 0x08) {+ this._loop = false;++ if (data.length === 0) {+ this.emit('conclude', 1005, '');+ this.end();+ } else if (data.length === 1) {+ return error$1(RangeError, 'invalid payload length 1', true, 1002);+ } else {+ const code = data.readUInt16BE(0);++ if (!validation.isValidStatusCode(code)) {+ return error$1(RangeError, `invalid status code ${code}`, true, 1002);+ }++ const buf = data.slice(2);++ if (!validation.isValidUTF8(buf)) {+ return error$1(Error, 'invalid UTF-8 sequence', true, 1007);+ }++ this.emit('conclude', code, buf.toString());+ this.end();+ }++ return;+ }++ if (this._opcode === 0x09) this.emit('ping', data);+ else this.emit('pong', data);++ this._state = GET_INFO;+ }+}++var receiver = Receiver;++/**+ * Builds an error object.+ *+ * @param {(Error|RangeError)} ErrorCtor The error constructor+ * @param {String} message The error message+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to+ * `message`+ * @param {Number} statusCode The status code+ * @return {(Error|RangeError)} The error+ * @private+ */+function error$1 (ErrorCtor, message, prefix, statusCode) {+ const err = new ErrorCtor(+ prefix ? `Invalid WebSocket frame: ${message}` : message+ );++ Error.captureStackTrace(err, error$1);+ err[constants$3.kStatusCode] = statusCode;+ return err;+}++/**+ * Makes a buffer from a list of fragments.+ *+ * @param {Buffer[]} fragments The list of fragments composing the message+ * @param {Number} messageLength The length of the message+ * @return {Buffer}+ * @private+ */+function toBuffer (fragments, messageLength) {+ if (fragments.length === 1) return fragments[0];+ if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength);+ return constants$3.EMPTY_BUFFER;+}++/**+ * Converts a buffer to an `ArrayBuffer`.+ *+ * @param {Buffer} The buffer to convert+ * @return {ArrayBuffer} Converted buffer+ */+function toArrayBuffer (buf) {+ if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {+ return buf.buffer;+ }++ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);+}++/**+ * HyBi Sender implementation.+ */+class Sender {+ /**+ * Creates a Sender instance.+ *+ * @param {net.Socket} socket The connection socket+ * @param {Object} extensions An object containing the negotiated extensions+ */+ constructor (socket, extensions) {+ this._extensions = extensions || {};+ this._socket = socket;++ this._firstFragment = true;+ this._compress = false;++ this._bufferedBytes = 0;+ this._deflating = false;+ this._queue = [];+ }++ /**+ * Frames a piece of data according to the HyBi WebSocket protocol.+ *+ * @param {Buffer} data The data to frame+ * @param {Object} options Options object+ * @param {Number} options.opcode The opcode+ * @param {Boolean} options.readOnly Specifies whether `data` can be modified+ * @param {Boolean} options.fin Specifies whether or not to set the FIN bit+ * @param {Boolean} options.mask Specifies whether or not to mask `data`+ * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit+ * @return {Buffer[]} The framed data as a list of `Buffer` instances+ * @public+ */+ static frame (data, options) {+ const merge = data.length < 1024 || (options.mask && options.readOnly);+ var offset = options.mask ? 6 : 2;+ var payloadLength = data.length;++ if (data.length >= 65536) {+ offset += 8;+ payloadLength = 127;+ } else if (data.length > 125) {+ offset += 2;+ payloadLength = 126;+ }++ const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);++ target[0] = options.fin ? options.opcode | 0x80 : options.opcode;+ if (options.rsv1) target[0] |= 0x40;++ if (payloadLength === 126) {+ target.writeUInt16BE(data.length, 2);+ } else if (payloadLength === 127) {+ target.writeUInt32BE(0, 2);+ target.writeUInt32BE(data.length, 6);+ }++ if (!options.mask) {+ target[1] = payloadLength;+ if (merge) {+ data.copy(target, offset);+ return [target];+ }++ return [target, data];+ }++ const mask = crypto__default['default'].randomBytes(4);++ target[1] = payloadLength | 0x80;+ target[offset - 4] = mask[0];+ target[offset - 3] = mask[1];+ target[offset - 2] = mask[2];+ target[offset - 1] = mask[3];++ if (merge) {+ bufferUtil.mask(data, mask, target, offset, data.length);+ return [target];+ }++ bufferUtil.mask(data, mask, data, 0, data.length);+ return [target, data];+ }++ /**+ * Sends a close message to the other peer.+ *+ * @param {(Number|undefined)} code The status code component of the body+ * @param {String} data The message component of the body+ * @param {Boolean} mask Specifies whether or not to mask the message+ * @param {Function} cb Callback+ * @public+ */+ close (code, data, mask, cb) {+ var buf;++ if (code === undefined) {+ buf = constants$3.EMPTY_BUFFER;+ } else if (typeof code !== 'number' || !validation.isValidStatusCode(code)) {+ throw new TypeError('First argument must be a valid error code number');+ } else if (data === undefined || data === '') {+ buf = Buffer.allocUnsafe(2);+ buf.writeUInt16BE(code, 0);+ } else {+ buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));+ buf.writeUInt16BE(code, 0);+ buf.write(data, 2);+ }++ if (this._deflating) {+ this.enqueue([this.doClose, buf, mask, cb]);+ } else {+ this.doClose(buf, mask, cb);+ }+ }++ /**+ * Frames and sends a close message.+ *+ * @param {Buffer} data The message to send+ * @param {Boolean} mask Specifies whether or not to mask `data`+ * @param {Function} cb Callback+ * @private+ */+ doClose (data, mask, cb) {+ this.sendFrame(Sender.frame(data, {+ fin: true,+ rsv1: false,+ opcode: 0x08,+ mask,+ readOnly: false+ }), cb);+ }++ /**+ * Sends a ping message to the other peer.+ *+ * @param {*} data The message to send+ * @param {Boolean} mask Specifies whether or not to mask `data`+ * @param {Function} cb Callback+ * @public+ */+ ping (data, mask, cb) {+ var readOnly = true;++ if (!Buffer.isBuffer(data)) {+ if (data instanceof ArrayBuffer) {+ data = Buffer.from(data);+ } else if (ArrayBuffer.isView(data)) {+ data = viewToBuffer(data);+ } else {+ data = Buffer.from(data);+ readOnly = false;+ }+ }++ if (this._deflating) {+ this.enqueue([this.doPing, data, mask, readOnly, cb]);+ } else {+ this.doPing(data, mask, readOnly, cb);+ }+ }++ /**+ * Frames and sends a ping message.+ *+ * @param {*} data The message to send+ * @param {Boolean} mask Specifies whether or not to mask `data`+ * @param {Boolean} readOnly Specifies whether `data` can be modified+ * @param {Function} cb Callback+ * @private+ */+ doPing (data, mask, readOnly, cb) {+ this.sendFrame(Sender.frame(data, {+ fin: true,+ rsv1: false,+ opcode: 0x09,+ mask,+ readOnly+ }), cb);+ }++ /**+ * Sends a pong message to the other peer.+ *+ * @param {*} data The message to send+ * @param {Boolean} mask Specifies whether or not to mask `data`+ * @param {Function} cb Callback+ * @public+ */+ pong (data, mask, cb) {+ var readOnly = true;++ if (!Buffer.isBuffer(data)) {+ if (data instanceof ArrayBuffer) {+ data = Buffer.from(data);+ } else if (ArrayBuffer.isView(data)) {+ data = viewToBuffer(data);+ } else {+ data = Buffer.from(data);+ readOnly = false;+ }+ }++ if (this._deflating) {+ this.enqueue([this.doPong, data, mask, readOnly, cb]);+ } else {+ this.doPong(data, mask, readOnly, cb);+ }+ }++ /**+ * Frames and sends a pong message.+ *+ * @param {*} data The message to send+ * @param {Boolean} mask Specifies whether or not to mask `data`+ * @param {Boolean} readOnly Specifies whether `data` can be modified+ * @param {Function} cb Callback+ * @private+ */+ doPong (data, mask, readOnly, cb) {+ this.sendFrame(Sender.frame(data, {+ fin: true,+ rsv1: false,+ opcode: 0x0a,+ mask,+ readOnly+ }), cb);+ }++ /**+ * Sends a data message to the other peer.+ *+ * @param {*} data The message to send+ * @param {Object} options Options object+ * @param {Boolean} options.compress Specifies whether or not to compress `data`+ * @param {Boolean} options.binary Specifies whether `data` is binary or text+ * @param {Boolean} options.fin Specifies whether the fragment is the last one+ * @param {Boolean} options.mask Specifies whether or not to mask `data`+ * @param {Function} cb Callback+ * @public+ */+ send (data, options, cb) {+ var opcode = options.binary ? 2 : 1;+ var rsv1 = options.compress;+ var readOnly = true;++ if (!Buffer.isBuffer(data)) {+ if (data instanceof ArrayBuffer) {+ data = Buffer.from(data);+ } else if (ArrayBuffer.isView(data)) {+ data = viewToBuffer(data);+ } else {+ data = Buffer.from(data);+ readOnly = false;+ }+ }++ const perMessageDeflate = this._extensions[permessageDeflate.extensionName];++ if (this._firstFragment) {+ this._firstFragment = false;+ if (rsv1 && perMessageDeflate) {+ rsv1 = data.length >= perMessageDeflate._threshold;+ }+ this._compress = rsv1;+ } else {+ rsv1 = false;+ opcode = 0;+ }++ if (options.fin) this._firstFragment = true;++ if (perMessageDeflate) {+ const opts = {+ fin: options.fin,+ rsv1,+ opcode,+ mask: options.mask,+ readOnly+ };++ if (this._deflating) {+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);+ } else {+ this.dispatch(data, this._compress, opts, cb);+ }+ } else {+ this.sendFrame(Sender.frame(data, {+ fin: options.fin,+ rsv1: false,+ opcode,+ mask: options.mask,+ readOnly+ }), cb);+ }+ }++ /**+ * Dispatches a data message.+ *+ * @param {Buffer} data The message to send+ * @param {Boolean} compress Specifies whether or not to compress `data`+ * @param {Object} options Options object+ * @param {Number} options.opcode The opcode+ * @param {Boolean} options.readOnly Specifies whether `data` can be modified+ * @param {Boolean} options.fin Specifies whether or not to set the FIN bit+ * @param {Boolean} options.mask Specifies whether or not to mask `data`+ * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit+ * @param {Function} cb Callback+ * @private+ */+ dispatch (data, compress, options, cb) {+ if (!compress) {+ this.sendFrame(Sender.frame(data, options), cb);+ return;+ }++ const perMessageDeflate = this._extensions[permessageDeflate.extensionName];++ this._deflating = true;+ perMessageDeflate.compress(data, options.fin, (_, buf) => {+ options.readOnly = false;+ this.sendFrame(Sender.frame(buf, options), cb);+ this._deflating = false;+ this.dequeue();+ });+ }++ /**+ * Executes queued send operations.+ *+ * @private+ */+ dequeue () {+ while (!this._deflating && this._queue.length) {+ const params = this._queue.shift();++ this._bufferedBytes -= params[1].length;+ params[0].apply(this, params.slice(1));+ }+ }++ /**+ * Enqueues a send operation.+ *+ * @param {Array} params Send operation parameters.+ * @private+ */+ enqueue (params) {+ this._bufferedBytes += params[1].length;+ this._queue.push(params);+ }++ /**+ * Sends a frame.+ *+ * @param {Buffer[]} list The frame to send+ * @param {Function} cb Callback+ * @private+ */+ sendFrame (list, cb) {+ if (list.length === 2) {+ this._socket.write(list[0]);+ this._socket.write(list[1], cb);+ } else {+ this._socket.write(list[0], cb);+ }+ }+}++var sender = Sender;++/**+ * Converts an `ArrayBuffer` view into a buffer.+ *+ * @param {(DataView|TypedArray)} view The view to convert+ * @return {Buffer} Converted view+ * @private+ */+function viewToBuffer (view) {+ const buf = Buffer.from(view.buffer);++ if (view.byteLength !== view.buffer.byteLength) {+ return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);+ }++ return buf;+}++const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];+const kWebSocket = constants$3.kWebSocket;+const protocolVersions = [8, 13];+const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly.++/**+ * Class representing a WebSocket.+ *+ * @extends EventEmitter+ */+class WebSocket extends EventEmitter__default['default'] {+ /**+ * Create a new `WebSocket`.+ *+ * @param {(String|url.Url|url.URL)} address The URL to which to connect+ * @param {(String|String[])} protocols The subprotocols+ * @param {Object} options Connection options+ */+ constructor (address, protocols, options) {+ super();++ this.readyState = WebSocket.CONNECTING;+ this.protocol = '';++ this._binaryType = constants$3.BINARY_TYPES[0];+ this._closeFrameReceived = false;+ this._closeFrameSent = false;+ this._closeMessage = '';+ this._closeTimer = null;+ this._closeCode = 1006;+ this._extensions = {};+ this._isServer = true;+ this._receiver = null;+ this._sender = null;+ this._socket = null;++ if (address !== null) {+ if (Array.isArray(protocols)) {+ protocols = protocols.join(', ');+ } else if (typeof protocols === 'object' && protocols !== null) {+ options = protocols;+ protocols = undefined;+ }++ initAsClient.call(this, address, protocols, options);+ }+ }++ get CONNECTING () { return WebSocket.CONNECTING; }+ get CLOSING () { return WebSocket.CLOSING; }+ get CLOSED () { return WebSocket.CLOSED; }+ get OPEN () { return WebSocket.OPEN; }++ /**+ * This deviates from the WHATWG interface since ws doesn't support the required+ * default "blob" type (instead we define a custom "nodebuffer" type).+ *+ * @type {String}+ */+ get binaryType () {+ return this._binaryType;+ }++ set binaryType (type) {+ if (constants$3.BINARY_TYPES.indexOf(type) < 0) return;++ this._binaryType = type;++ //+ // Allow to change `binaryType` on the fly.+ //+ if (this._receiver) this._receiver._binaryType = type;+ }++ /**+ * @type {Number}+ */+ get bufferedAmount () {+ if (!this._socket) return 0;++ //+ // `socket.bufferSize` is `undefined` if the socket is closed.+ //+ return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;+ }++ /**+ * @type {String}+ */+ get extensions () {+ return Object.keys(this._extensions).join();+ }++ /**+ * Set up the socket and the internal resources.+ *+ * @param {net.Socket} socket The network socket between the server and client+ * @param {Buffer} head The first packet of the upgraded stream+ * @param {Number} maxPayload The maximum allowed message size+ * @private+ */+ setSocket (socket, head, maxPayload) {+ const receiver$1 = new receiver(+ this._binaryType,+ this._extensions,+ maxPayload+ );++ this._sender = new sender(socket, this._extensions);+ this._receiver = receiver$1;+ this._socket = socket;++ receiver$1[kWebSocket] = this;+ socket[kWebSocket] = this;++ receiver$1.on('conclude', receiverOnConclude);+ receiver$1.on('drain', receiverOnDrain);+ receiver$1.on('error', receiverOnError);+ receiver$1.on('message', receiverOnMessage);+ receiver$1.on('ping', receiverOnPing);+ receiver$1.on('pong', receiverOnPong);++ socket.setTimeout(0);+ socket.setNoDelay();++ if (head.length > 0) socket.unshift(head);++ socket.on('close', socketOnClose);+ socket.on('data', socketOnData);+ socket.on('end', socketOnEnd);+ socket.on('error', socketOnError);++ this.readyState = WebSocket.OPEN;+ this.emit('open');+ }++ /**+ * Emit the `'close'` event.+ *+ * @private+ */+ emitClose () {+ this.readyState = WebSocket.CLOSED;++ if (!this._socket) {+ this.emit('close', this._closeCode, this._closeMessage);+ return;+ }++ if (this._extensions[permessageDeflate.extensionName]) {+ this._extensions[permessageDeflate.extensionName].cleanup();+ }++ this._receiver.removeAllListeners();+ this.emit('close', this._closeCode, this._closeMessage);+ }++ /**+ * Start a closing handshake.+ *+ * +----------+ +-----------+ +----------++ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -+ * | +----------+ +-----------+ +----------+ |+ * +----------+ +-----------+ |+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING+ * +----------+ +-----------+ |+ * | | | +---+ |+ * +------------------------+-->|fin| - - - -+ * | +---+ | +---++ * - - - - -|fin|<---------------------++ * +---++ *+ * @param {Number} code Status code explaining why the connection is closing+ * @param {String} data A string explaining why the connection is closing+ * @public+ */+ close (code, data) {+ if (this.readyState === WebSocket.CLOSED) return;+ if (this.readyState === WebSocket.CONNECTING) {+ const msg = 'WebSocket was closed before the connection was established';+ return abortHandshake(this, this._req, msg);+ }++ if (this.readyState === WebSocket.CLOSING) {+ if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();+ return;+ }++ this.readyState = WebSocket.CLOSING;+ this._sender.close(code, data, !this._isServer, (err) => {+ //+ // This error is handled by the `'error'` listener on the socket. We only+ // want to know if the close frame has been sent here.+ //+ if (err) return;++ this._closeFrameSent = true;++ if (this._socket.writable) {+ if (this._closeFrameReceived) this._socket.end();++ //+ // Ensure that the connection is closed even if the closing handshake+ // fails.+ //+ this._closeTimer = setTimeout(+ this._socket.destroy.bind(this._socket),+ closeTimeout+ );+ }+ });+ }++ /**+ * Send a ping.+ *+ * @param {*} data The data to send+ * @param {Boolean} mask Indicates whether or not to mask `data`+ * @param {Function} cb Callback which is executed when the ping is sent+ * @public+ */+ ping (data, mask, cb) {+ if (typeof data === 'function') {+ cb = data;+ data = mask = undefined;+ } else if (typeof mask === 'function') {+ cb = mask;+ mask = undefined;+ }++ if (this.readyState !== WebSocket.OPEN) {+ const err = new Error(+ `WebSocket is not open: readyState ${this.readyState} ` ++ `(${readyStates[this.readyState]})`+ );++ if (cb) return cb(err);+ throw err;+ }++ if (typeof data === 'number') data = data.toString();+ if (mask === undefined) mask = !this._isServer;+ this._sender.ping(data || constants$3.EMPTY_BUFFER, mask, cb);+ }++ /**+ * Send a pong.+ *+ * @param {*} data The data to send+ * @param {Boolean} mask Indicates whether or not to mask `data`+ * @param {Function} cb Callback which is executed when the pong is sent+ * @public+ */+ pong (data, mask, cb) {+ if (typeof data === 'function') {+ cb = data;+ data = mask = undefined;+ } else if (typeof mask === 'function') {+ cb = mask;+ mask = undefined;+ }++ if (this.readyState !== WebSocket.OPEN) {+ const err = new Error(+ `WebSocket is not open: readyState ${this.readyState} ` ++ `(${readyStates[this.readyState]})`+ );++ if (cb) return cb(err);+ throw err;+ }++ if (typeof data === 'number') data = data.toString();+ if (mask === undefined) mask = !this._isServer;+ this._sender.pong(data || constants$3.EMPTY_BUFFER, mask, cb);+ }++ /**+ * Send a data message.+ *+ * @param {*} data The message to send+ * @param {Object} options Options object+ * @param {Boolean} options.compress Specifies whether or not to compress `data`+ * @param {Boolean} options.binary Specifies whether `data` is binary or text+ * @param {Boolean} options.fin Specifies whether the fragment is the last one+ * @param {Boolean} options.mask Specifies whether or not to mask `data`+ * @param {Function} cb Callback which is executed when data is written out+ * @public+ */+ send (data, options, cb) {+ if (typeof options === 'function') {+ cb = options;+ options = {};+ }++ if (this.readyState !== WebSocket.OPEN) {+ const err = new Error(+ `WebSocket is not open: readyState ${this.readyState} ` ++ `(${readyStates[this.readyState]})`+ );++ if (cb) return cb(err);+ throw err;+ }++ if (typeof data === 'number') data = data.toString();++ const opts = Object.assign({+ binary: typeof data !== 'string',+ mask: !this._isServer,+ compress: true,+ fin: true+ }, options);++ if (!this._extensions[permessageDeflate.extensionName]) {+ opts.compress = false;+ }++ this._sender.send(data || constants$3.EMPTY_BUFFER, opts, cb);+ }++ /**+ * Forcibly close the connection.+ *+ * @public+ */+ terminate () {+ if (this.readyState === WebSocket.CLOSED) return;+ if (this.readyState === WebSocket.CONNECTING) {+ const msg = 'WebSocket was closed before the connection was established';+ return abortHandshake(this, this._req, msg);+ }++ if (this._socket) {+ this.readyState = WebSocket.CLOSING;+ this._socket.destroy();+ }+ }+}++readyStates.forEach((readyState, i) => {+ WebSocket[readyStates[i]] = i;+});++//+// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.+// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface+//+['open', 'error', 'close', 'message'].forEach((method) => {+ Object.defineProperty(WebSocket.prototype, `on${method}`, {+ /**+ * Return the listener of the event.+ *+ * @return {(Function|undefined)} The event listener or `undefined`+ * @public+ */+ get () {+ const listeners = this.listeners(method);+ for (var i = 0; i < listeners.length; i++) {+ if (listeners[i]._listener) return listeners[i]._listener;+ }+ },+ /**+ * Add a listener for the event.+ *+ * @param {Function} listener The listener to add+ * @public+ */+ set (listener) {+ const listeners = this.listeners(method);+ for (var i = 0; i < listeners.length; i++) {+ //+ // Remove only the listeners added via `addEventListener`.+ //+ if (listeners[i]._listener) this.removeListener(method, listeners[i]);+ }+ this.addEventListener(method, listener);+ }+ });+});++WebSocket.prototype.addEventListener = eventTarget.addEventListener;+WebSocket.prototype.removeEventListener = eventTarget.removeEventListener;++var websocket = WebSocket;++/**+ * Initialize a WebSocket client.+ *+ * @param {(String|url.Url|url.URL)} address The URL to which to connect+ * @param {String} protocols The subprotocols+ * @param {Object} options Connection options+ * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate+ * @param {Number} options.handshakeTimeout Timeout in milliseconds for the handshake request+ * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header+ * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header+ * @private+ */+function initAsClient (address, protocols, options) {+ options = Object.assign({+ protocolVersion: protocolVersions[1],+ perMessageDeflate: true+ }, options, {+ createConnection: undefined,+ socketPath: undefined,+ hostname: undefined,+ protocol: undefined,+ timeout: undefined,+ method: undefined,+ auth: undefined,+ host: undefined,+ path: undefined,+ port: undefined+ });++ if (protocolVersions.indexOf(options.protocolVersion) === -1) {+ throw new RangeError(+ `Unsupported protocol version: ${options.protocolVersion} ` ++ `(supported versions: ${protocolVersions.join(', ')})`+ );+ }++ this._isServer = false;++ var parsedUrl;++ if (typeof address === 'object' && address.href !== undefined) {+ parsedUrl = address;+ this.url = address.href;+ } else {+ parsedUrl = Url__default['default'].parse(address);+ this.url = address;+ }++ const isUnixSocket = parsedUrl.protocol === 'ws+unix:';++ if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {+ throw new Error(`Invalid URL: ${this.url}`);+ }++ const isSecure = parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';+ const key = crypto__default['default'].randomBytes(16).toString('base64');+ const httpObj = isSecure ? https__default['default'] : http__default['default'];+ const path = parsedUrl.search+ ? `${parsedUrl.pathname || '/'}${parsedUrl.search}`+ : parsedUrl.pathname || '/';+ var perMessageDeflate;++ options.createConnection = isSecure ? tlsConnect : netConnect;+ options.port = parsedUrl.port || (isSecure ? 443 : 80);+ options.host = parsedUrl.hostname.startsWith('[')+ ? parsedUrl.hostname.slice(1, -1)+ : parsedUrl.hostname;+ options.headers = Object.assign({+ 'Sec-WebSocket-Version': options.protocolVersion,+ 'Sec-WebSocket-Key': key,+ 'Connection': 'Upgrade',+ 'Upgrade': 'websocket'+ }, options.headers);+ options.path = path;++ if (options.perMessageDeflate) {+ perMessageDeflate = new permessageDeflate(+ options.perMessageDeflate !== true ? options.perMessageDeflate : {},+ false+ );+ options.headers['Sec-WebSocket-Extensions'] = extension.format({+ [permessageDeflate.extensionName]: perMessageDeflate.offer()+ });+ }+ if (protocols) {+ options.headers['Sec-WebSocket-Protocol'] = protocols;+ }+ if (options.origin) {+ if (options.protocolVersion < 13) {+ options.headers['Sec-WebSocket-Origin'] = options.origin;+ } else {+ options.headers.Origin = options.origin;+ }+ }+ if (parsedUrl.auth) {+ options.auth = parsedUrl.auth;+ } else if (parsedUrl.username || parsedUrl.password) {+ options.auth = `${parsedUrl.username}:${parsedUrl.password}`;+ }++ if (isUnixSocket) {+ const parts = path.split(':');++ if (options.agent == null && process.versions.modules < 57) {+ //+ // Setting `socketPath` in conjunction with `createConnection` without an+ // agent throws an error on Node.js < 8. Work around the issue by using a+ // different property.+ //+ options._socketPath = parts[0];+ } else {+ options.socketPath = parts[0];+ }++ options.path = parts[1];+ }++ var req = this._req = httpObj.get(options);++ if (options.handshakeTimeout) {+ req.setTimeout(+ options.handshakeTimeout,+ () => abortHandshake(this, req, 'Opening handshake has timed out')+ );+ }++ req.on('error', (err) => {+ if (this._req.aborted) return;++ req = this._req = null;+ this.readyState = WebSocket.CLOSING;+ this.emit('error', err);+ this.emitClose();+ });++ req.on('response', (res) => {+ if (this.emit('unexpected-response', req, res)) return;++ abortHandshake(this, req, `Unexpected server response: ${res.statusCode}`);+ });++ req.on('upgrade', (res, socket, head) => {+ this.emit('upgrade', res);++ //+ // The user may have closed the connection from a listener of the `upgrade`+ // event.+ //+ if (this.readyState !== WebSocket.CONNECTING) return;++ req = this._req = null;++ const digest = crypto__default['default'].createHash('sha1')+ .update(key + constants$3.GUID, 'binary')+ .digest('base64');++ if (res.headers['sec-websocket-accept'] !== digest) {+ abortHandshake(this, socket, 'Invalid Sec-WebSocket-Accept header');+ return;+ }++ const serverProt = res.headers['sec-websocket-protocol'];+ const protList = (protocols || '').split(/, */);+ var protError;++ if (!protocols && serverProt) {+ protError = 'Server sent a subprotocol but none was requested';+ } else if (protocols && !serverProt) {+ protError = 'Server sent no subprotocol';+ } else if (serverProt && protList.indexOf(serverProt) === -1) {+ protError = 'Server sent an invalid subprotocol';+ }++ if (protError) {+ abortHandshake(this, socket, protError);+ return;+ }++ if (serverProt) this.protocol = serverProt;++ if (perMessageDeflate) {+ try {+ const extensions = extension.parse(+ res.headers['sec-websocket-extensions']+ );++ if (extensions[permessageDeflate.extensionName]) {+ perMessageDeflate.accept(+ extensions[permessageDeflate.extensionName]+ );+ this._extensions[permessageDeflate.extensionName] = perMessageDeflate;+ }+ } catch (err) {+ abortHandshake(this, socket, 'Invalid Sec-WebSocket-Extensions header');+ return;+ }+ }++ this.setSocket(socket, head, 0);+ });+}++/**+ * Create a `net.Socket` and initiate a connection.+ *+ * @param {Object} options Connection options+ * @return {net.Socket} The newly created socket used to start the connection+ * @private+ */+function netConnect (options) {+ options.path = options.socketPath || options._socketPath || undefined;+ return net__default['default'].connect(options);+}++/**+ * Create a `tls.TLSSocket` and initiate a connection.+ *+ * @param {Object} options Connection options+ * @return {tls.TLSSocket} The newly created socket used to start the connection+ * @private+ */+function tlsConnect (options) {+ options.path = options.socketPath || options._socketPath || undefined;+ options.servername = options.servername || options.host;+ return tls__default['default'].connect(options);+}++/**+ * Abort the handshake and emit an error.+ *+ * @param {WebSocket} websocket The WebSocket instance+ * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the+ * socket to destroy+ * @param {String} message The error message+ * @private+ */+function abortHandshake (websocket, stream, message) {+ websocket.readyState = WebSocket.CLOSING;++ const err = new Error(message);+ Error.captureStackTrace(err, abortHandshake);++ if (stream.setHeader) {+ stream.abort();+ stream.once('abort', websocket.emitClose.bind(websocket));+ websocket.emit('error', err);+ } else {+ stream.destroy(err);+ stream.once('error', websocket.emit.bind(websocket, 'error'));+ stream.once('close', websocket.emitClose.bind(websocket));+ }+}++/**+ * The listener of the `Receiver` `'conclude'` event.+ *+ * @param {Number} code The status code+ * @param {String} reason The reason for closing+ * @private+ */+function receiverOnConclude (code, reason) {+ const websocket = this[kWebSocket];++ websocket._socket.removeListener('data', socketOnData);+ websocket._socket.resume();++ websocket._closeFrameReceived = true;+ websocket._closeMessage = reason;+ websocket._closeCode = code;++ if (code === 1005) websocket.close();+ else websocket.close(code, reason);+}++/**+ * The listener of the `Receiver` `'drain'` event.+ *+ * @private+ */+function receiverOnDrain () {+ this[kWebSocket]._socket.resume();+}++/**+ * The listener of the `Receiver` `'error'` event.+ *+ * @param {(RangeError|Error)} err The emitted error+ * @private+ */+function receiverOnError (err) {+ const websocket = this[kWebSocket];++ websocket._socket.removeListener('data', socketOnData);++ websocket.readyState = WebSocket.CLOSING;+ websocket._closeCode = err[constants$3.kStatusCode];+ websocket.emit('error', err);+ websocket._socket.destroy();+}++/**+ * The listener of the `Receiver` `'finish'` event.+ *+ * @private+ */+function receiverOnFinish () {+ this[kWebSocket].emitClose();+}++/**+ * The listener of the `Receiver` `'message'` event.+ *+ * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message+ * @private+ */+function receiverOnMessage (data) {+ this[kWebSocket].emit('message', data);+}++/**+ * The listener of the `Receiver` `'ping'` event.+ *+ * @param {Buffer} data The data included in the ping frame+ * @private+ */+function receiverOnPing (data) {+ const websocket = this[kWebSocket];++ websocket.pong(data, !websocket._isServer, constants$3.NOOP);+ websocket.emit('ping', data);+}++/**+ * The listener of the `Receiver` `'pong'` event.+ *+ * @param {Buffer} data The data included in the pong frame+ * @private+ */+function receiverOnPong (data) {+ this[kWebSocket].emit('pong', data);+}++/**+ * The listener of the `net.Socket` `'close'` event.+ *+ * @private+ */+function socketOnClose () {+ const websocket = this[kWebSocket];++ this.removeListener('close', socketOnClose);+ this.removeListener('end', socketOnEnd);++ websocket.readyState = WebSocket.CLOSING;++ //+ // The close frame might not have been received or the `'end'` event emitted,+ // for example, if the socket was destroyed due to an error. Ensure that the+ // `receiver` stream is closed after writing any remaining buffered data to+ // it. If the readable side of the socket is in flowing mode then there is no+ // buffered data as everything has been already written and `readable.read()`+ // will return `null`. If instead, the socket is paused, any possible buffered+ // data will be read as a single chunk and emitted synchronously in a single+ // `'data'` event.+ //+ websocket._socket.read();+ websocket._receiver.end();++ this.removeListener('data', socketOnData);+ this[kWebSocket] = undefined;++ clearTimeout(websocket._closeTimer);++ if (+ websocket._receiver._writableState.finished ||+ websocket._receiver._writableState.errorEmitted+ ) {+ websocket.emitClose();+ } else {+ websocket._receiver.on('error', receiverOnFinish);+ websocket._receiver.on('finish', receiverOnFinish);+ }+}++/**+ * The listener of the `net.Socket` `'data'` event.+ *+ * @param {Buffer} chunk A chunk of data+ * @private+ */+function socketOnData (chunk) {+ if (!this[kWebSocket]._receiver.write(chunk)) {+ this.pause();+ }+}++/**+ * The listener of the `net.Socket` `'end'` event.+ *+ * @private+ */+function socketOnEnd () {+ const websocket = this[kWebSocket];++ websocket.readyState = WebSocket.CLOSING;+ websocket._receiver.end();+ this.end();+}++/**+ * The listener of the `net.Socket` `'error'` event.+ *+ * @private+ */+function socketOnError () {+ const websocket = this[kWebSocket];++ this.removeListener('error', socketOnError);+ this.on('error', constants$3.NOOP);++ if (websocket) {+ websocket.readyState = WebSocket.CLOSING;+ this.destroy();+ }+}++/**+ * Class representing a WebSocket server.+ *+ * @extends EventEmitter+ */+class WebSocketServer extends EventEmitter__default['default'] {+ /**+ * Create a `WebSocketServer` instance.+ *+ * @param {Object} options Configuration options+ * @param {String} options.host The hostname where to bind the server+ * @param {Number} options.port The port where to bind the server+ * @param {http.Server} options.server A pre-created HTTP/S server to use+ * @param {Function} options.verifyClient An hook to reject connections+ * @param {Function} options.handleProtocols An hook to handle protocols+ * @param {String} options.path Accept only connections matching this path+ * @param {Boolean} options.noServer Enable no server mode+ * @param {Boolean} options.clientTracking Specifies whether or not to track clients+ * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate+ * @param {Number} options.maxPayload The maximum allowed message size+ * @param {Function} callback A listener for the `listening` event+ */+ constructor (options, callback) {+ super();++ options = Object.assign({+ maxPayload: 100 * 1024 * 1024,+ perMessageDeflate: false,+ handleProtocols: null,+ clientTracking: true,+ verifyClient: null,+ noServer: false,+ backlog: null, // use default (511 as implemented in net.js)+ server: null,+ host: null,+ path: null,+ port: null+ }, options);++ if (options.port == null && !options.server && !options.noServer) {+ throw new TypeError(+ 'One of the "port", "server", or "noServer" options must be specified'+ );+ }++ if (options.port != null) {+ this._server = http__default['default'].createServer((req, res) => {+ const body = http__default['default'].STATUS_CODES[426];++ res.writeHead(426, {+ 'Content-Length': body.length,+ 'Content-Type': 'text/plain'+ });+ res.end(body);+ });+ this._server.listen(options.port, options.host, options.backlog, callback);+ } else if (options.server) {+ this._server = options.server;+ }++ if (this._server) {+ this._removeListeners = addListeners(this._server, {+ listening: this.emit.bind(this, 'listening'),+ error: this.emit.bind(this, 'error'),+ upgrade: (req, socket, head) => {+ this.handleUpgrade(req, socket, head, (ws) => {+ this.emit('connection', ws, req);+ });+ }+ });+ }++ if (options.perMessageDeflate === true) options.perMessageDeflate = {};+ if (options.clientTracking) this.clients = new Set();+ this.options = options;+ }++ /**+ * Returns the bound address, the address family name, and port of the server+ * as reported by the operating system if listening on an IP socket.+ * If the server is listening on a pipe or UNIX domain socket, the name is+ * returned as a string.+ *+ * @return {(Object|String|null)} The address of the server+ * @public+ */+ address () {+ if (this.options.noServer) {+ throw new Error('The server is operating in "noServer" mode');+ }++ if (!this._server) return null;+ return this._server.address();+ }++ /**+ * Close the server.+ *+ * @param {Function} cb Callback+ * @public+ */+ close (cb) {+ //+ // Terminate all associated clients.+ //+ if (this.clients) {+ for (const client of this.clients) client.terminate();+ }++ const server = this._server;++ if (server) {+ this._removeListeners();+ this._removeListeners = this._server = null;++ //+ // Close the http server if it was internally created.+ //+ if (this.options.port != null) return server.close(cb);+ }++ if (cb) cb();+ }++ /**+ * See if a given request should be handled by this server instance.+ *+ * @param {http.IncomingMessage} req Request object to inspect+ * @return {Boolean} `true` if the request is valid, else `false`+ * @public+ */+ shouldHandle (req) {+ if (this.options.path && Url__default['default'].parse(req.url).pathname !== this.options.path) {+ return false;+ }++ return true;+ }++ /**+ * Handle a HTTP Upgrade request.+ *+ * @param {http.IncomingMessage} req The request object+ * @param {net.Socket} socket The network socket between the server and client+ * @param {Buffer} head The first packet of the upgraded stream+ * @param {Function} cb Callback+ * @public+ */+ handleUpgrade (req, socket, head, cb) {+ socket.on('error', socketOnError$1);++ const version = +req.headers['sec-websocket-version'];+ const extensions = {};++ if (+ req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' ||+ !req.headers['sec-websocket-key'] || (version !== 8 && version !== 13) ||+ !this.shouldHandle(req)+ ) {+ return abortHandshake$1(socket, 400);+ }++ if (this.options.perMessageDeflate) {+ const perMessageDeflate = new permessageDeflate(+ this.options.perMessageDeflate,+ true,+ this.options.maxPayload+ );++ try {+ const offers = extension.parse(+ req.headers['sec-websocket-extensions']+ );++ if (offers[permessageDeflate.extensionName]) {+ perMessageDeflate.accept(offers[permessageDeflate.extensionName]);+ extensions[permessageDeflate.extensionName] = perMessageDeflate;+ }+ } catch (err) {+ return abortHandshake$1(socket, 400);+ }+ }++ //+ // Optionally call external client verification handler.+ //+ if (this.options.verifyClient) {+ const info = {+ origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],+ secure: !!(req.connection.authorized || req.connection.encrypted),+ req+ };++ if (this.options.verifyClient.length === 2) {+ this.options.verifyClient(info, (verified, code, message, headers) => {+ if (!verified) {+ return abortHandshake$1(socket, code || 401, message, headers);+ }++ this.completeUpgrade(extensions, req, socket, head, cb);+ });+ return;+ }++ if (!this.options.verifyClient(info)) return abortHandshake$1(socket, 401);+ }++ this.completeUpgrade(extensions, req, socket, head, cb);+ }++ /**+ * Upgrade the connection to WebSocket.+ *+ * @param {Object} extensions The accepted extensions+ * @param {http.IncomingMessage} req The request object+ * @param {net.Socket} socket The network socket between the server and client+ * @param {Buffer} head The first packet of the upgraded stream+ * @param {Function} cb Callback+ * @private+ */+ completeUpgrade (extensions, req, socket, head, cb) {+ //+ // Destroy the socket if the client has already sent a FIN packet.+ //+ if (!socket.readable || !socket.writable) return socket.destroy();++ const key = crypto__default['default'].createHash('sha1')+ .update(req.headers['sec-websocket-key'] + constants$3.GUID, 'binary')+ .digest('base64');++ const headers = [+ 'HTTP/1.1 101 Switching Protocols',+ 'Upgrade: websocket',+ 'Connection: Upgrade',+ `Sec-WebSocket-Accept: ${key}`+ ];++ const ws = new websocket(null);+ var protocol = req.headers['sec-websocket-protocol'];++ if (protocol) {+ protocol = protocol.trim().split(/ *, */);++ //+ // Optionally call external protocol selection handler.+ //+ if (this.options.handleProtocols) {+ protocol = this.options.handleProtocols(protocol, req);+ } else {+ protocol = protocol[0];+ }++ if (protocol) {+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);+ ws.protocol = protocol;+ }+ }++ if (extensions[permessageDeflate.extensionName]) {+ const params = extensions[permessageDeflate.extensionName].params;+ const value = extension.format({+ [permessageDeflate.extensionName]: [params]+ });+ headers.push(`Sec-WebSocket-Extensions: ${value}`);+ ws._extensions = extensions;+ }++ //+ // Allow external modification/inspection of handshake headers.+ //+ this.emit('headers', headers, req);++ socket.write(headers.concat('\r\n').join('\r\n'));+ socket.removeListener('error', socketOnError$1);++ ws.setSocket(socket, head, this.options.maxPayload);++ if (this.clients) {+ this.clients.add(ws);+ ws.on('close', () => this.clients.delete(ws));+ }++ cb(ws);+ }+}++var websocketServer = WebSocketServer;++/**+ * Add event listeners on an `EventEmitter` using a map of <event, listener>+ * pairs.+ *+ * @param {EventEmitter} server The event emitter+ * @param {Object.<String, Function>} map The listeners to add+ * @return {Function} A function that will remove the added listeners when called+ * @private+ */+function addListeners (server, map) {+ for (const event of Object.keys(map)) server.on(event, map[event]);++ return function removeListeners () {+ for (const event of Object.keys(map)) {+ server.removeListener(event, map[event]);+ }+ };+}++/**+ * Handle premature socket errors.+ *+ * @private+ */+function socketOnError$1 () {+ this.destroy();+}++/**+ * Close the connection when preconditions are not fulfilled.+ *+ * @param {net.Socket} socket The socket of the upgrade request+ * @param {Number} code The HTTP response status code+ * @param {String} [message] The HTTP response body+ * @param {Object} [headers] Additional HTTP response headers+ * @private+ */+function abortHandshake$1 (socket, code, message, headers) {+ if (socket.writable) {+ message = message || http__default['default'].STATUS_CODES[code];+ headers = Object.assign({+ 'Connection': 'close',+ 'Content-type': 'text/html',+ 'Content-Length': Buffer.byteLength(message)+ }, headers);++ socket.write(+ `HTTP/1.1 ${code} ${http__default['default'].STATUS_CODES[code]}\r\n` ++ Object.keys(headers).map(h => `${h}: ${headers[h]}`).join('\r\n') ++ '\r\n\r\n' ++ message+ );+ }++ socket.removeListener('error', socketOnError$1);+ socket.destroy();+}++websocket.Server = websocketServer;+websocket.Receiver = receiver;+websocket.Sender = sender;++var ws = websocket;++/**+ * Copyright (c) 2016, Lee Byron+ * All rights reserved.+ *+ * This source code is licensed under the MIT license found in the+ * LICENSE file in the root directory of this source tree.+ *+ * @flow+ * @ignore+ */++/**+ * [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator)+ * is a *protocol* which describes a standard way to produce a sequence of+ * values, typically the values of the Iterable represented by this Iterator.+ *+ * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface)+ * it can be utilized by any version of JavaScript.+ *+ * @external Iterator+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator|MDN Iteration protocols}+ */++/**+ * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)+ * is a *protocol* which when implemented allows a JavaScript object to define+ * their iteration behavior, such as what values are looped over in a+ * [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)+ * loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables)+ * implement the Iterable protocol, including `Array` and `Map`.+ *+ * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface)+ * it can be utilized by any version of JavaScript.+ *+ * @external Iterable+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable|MDN Iteration protocols}+ */++// In ES2015 environments, Symbol exists+var SYMBOL /*: any */ = typeof Symbol === 'function' ? Symbol : void 0;++// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator+var SYMBOL_ITERATOR$1 = SYMBOL && SYMBOL.iterator;++/**+ * A property name to be used as the name of an Iterable's method responsible+ * for producing an Iterator, referred to as `@@iterator`. Typically represents+ * the value `Symbol.iterator` but falls back to the string `"@@iterator"` when+ * `Symbol.iterator` is not defined.+ *+ * Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`,+ * but do not use it for accessing existing Iterables, instead use+ * {@link getIterator} or {@link isIterable}.+ *+ * @example+ *+ * var $$iterator = require('iterall').$$iterator+ *+ * function Counter (to) {+ * this.to = to+ * }+ *+ * Counter.prototype[$$iterator] = function () {+ * return {+ * to: this.to,+ * num: 0,+ * next () {+ * if (this.num >= this.to) {+ * return { value: undefined, done: true }+ * }+ * return { value: this.num++, done: false }+ * }+ * }+ * }+ *+ * var counter = new Counter(3)+ * for (var number of counter) {+ * console.log(number) // 0 ... 1 ... 2+ * }+ *+ * @type {Symbol|string}+ */+/*:: declare export var $$iterator: '@@iterator'; */+var $$iterator = SYMBOL_ITERATOR$1 || '@@iterator';++/**+ * Returns true if the provided object implements the Iterator protocol via+ * either implementing a `Symbol.iterator` or `"@@iterator"` method.+ *+ * @example+ *+ * var isIterable = require('iterall').isIterable+ * isIterable([ 1, 2, 3 ]) // true+ * isIterable('ABC') // true+ * isIterable({ length: 1, 0: 'Alpha' }) // false+ * isIterable({ key: 'value' }) // false+ * isIterable(new Map()) // true+ *+ * @param obj+ * A value which might implement the Iterable protocol.+ * @return {boolean} true if Iterable.+ */+/*:: declare export function isIterable(obj: any): boolean; */+function isIterable(obj) {+ return !!getIteratorMethod(obj)+}++/**+ * Returns true if the provided object implements the Array-like protocol via+ * defining a positive-integer `length` property.+ *+ * @example+ *+ * var isArrayLike = require('iterall').isArrayLike+ * isArrayLike([ 1, 2, 3 ]) // true+ * isArrayLike('ABC') // true+ * isArrayLike({ length: 1, 0: 'Alpha' }) // true+ * isArrayLike({ key: 'value' }) // false+ * isArrayLike(new Map()) // false+ *+ * @param obj+ * A value which might implement the Array-like protocol.+ * @return {boolean} true if Array-like.+ */+/*:: declare export function isArrayLike(obj: any): boolean; */+function isArrayLike$1(obj) {+ var length = obj != null && obj.length;+ return typeof length === 'number' && length >= 0 && length % 1 === 0+}++/**+ * Returns true if the provided object is an Object (i.e. not a string literal)+ * and is either Iterable or Array-like.+ *+ * This may be used in place of [Array.isArray()][isArray] to determine if an+ * object should be iterated-over. It always excludes string literals and+ * includes Arrays (regardless of if it is Iterable). It also includes other+ * Array-like objects such as NodeList, TypedArray, and Buffer.+ *+ * @example+ *+ * var isCollection = require('iterall').isCollection+ * isCollection([ 1, 2, 3 ]) // true+ * isCollection('ABC') // false+ * isCollection({ length: 1, 0: 'Alpha' }) // true+ * isCollection({ key: 'value' }) // false+ * isCollection(new Map()) // true+ *+ * @example+ *+ * var forEach = require('iterall').forEach+ * if (isCollection(obj)) {+ * forEach(obj, function (value) {+ * console.log(value)+ * })+ * }+ *+ * @param obj+ * An Object value which might implement the Iterable or Array-like protocols.+ * @return {boolean} true if Iterable or Array-like Object.+ */+/*:: declare export function isCollection(obj: any): boolean; */+function isCollection$1(obj) {+ return Object(obj) === obj && (isArrayLike$1(obj) || isIterable(obj))+}++/**+ * If the provided object implements the Iterator protocol, its Iterator object+ * is returned. Otherwise returns undefined.+ *+ * @example+ *+ * var getIterator = require('iterall').getIterator+ * var iterator = getIterator([ 1, 2, 3 ])+ * iterator.next() // { value: 1, done: false }+ * iterator.next() // { value: 2, done: false }+ * iterator.next() // { value: 3, done: false }+ * iterator.next() // { value: undefined, done: true }+ *+ * @template T the type of each iterated value+ * @param {Iterable<T>} iterable+ * An Iterable object which is the source of an Iterator.+ * @return {Iterator<T>} new Iterator instance.+ */+/*:: declare export var getIterator:+ & (<+TValue>(iterable: Iterable<TValue>) => Iterator<TValue>)+ & ((iterable: mixed) => void | Iterator<mixed>); */+function getIterator(iterable) {+ var method = getIteratorMethod(iterable);+ if (method) {+ return method.call(iterable)+ }+}++/**+ * If the provided object implements the Iterator protocol, the method+ * responsible for producing its Iterator object is returned.+ *+ * This is used in rare cases for performance tuning. This method must be called+ * with obj as the contextual this-argument.+ *+ * @example+ *+ * var getIteratorMethod = require('iterall').getIteratorMethod+ * var myArray = [ 1, 2, 3 ]+ * var method = getIteratorMethod(myArray)+ * if (method) {+ * var iterator = method.call(myArray)+ * }+ *+ * @template T the type of each iterated value+ * @param {Iterable<T>} iterable+ * An Iterable object which defines an `@@iterator` method.+ * @return {function(): Iterator<T>} `@@iterator` method.+ */+/*:: declare export var getIteratorMethod:+ & (<+TValue>(iterable: Iterable<TValue>) => (() => Iterator<TValue>))+ & ((iterable: mixed) => (void | (() => Iterator<mixed>))); */+function getIteratorMethod(iterable) {+ if (iterable != null) {+ var method =+ (SYMBOL_ITERATOR$1 && iterable[SYMBOL_ITERATOR$1]) || iterable['@@iterator'];+ if (typeof method === 'function') {+ return method+ }+ }+}++/**+ * Similar to {@link getIterator}, this method returns a new Iterator given an+ * Iterable. However it will also create an Iterator for a non-Iterable+ * Array-like collection, such as Array in a non-ES2015 environment.+ *+ * `createIterator` is complimentary to `forEach`, but allows a "pull"-based+ * iteration as opposed to `forEach`'s "push"-based iteration.+ *+ * `createIterator` produces an Iterator for Array-likes with the same behavior+ * as ArrayIteratorPrototype described in the ECMAScript specification, and+ * does *not* skip over "holes".+ *+ * @example+ *+ * var createIterator = require('iterall').createIterator+ *+ * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' }+ * var iterator = createIterator(myArraylike)+ * iterator.next() // { value: 'Alpha', done: false }+ * iterator.next() // { value: 'Bravo', done: false }+ * iterator.next() // { value: 'Charlie', done: false }+ * iterator.next() // { value: undefined, done: true }+ *+ * @template T the type of each iterated value+ * @param {Iterable<T>|{ length: number }} collection+ * An Iterable or Array-like object to produce an Iterator.+ * @return {Iterator<T>} new Iterator instance.+ */+/*:: declare export var createIterator:+ & (<+TValue>(collection: Iterable<TValue>) => Iterator<TValue>)+ & ((collection: {length: number}) => Iterator<mixed>)+ & ((collection: mixed) => (void | Iterator<mixed>)); */+function createIterator(collection) {+ if (collection != null) {+ var iterator = getIterator(collection);+ if (iterator) {+ return iterator+ }+ if (isArrayLike$1(collection)) {+ return new ArrayLikeIterator(collection)+ }+ }+}++// When the object provided to `createIterator` is not Iterable but is+// Array-like, this simple Iterator is created.+function ArrayLikeIterator(obj) {+ this._o = obj;+ this._i = 0;+}++// Note: all Iterators are themselves Iterable.+ArrayLikeIterator.prototype[$$iterator] = function() {+ return this+};++// A simple state-machine determines the IteratorResult returned, yielding+// each value in the Array-like object in order of their indicies.+ArrayLikeIterator.prototype.next = function() {+ if (this._o === void 0 || this._i >= this._o.length) {+ this._o = void 0;+ return { value: void 0, done: true }+ }+ return { value: this._o[this._i++], done: false }+};++/**+ * Given an object which either implements the Iterable protocol or is+ * Array-like, iterate over it, calling the `callback` at each iteration.+ *+ * Use `forEach` where you would expect to use a `for ... of` loop in ES6.+ * However `forEach` adheres to the behavior of [Array#forEach][] described in+ * the ECMAScript specification, skipping over "holes" in Array-likes. It will+ * also delegate to a `forEach` method on `collection` if one is defined,+ * ensuring native performance for `Arrays`.+ *+ * Similar to [Array#forEach][], the `callback` function accepts three+ * arguments, and is provided with `thisArg` as the calling context.+ *+ * Note: providing an infinite Iterator to forEach will produce an error.+ *+ * [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach+ *+ * @example+ *+ * var forEach = require('iterall').forEach+ *+ * forEach(myIterable, function (value, index, iterable) {+ * console.log(value, index, iterable === myIterable)+ * })+ *+ * @example+ *+ * // ES6:+ * for (let value of myIterable) {+ * console.log(value)+ * }+ *+ * // Any JavaScript environment:+ * forEach(myIterable, function (value) {+ * console.log(value)+ * })+ *+ * @template T the type of each iterated value+ * @param {Iterable<T>|{ length: number }} collection+ * The Iterable or array to iterate over.+ * @param {function(T, number, object)} callback+ * Function to execute for each iteration, taking up to three arguments+ * @param [thisArg]+ * Optional. Value to use as `this` when executing `callback`.+ */+/*:: declare export var forEach:+ & (<+TValue, TCollection: Iterable<TValue>>(+ collection: TCollection,+ callbackFn: (value: TValue, index: number, collection: TCollection) => any,+ thisArg?: any+ ) => void)+ & (<TCollection: {length: number}>(+ collection: TCollection,+ callbackFn: (value: mixed, index: number, collection: TCollection) => any,+ thisArg?: any+ ) => void); */+function forEach(collection, callback, thisArg) {+ if (collection != null) {+ if (typeof collection.forEach === 'function') {+ return collection.forEach(callback, thisArg)+ }+ var i = 0;+ var iterator = getIterator(collection);+ if (iterator) {+ var step;+ while (!(step = iterator.next()).done) {+ callback.call(thisArg, step.value, i++, collection);+ // Infinite Iterators could cause forEach to run forever.+ // After a very large number of iterations, produce an error.+ /* istanbul ignore if */+ if (i > 9999999) {+ throw new TypeError('Near-infinite iteration.')+ }+ }+ } else if (isArrayLike$1(collection)) {+ for (; i < collection.length; i++) {+ if (collection.hasOwnProperty(i)) {+ callback.call(thisArg, collection[i], i, collection);+ }+ }+ }+ }+}++/////////////////////////////////////////////////////+// //+// ASYNC ITERATORS //+// //+/////////////////////////////////////////////////////++/**+ * [AsyncIterable](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface)+ * is a *protocol* which when implemented allows a JavaScript object to define+ * an asynchronous iteration behavior, such as what values are looped over in+ * a [`for-await-of`](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements)+ * loop or `iterall`'s {@link forAwaitEach} function.+ *+ * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/)+ * it can be utilized by any version of JavaScript.+ *+ * @external AsyncIterable+ * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface|Async Iteration Proposal}+ * @template T The type of each iterated value+ * @property {function (): AsyncIterator<T>} Symbol.asyncIterator+ * A method which produces an AsyncIterator for this AsyncIterable.+ */++/**+ * [AsyncIterator](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface)+ * is a *protocol* which describes a standard way to produce and consume an+ * asynchronous sequence of values, typically the values of the+ * {@link AsyncIterable} represented by this {@link AsyncIterator}.+ *+ * AsyncIterator is similar to Observable or Stream. Like an {@link Iterator} it+ * also as a `next()` method, however instead of an IteratorResult,+ * calling this method returns a {@link Promise} for a IteratorResult.+ *+ * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/)+ * it can be utilized by any version of JavaScript.+ *+ * @external AsyncIterator+ * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface|Async Iteration Proposal}+ */++// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator+var SYMBOL_ASYNC_ITERATOR$1 = SYMBOL && SYMBOL.asyncIterator;++/**+ * A property name to be used as the name of an AsyncIterable's method+ * responsible for producing an Iterator, referred to as `@@asyncIterator`.+ * Typically represents the value `Symbol.asyncIterator` but falls back to the+ * string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined.+ *+ * Use `$$asyncIterator` for defining new AsyncIterables instead of+ * `Symbol.asyncIterator`, but do not use it for accessing existing Iterables,+ * instead use {@link getAsyncIterator} or {@link isAsyncIterable}.+ *+ * @example+ *+ * var $$asyncIterator = require('iterall').$$asyncIterator+ *+ * function Chirper (to) {+ * this.to = to+ * }+ *+ * Chirper.prototype[$$asyncIterator] = function () {+ * return {+ * to: this.to,+ * num: 0,+ * next () {+ * return new Promise(resolve => {+ * if (this.num >= this.to) {+ * resolve({ value: undefined, done: true })+ * } else {+ * setTimeout(() => {+ * resolve({ value: this.num++, done: false })+ * }, 1000)+ * }+ * })+ * }+ * }+ * }+ *+ * var chirper = new Chirper(3)+ * for await (var number of chirper) {+ * console.log(number) // 0 ...wait... 1 ...wait... 2+ * }+ *+ * @type {Symbol|string}+ */+/*:: declare export var $$asyncIterator: '@@asyncIterator'; */+var $$asyncIterator = SYMBOL_ASYNC_ITERATOR$1 || '@@asyncIterator';++/**+ * Returns true if the provided object implements the AsyncIterator protocol via+ * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method.+ *+ * @example+ *+ * var isAsyncIterable = require('iterall').isAsyncIterable+ * isAsyncIterable(myStream) // true+ * isAsyncIterable('ABC') // false+ *+ * @param obj+ * A value which might implement the AsyncIterable protocol.+ * @return {boolean} true if AsyncIterable.+ */+/*:: declare export function isAsyncIterable(obj: any): boolean; */+function isAsyncIterable$1(obj) {+ return !!getAsyncIteratorMethod(obj)+}++/**+ * If the provided object implements the AsyncIterator protocol, its+ * AsyncIterator object is returned. Otherwise returns undefined.+ *+ * @example+ *+ * var getAsyncIterator = require('iterall').getAsyncIterator+ * var asyncIterator = getAsyncIterator(myStream)+ * asyncIterator.next().then(console.log) // { value: 1, done: false }+ * asyncIterator.next().then(console.log) // { value: 2, done: false }+ * asyncIterator.next().then(console.log) // { value: 3, done: false }+ * asyncIterator.next().then(console.log) // { value: undefined, done: true }+ *+ * @template T the type of each iterated value+ * @param {AsyncIterable<T>} asyncIterable+ * An AsyncIterable object which is the source of an AsyncIterator.+ * @return {AsyncIterator<T>} new AsyncIterator instance.+ */+/*:: declare export var getAsyncIterator:+ & (<+TValue>(asyncIterable: AsyncIterable<TValue>) => AsyncIterator<TValue>)+ & ((asyncIterable: mixed) => (void | AsyncIterator<mixed>)); */+function getAsyncIterator(asyncIterable) {+ var method = getAsyncIteratorMethod(asyncIterable);+ if (method) {+ return method.call(asyncIterable)+ }+}++/**+ * If the provided object implements the AsyncIterator protocol, the method+ * responsible for producing its AsyncIterator object is returned.+ *+ * This is used in rare cases for performance tuning. This method must be called+ * with obj as the contextual this-argument.+ *+ * @example+ *+ * var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod+ * var method = getAsyncIteratorMethod(myStream)+ * if (method) {+ * var asyncIterator = method.call(myStream)+ * }+ *+ * @template T the type of each iterated value+ * @param {AsyncIterable<T>} asyncIterable+ * An AsyncIterable object which defines an `@@asyncIterator` method.+ * @return {function(): AsyncIterator<T>} `@@asyncIterator` method.+ */+/*:: declare export var getAsyncIteratorMethod:+ & (<+TValue>(asyncIterable: AsyncIterable<TValue>) => (() => AsyncIterator<TValue>))+ & ((asyncIterable: mixed) => (void | (() => AsyncIterator<mixed>))); */+function getAsyncIteratorMethod(asyncIterable) {+ if (asyncIterable != null) {+ var method =+ (SYMBOL_ASYNC_ITERATOR$1 && asyncIterable[SYMBOL_ASYNC_ITERATOR$1]) ||+ asyncIterable['@@asyncIterator'];+ if (typeof method === 'function') {+ return method+ }+ }+}++/**+ * Similar to {@link getAsyncIterator}, this method returns a new AsyncIterator+ * given an AsyncIterable. However it will also create an AsyncIterator for a+ * non-async Iterable as well as non-Iterable Array-like collection, such as+ * Array in a pre-ES2015 environment.+ *+ * `createAsyncIterator` is complimentary to `forAwaitEach`, but allows a+ * buffering "pull"-based iteration as opposed to `forAwaitEach`'s+ * "push"-based iteration.+ *+ * `createAsyncIterator` produces an AsyncIterator for non-async Iterables as+ * described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects).+ *+ * > Note: Creating `AsyncIterator`s requires the existence of `Promise`.+ * > While `Promise` has been available in modern browsers for a number of+ * > years, legacy browsers (like IE 11) may require a polyfill.+ *+ * @example+ *+ * var createAsyncIterator = require('iterall').createAsyncIterator+ *+ * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' }+ * var iterator = createAsyncIterator(myArraylike)+ * iterator.next().then(console.log) // { value: 'Alpha', done: false }+ * iterator.next().then(console.log) // { value: 'Bravo', done: false }+ * iterator.next().then(console.log) // { value: 'Charlie', done: false }+ * iterator.next().then(console.log) // { value: undefined, done: true }+ *+ * @template T the type of each iterated value+ * @param {AsyncIterable<T>|Iterable<T>|{ length: number }} source+ * An AsyncIterable, Iterable, or Array-like object to produce an Iterator.+ * @return {AsyncIterator<T>} new AsyncIterator instance.+ */+/*:: declare export var createAsyncIterator:+ & (<+TValue>(+ collection: Iterable<Promise<TValue> | TValue> | AsyncIterable<TValue>+ ) => AsyncIterator<TValue>)+ & ((collection: {length: number}) => AsyncIterator<mixed>)+ & ((collection: mixed) => (void | AsyncIterator<mixed>)); */+function createAsyncIterator(source) {+ if (source != null) {+ var asyncIterator = getAsyncIterator(source);+ if (asyncIterator) {+ return asyncIterator+ }+ var iterator = createIterator(source);+ if (iterator) {+ return new AsyncFromSyncIterator(iterator)+ }+ }+}++// When the object provided to `createAsyncIterator` is not AsyncIterable but is+// sync Iterable, this simple wrapper is created.+function AsyncFromSyncIterator(iterator) {+ this._i = iterator;+}++// Note: all AsyncIterators are themselves AsyncIterable.+AsyncFromSyncIterator.prototype[$$asyncIterator] = function() {+ return this+};++// A simple state-machine determines the IteratorResult returned, yielding+// each value in the Array-like object in order of their indicies.+AsyncFromSyncIterator.prototype.next = function(value) {+ return unwrapAsyncFromSync(this._i, 'next', value)+};++AsyncFromSyncIterator.prototype.return = function(value) {+ return this._i.return+ ? unwrapAsyncFromSync(this._i, 'return', value)+ : Promise.resolve({ value: value, done: true })+};++AsyncFromSyncIterator.prototype.throw = function(value) {+ return this._i.throw+ ? unwrapAsyncFromSync(this._i, 'throw', value)+ : Promise.reject(value)+};++function unwrapAsyncFromSync(iterator, fn, value) {+ var step;+ return new Promise(function(resolve) {+ step = iterator[fn](value);+ resolve(step.value);+ }).then(function(value) {+ return { value: value, done: step.done }+ })+}++/**+ * Given an object which either implements the AsyncIterable protocol or is+ * Array-like, iterate over it, calling the `callback` at each iteration.+ *+ * Use `forAwaitEach` where you would expect to use a [for-await-of](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) loop.+ *+ * Similar to [Array#forEach][], the `callback` function accepts three+ * arguments, and is provided with `thisArg` as the calling context.+ *+ * > Note: Using `forAwaitEach` requires the existence of `Promise`.+ * > While `Promise` has been available in modern browsers for a number of+ * > years, legacy browsers (like IE 11) may require a polyfill.+ *+ * @example+ *+ * var forAwaitEach = require('iterall').forAwaitEach+ *+ * forAwaitEach(myIterable, function (value, index, iterable) {+ * console.log(value, index, iterable === myIterable)+ * })+ *+ * @example+ *+ * // ES2017:+ * for await (let value of myAsyncIterable) {+ * console.log(await doSomethingAsync(value))+ * }+ * console.log('done')+ *+ * // Any JavaScript environment:+ * forAwaitEach(myAsyncIterable, function (value) {+ * return doSomethingAsync(value).then(console.log)+ * }).then(function () {+ * console.log('done')+ * })+ *+ * @template T the type of each iterated value+ * @param {AsyncIterable<T>|Iterable<Promise<T> | T>|{ length: number }} source+ * The AsyncIterable or array to iterate over.+ * @param {function(T, number, object)} callback+ * Function to execute for each iteration, taking up to three arguments+ * @param [thisArg]+ * Optional. Value to use as `this` when executing `callback`.+ */+/*:: declare export var forAwaitEach:+ & (<+TValue, TCollection: Iterable<Promise<TValue> | TValue> | AsyncIterable<TValue>>(+ collection: TCollection,+ callbackFn: (value: TValue, index: number, collection: TCollection) => any,+ thisArg?: any+ ) => Promise<void>)+ & (<TCollection: { length: number }>(+ collection: TCollection,+ callbackFn: (value: mixed, index: number, collection: TCollection) => any,+ thisArg?: any+ ) => Promise<void>); */+function forAwaitEach(source, callback, thisArg) {+ var asyncIterator = createAsyncIterator(source);+ if (asyncIterator) {+ var i = 0;+ return new Promise(function(resolve, reject) {+ function next() {+ asyncIterator+ .next()+ .then(function(step) {+ if (!step.done) {+ Promise.resolve(callback.call(thisArg, step.value, i++, source))+ .then(next)+ .catch(reject);+ } else {+ resolve();+ }+ // Explicitly return null, silencing bluebird-style warnings.+ return null+ })+ .catch(reject);+ // Explicitly return null, silencing bluebird-style warnings.+ return null+ }+ next();+ })+ }+}++var iterall = /*#__PURE__*/Object.freeze({+ __proto__: null,+ $$iterator: $$iterator,+ isIterable: isIterable,+ isArrayLike: isArrayLike$1,+ isCollection: isCollection$1,+ getIterator: getIterator,+ getIteratorMethod: getIteratorMethod,+ createIterator: createIterator,+ forEach: forEach,+ $$asyncIterator: $$asyncIterator,+ isAsyncIterable: isAsyncIterable$1,+ getAsyncIterator: getAsyncIterator,+ getAsyncIteratorMethod: getAsyncIteratorMethod,+ createAsyncIterator: createAsyncIterator,+ forAwaitEach: forAwaitEach+});++var iterall_1 = /*@__PURE__*/getAugmentedNamespace(iterall);++var emptyIterable = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true });+exports.createEmptyIterable = void 0;++exports.createEmptyIterable = function () {+ var _a;+ return _a = {+ next: function () {+ return Promise.resolve({ value: undefined, done: true });+ },+ return: function () {+ return Promise.resolve({ value: undefined, done: true });+ },+ throw: function (e) {+ return Promise.reject(e);+ }+ },+ _a[iterall_1.$$asyncIterator] = function () {+ return this;+ },+ _a;+};++});++var graphql_1 = /*@__PURE__*/getAugmentedNamespace(graphql$1);++var isSubscriptions = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true });+exports.isASubscriptionOperation = void 0;++exports.isASubscriptionOperation = function (document, operationName) {+ var operationAST = graphql_1.getOperationAST(document, operationName);+ return !!operationAST && operationAST.operation === 'subscription';+};++});++var parseLegacyProtocol = createCommonjsModule(function (module, exports) {+var __assign = (commonjsGlobal && commonjsGlobal.__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);+};+Object.defineProperty(exports, "__esModule", { value: true });+exports.parseLegacyProtocolMessage = void 0;++exports.parseLegacyProtocolMessage = function (connectionContext, message) {+ var messageToReturn = message;+ switch (message.type) {+ case messageTypes.default.INIT:+ connectionContext.isLegacy = true;+ messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.GQL_CONNECTION_INIT });+ break;+ case messageTypes.default.SUBSCRIPTION_START:+ messageToReturn = {+ id: message.id,+ type: messageTypes.default.GQL_START,+ payload: {+ query: message.query,+ operationName: message.operationName,+ variables: message.variables,+ },+ };+ break;+ case messageTypes.default.SUBSCRIPTION_END:+ messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.GQL_STOP });+ break;+ case messageTypes.default.GQL_CONNECTION_ACK:+ if (connectionContext.isLegacy) {+ messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.INIT_SUCCESS });+ }+ break;+ case messageTypes.default.GQL_CONNECTION_ERROR:+ if (connectionContext.isLegacy) {+ messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.INIT_FAIL, payload: message.payload.message ? { error: message.payload.message } : message.payload });+ }+ break;+ case messageTypes.default.GQL_ERROR:+ if (connectionContext.isLegacy) {+ messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.SUBSCRIPTION_FAIL });+ }+ break;+ case messageTypes.default.GQL_DATA:+ if (connectionContext.isLegacy) {+ messageToReturn = __assign(__assign({}, message), { type: messageTypes.default.SUBSCRIPTION_DATA });+ }+ break;+ case messageTypes.default.GQL_COMPLETE:+ if (connectionContext.isLegacy) {+ messageToReturn = null;+ }+ break;+ case messageTypes.default.SUBSCRIPTION_SUCCESS:+ if (!connectionContext.isLegacy) {+ messageToReturn = null;+ }+ break;+ }+ return messageToReturn;+};++});++var server = createCommonjsModule(function (module, exports) {+Object.defineProperty(exports, "__esModule", { value: true });+exports.SubscriptionServer = void 0;++++++++++var isWebSocketServer = function (socket) { return socket.on; };+var SubscriptionServer = (function () {+ function SubscriptionServer(options, socketOptionsOrServer) {+ var _this = this;+ var onOperation = options.onOperation, onOperationComplete = options.onOperationComplete, onConnect = options.onConnect, onDisconnect = options.onDisconnect, keepAlive = options.keepAlive;+ this.specifiedRules = options.validationRules || graphql_1.specifiedRules;+ this.loadExecutor(options);+ this.onOperation = onOperation;+ this.onOperationComplete = onOperationComplete;+ this.onConnect = onConnect;+ this.onDisconnect = onDisconnect;+ this.keepAlive = keepAlive;+ if (isWebSocketServer(socketOptionsOrServer)) {+ this.wsServer = socketOptionsOrServer;+ }+ else {+ this.wsServer = new ws.Server(socketOptionsOrServer || {});+ }+ var connectionHandler = (function (socket, request) {+ socket.upgradeReq = request;+ if (socket.protocol === undefined ||+ (socket.protocol.indexOf(protocol.GRAPHQL_WS) === -1 && socket.protocol.indexOf(protocol.GRAPHQL_SUBSCRIPTIONS) === -1)) {+ socket.close(1002);+ return;+ }+ var connectionContext = Object.create(null);+ connectionContext.initPromise = Promise.resolve(true);+ connectionContext.isLegacy = false;+ connectionContext.socket = socket;+ connectionContext.request = request;+ connectionContext.operations = {};+ var connectionClosedHandler = function (error) {+ if (error) {+ _this.sendError(connectionContext, '', { message: error.message ? error.message : error }, messageTypes.default.GQL_CONNECTION_ERROR);+ setTimeout(function () {+ connectionContext.socket.close(1011);+ }, 10);+ }+ _this.onClose(connectionContext);+ if (_this.onDisconnect) {+ _this.onDisconnect(socket, connectionContext);+ }+ };+ socket.on('error', connectionClosedHandler);+ socket.on('close', connectionClosedHandler);+ socket.on('message', _this.onMessage(connectionContext));+ });+ this.wsServer.on('connection', connectionHandler);+ this.closeHandler = function () {+ _this.wsServer.removeListener('connection', connectionHandler);+ _this.wsServer.close();+ };+ }+ SubscriptionServer.create = function (options, socketOptionsOrServer) {+ return new SubscriptionServer(options, socketOptionsOrServer);+ };+ Object.defineProperty(SubscriptionServer.prototype, "server", {+ get: function () {+ return this.wsServer;+ },+ enumerable: false,+ configurable: true+ });+ SubscriptionServer.prototype.close = function () {+ this.closeHandler();+ };+ SubscriptionServer.prototype.loadExecutor = function (options) {+ var execute = options.execute, subscribe = options.subscribe, schema = options.schema, rootValue = options.rootValue;+ if (!execute) {+ throw new Error('Must provide `execute` for websocket server constructor.');+ }+ this.schema = schema;+ this.rootValue = rootValue;+ this.execute = execute;+ this.subscribe = subscribe;+ };+ SubscriptionServer.prototype.unsubscribe = function (connectionContext, opId) {+ if (connectionContext.operations && connectionContext.operations[opId]) {+ if (connectionContext.operations[opId].return) {+ connectionContext.operations[opId].return();+ }+ delete connectionContext.operations[opId];+ if (this.onOperationComplete) {+ this.onOperationComplete(connectionContext.socket, opId);+ }+ }+ };+ SubscriptionServer.prototype.onClose = function (connectionContext) {+ var _this = this;+ Object.keys(connectionContext.operations).forEach(function (opId) {+ _this.unsubscribe(connectionContext, opId);+ });+ };+ SubscriptionServer.prototype.onMessage = function (connectionContext) {+ var _this = this;+ return function (message) {+ var parsedMessage;+ try {+ parsedMessage = parseLegacyProtocol.parseLegacyProtocolMessage(connectionContext, JSON.parse(message));+ }+ catch (e) {+ _this.sendError(connectionContext, null, { message: e.message }, messageTypes.default.GQL_CONNECTION_ERROR);+ return;+ }+ var opId = parsedMessage.id;+ switch (parsedMessage.type) {+ case messageTypes.default.GQL_CONNECTION_INIT:+ if (_this.onConnect) {+ connectionContext.initPromise = new Promise(function (resolve, reject) {+ try {+ resolve(_this.onConnect(parsedMessage.payload, connectionContext.socket, connectionContext));+ }+ catch (e) {+ reject(e);+ }+ });+ }+ connectionContext.initPromise.then(function (result) {+ if (result === false) {+ throw new Error('Prohibited connection!');+ }+ _this.sendMessage(connectionContext, undefined, messageTypes.default.GQL_CONNECTION_ACK, undefined);+ if (_this.keepAlive) {+ _this.sendKeepAlive(connectionContext);+ var keepAliveTimer_1 = setInterval(function () {+ if (connectionContext.socket.readyState === ws.OPEN) {+ _this.sendKeepAlive(connectionContext);+ }+ else {+ clearInterval(keepAliveTimer_1);+ }+ }, _this.keepAlive);+ }+ }).catch(function (error) {+ _this.sendError(connectionContext, opId, { message: error.message }, messageTypes.default.GQL_CONNECTION_ERROR);+ setTimeout(function () {+ connectionContext.socket.close(1011);+ }, 10);+ });+ break;+ case messageTypes.default.GQL_CONNECTION_TERMINATE:+ connectionContext.socket.close();+ break;+ case messageTypes.default.GQL_START:+ connectionContext.initPromise.then(function (initResult) {+ if (connectionContext.operations && connectionContext.operations[opId]) {+ _this.unsubscribe(connectionContext, opId);+ }+ var baseParams = {+ query: parsedMessage.payload.query,+ variables: parsedMessage.payload.variables,+ operationName: parsedMessage.payload.operationName,+ context: isObject_1.default(initResult) ? Object.assign(Object.create(Object.getPrototypeOf(initResult)), initResult) : {},+ formatResponse: undefined,+ formatError: undefined,+ callback: undefined,+ schema: _this.schema,+ };+ var promisedParams = Promise.resolve(baseParams);+ connectionContext.operations[opId] = emptyIterable.createEmptyIterable();+ if (_this.onOperation) {+ var messageForCallback = parsedMessage;+ promisedParams = Promise.resolve(_this.onOperation(messageForCallback, baseParams, connectionContext.socket));+ }+ return promisedParams.then(function (params) {+ if (typeof params !== 'object') {+ var error = "Invalid params returned from onOperation! return values must be an object!";+ _this.sendError(connectionContext, opId, { message: error });+ throw new Error(error);+ }+ if (!params.schema) {+ var error = 'Missing schema information. The GraphQL schema should be provided either statically in' ++ ' the `SubscriptionServer` constructor or as a property on the object returned from onOperation!';+ _this.sendError(connectionContext, opId, { message: error });+ throw new Error(error);+ }+ var document = typeof baseParams.query !== 'string' ? baseParams.query : graphql_1.parse(baseParams.query);+ var executionPromise;+ var validationErrors = graphql_1.validate(params.schema, document, _this.specifiedRules);+ if (validationErrors.length > 0) {+ executionPromise = Promise.resolve({ errors: validationErrors });+ }+ else {+ var executor = _this.execute;+ if (_this.subscribe && isSubscriptions.isASubscriptionOperation(document, params.operationName)) {+ executor = _this.subscribe;+ }+ executionPromise = Promise.resolve(executor(params.schema, document, _this.rootValue, params.context, params.variables, params.operationName));+ }+ return executionPromise.then(function (executionResult) { return ({+ executionIterable: iterall_1.isAsyncIterable(executionResult) ?+ executionResult : iterall_1.createAsyncIterator([executionResult]),+ params: params,+ }); });+ }).then(function (_a) {+ var executionIterable = _a.executionIterable, params = _a.params;+ iterall_1.forAwaitEach(executionIterable, function (value) {+ var result = value;+ if (params.formatResponse) {+ try {+ result = params.formatResponse(value, params);+ }+ catch (err) {+ console.error('Error in formatResponse function:', err);+ }+ }+ _this.sendMessage(connectionContext, opId, messageTypes.default.GQL_DATA, result);+ })+ .then(function () {+ _this.sendMessage(connectionContext, opId, messageTypes.default.GQL_COMPLETE, null);+ })+ .catch(function (e) {+ var error = e;+ if (params.formatError) {+ try {+ error = params.formatError(e, params);+ }+ catch (err) {+ console.error('Error in formatError function: ', err);+ }+ }+ if (Object.keys(error).length === 0) {+ error = { name: error.name, message: error.message };+ }+ _this.sendError(connectionContext, opId, error);+ });+ return executionIterable;+ }).then(function (subscription) {+ connectionContext.operations[opId] = subscription;+ }).then(function () {+ _this.sendMessage(connectionContext, opId, messageTypes.default.SUBSCRIPTION_SUCCESS, undefined);+ }).catch(function (e) {+ if (e.errors) {+ _this.sendMessage(connectionContext, opId, messageTypes.default.GQL_DATA, { errors: e.errors });+ }+ else {+ _this.sendError(connectionContext, opId, { message: e.message });+ }+ _this.unsubscribe(connectionContext, opId);+ return;+ });+ }).catch(function (error) {+ _this.sendError(connectionContext, opId, { message: error.message });+ _this.unsubscribe(connectionContext, opId);+ });+ break;+ case messageTypes.default.GQL_STOP:+ _this.unsubscribe(connectionContext, opId);+ break;+ default:+ _this.sendError(connectionContext, opId, { message: 'Invalid message type!' });+ }+ };+ };+ SubscriptionServer.prototype.sendKeepAlive = function (connectionContext) {+ if (connectionContext.isLegacy) {+ this.sendMessage(connectionContext, undefined, messageTypes.default.KEEP_ALIVE, undefined);+ }+ else {+ this.sendMessage(connectionContext, undefined, messageTypes.default.GQL_CONNECTION_KEEP_ALIVE, undefined);+ }+ };+ SubscriptionServer.prototype.sendMessage = function (connectionContext, opId, type, payload) {+ var parsedMessage = parseLegacyProtocol.parseLegacyProtocolMessage(connectionContext, {+ type: type,+ id: opId,+ payload: payload,+ });+ if (parsedMessage && connectionContext.socket.readyState === ws.OPEN) {+ connectionContext.socket.send(JSON.stringify(parsedMessage));+ }+ };+ SubscriptionServer.prototype.sendError = function (connectionContext, opId, errorPayload, overrideDefaultErrorType) {+ var sanitizedOverrideDefaultErrorType = overrideDefaultErrorType || messageTypes.default.GQL_ERROR;+ if ([+ messageTypes.default.GQL_CONNECTION_ERROR,+ messageTypes.default.GQL_ERROR,+ ].indexOf(sanitizedOverrideDefaultErrorType) === -1) {+ throw new Error('overrideDefaultErrorType should be one of the allowed error messages' ++ ' GQL_CONNECTION_ERROR or GQL_ERROR');+ }+ this.sendMessage(connectionContext, opId, sanitizedOverrideDefaultErrorType, errorPayload);+ };+ return SubscriptionServer;+}());+exports.SubscriptionServer = SubscriptionServer;++});++var dist = createCommonjsModule(function (module, exports) {+var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });+}) : (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ o[k2] = m[k];+}));+var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {+ for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);+};+Object.defineProperty(exports, "__esModule", { value: true });+__exportStar(client, exports);+__exportStar(server, exports);++Object.defineProperty(exports, "MessageTypes", { enumerable: true, get: function () { return messageTypes.default; } });+__exportStar(protocol, exports);++});++/* eslint-disable no-case-declarations */+/**+ * This loader loads a schema from a URL. The loaded schema is a fully-executable,+ * remote schema since it's created using [@graphql-tools/wrap](/docs/remote-schemas).+ *+ * ```+ * const schema = await loadSchema('http://localhost:3000/graphql', {+ * loaders: [+ * new UrlLoader(),+ * ]+ * });+ * ```+ */+class UrlLoader {+ loaderId() {+ return 'url';+ }+ async canLoad(pointer, options) {+ return this.canLoadSync(pointer, options);+ }+ canLoadSync(pointer, _options) {+ return !!validUrl.isWebUri(pointer);+ }+ buildAsyncExecutor({ pointer, fetch, extraHeaders, defaultMethod, useGETForQueries, }) {+ const HTTP_URL = switchProtocols(pointer, {+ wss: 'https',+ ws: 'http',+ });+ return async ({ document, variables }) => {+ let method = defaultMethod;+ if (useGETForQueries) {+ method = 'GET';+ for (const definition of document.definitions) {+ if (definition.kind === Kind.OPERATION_DEFINITION) {+ if (definition.operation !== 'query') {+ method = defaultMethod;+ }+ }+ }+ }+ let fetchResult;+ const query = print(document);+ switch (method) {+ case 'GET':+ const urlObj = new URL(HTTP_URL);+ urlObj.searchParams.set('query', query);+ if (variables && Object.keys(variables).length > 0) {+ urlObj.searchParams.set('variables', JSON.stringify(variables));+ }+ const finalUrl = urlObj.toString();+ fetchResult = await fetch(finalUrl, {+ method: 'GET',+ headers: extraHeaders,+ });+ break;+ case 'POST':+ fetchResult = await fetch(HTTP_URL, {+ method: 'POST',+ body: JSON.stringify({+ query,+ variables,+ }),+ headers: extraHeaders,+ });+ break;+ }+ return fetchResult.json();+ };+ }+ buildSubscriber(pointer, webSocketImpl) {+ const WS_URL = switchProtocols(pointer, {+ https: 'wss',+ http: 'ws',+ });+ const subscriptionClient = new dist.SubscriptionClient(WS_URL, {}, webSocketImpl);+ return async ({ document, variables }) => {+ return observableToAsyncIterable(subscriptionClient.request({+ query: document,+ variables,+ }));+ };+ }+ async getExecutorAndSubscriber(pointer, options) {+ let headers = {};+ let fetch$1 = nodePonyfill.fetch;+ let defaultMethod = 'POST';+ let webSocketImpl = websocket$1.w3cwebsocket;+ if (options) {+ if (Array.isArray(options.headers)) {+ headers = options.headers.reduce((prev, v) => ({ ...prev, ...v }), {});+ }+ else if (typeof options.headers === 'object') {+ headers = options.headers;+ }+ if (options.customFetch) {+ if (typeof options.customFetch === 'string') {+ const [moduleName, fetchFnName] = options.customFetch.split('#');+ fetch$1 = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(moduleName)); }).then(module => (fetchFnName ? module[fetchFnName] : module));+ }+ else {+ fetch$1 = options.customFetch;+ }+ }+ if (options.webSocketImpl) {+ if (typeof options.webSocketImpl === 'string') {+ const [moduleName, webSocketImplName] = options.webSocketImpl.split('#');+ webSocketImpl = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(moduleName)); }).then(module => webSocketImplName ? module[webSocketImplName] : module);+ }+ else {+ webSocketImpl = options.webSocketImpl;+ }+ }+ if (options.method) {+ defaultMethod = options.method;+ }+ }+ const extraHeaders = {+ Accept: 'application/json',+ 'Content-Type': 'application/json',+ ...headers,+ };+ const executor = this.buildAsyncExecutor({+ pointer,+ fetch: fetch$1,+ extraHeaders,+ defaultMethod,+ useGETForQueries: options.useGETForQueries,+ });+ let subscriber;+ if (options.enableSubscriptions) {+ subscriber = this.buildSubscriber(pointer, webSocketImpl);+ }+ return {+ executor,+ subscriber,+ };+ }+ async getSubschemaConfig(pointer, options) {+ const { executor, subscriber } = await this.getExecutorAndSubscriber(pointer, options);+ return {+ schema: await introspectSchema(executor, undefined, options),+ executor,+ subscriber,+ };+ }+ async load(pointer, options) {+ const subschemaConfig = await this.getSubschemaConfig(pointer, options);+ const remoteExecutableSchema = wrapSchema(subschemaConfig);+ return {+ location: pointer,+ schema: remoteExecutableSchema,+ };+ }+ loadSync() {+ throw new Error('Loader Url has no sync mode');+ }+}+function switchProtocols(pointer, protocolMap) {+ const protocols = Object.keys(protocolMap).map(source => [source, protocolMap[source]]);+ return protocols.reduce((prev, [source, target]) => prev.replace(`${source}://`, `${target}://`).replace(`${source}:\\`, `${target}:\\`), pointer);+}++function isNothing(subject) {+ return (typeof subject === 'undefined') || (subject === null);+}+++function isObject$3(subject) {+ return (typeof subject === 'object') && (subject !== null);+}+++function toArray(sequence) {+ if (Array.isArray(sequence)) return sequence;+ else if (isNothing(sequence)) return [];++ return [ sequence ];+}+++function extend(target, source) {+ var index, length, key, sourceKeys;++ if (source) {+ sourceKeys = Object.keys(source);++ for (index = 0, length = sourceKeys.length; index < length; index += 1) {+ key = sourceKeys[index];+ target[key] = source[key];+ }+ }++ return target;+}+++function repeat(string, count) {+ var result = '', cycle;++ for (cycle = 0; cycle < count; cycle += 1) {+ result += string;+ }++ return result;+}+++function isNegativeZero(number) {+ return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);+}+++var isNothing_1 = isNothing;+var isObject_1$1 = isObject$3;+var toArray_1 = toArray;+var repeat_1 = repeat;+var isNegativeZero_1 = isNegativeZero;+var extend_1 = extend;++var common$1 = {+ isNothing: isNothing_1,+ isObject: isObject_1$1,+ toArray: toArray_1,+ repeat: repeat_1,+ isNegativeZero: isNegativeZero_1,+ extend: extend_1+};++// YAML error class. http://stackoverflow.com/questions/8458984++function YAMLException(reason, mark) {+ // Super constructor+ Error.call(this);++ this.name = 'YAMLException';+ this.reason = reason;+ this.mark = mark;+ this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');++ // Include stack trace in error object+ if (Error.captureStackTrace) {+ // Chrome and NodeJS+ Error.captureStackTrace(this, this.constructor);+ } else {+ // FF, IE 10+ and Safari 6+. Fallback for others+ this.stack = (new Error()).stack || '';+ }+}+++// Inherit from Error+YAMLException.prototype = Object.create(Error.prototype);+YAMLException.prototype.constructor = YAMLException;+++YAMLException.prototype.toString = function toString(compact) {+ var result = this.name + ': ';++ result += this.reason || '(unknown reason)';++ if (!compact && this.mark) {+ result += ' ' + this.mark.toString();+ }++ return result;+};+++var exception = YAMLException;++function Mark(name, buffer, position, line, column) {+ this.name = name;+ this.buffer = buffer;+ this.position = position;+ this.line = line;+ this.column = column;+}+++Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {+ var head, start, tail, end, snippet;++ if (!this.buffer) return null;++ indent = indent || 4;+ maxLength = maxLength || 75;++ head = '';+ start = this.position;++ while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {+ start -= 1;+ if (this.position - start > (maxLength / 2 - 1)) {+ head = ' ... ';+ start += 5;+ break;+ }+ }++ tail = '';+ end = this.position;++ while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) {+ end += 1;+ if (end - this.position > (maxLength / 2 - 1)) {+ tail = ' ... ';+ end -= 5;+ break;+ }+ }++ snippet = this.buffer.slice(start, end);++ return common$1.repeat(' ', indent) + head + snippet + tail + '\n' ++ common$1.repeat(' ', indent + this.position - start + head.length) + '^';+};+++Mark.prototype.toString = function toString(compact) {+ var snippet, where = '';++ if (this.name) {+ where += 'in "' + this.name + '" ';+ }++ where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);++ if (!compact) {+ snippet = this.getSnippet();++ if (snippet) {+ where += ':\n' + snippet;+ }+ }++ return where;+};+++var mark = Mark;++var TYPE_CONSTRUCTOR_OPTIONS = [+ 'kind',+ 'resolve',+ 'construct',+ 'instanceOf',+ 'predicate',+ 'represent',+ 'defaultStyle',+ 'styleAliases'+];++var YAML_NODE_KINDS = [+ 'scalar',+ 'sequence',+ 'mapping'+];++function compileStyleAliases(map) {+ var result = {};++ if (map !== null) {+ Object.keys(map).forEach(function (style) {+ map[style].forEach(function (alias) {+ result[String(alias)] = style;+ });+ });+ }++ return result;+}++function Type(tag, options) {+ options = options || {};++ Object.keys(options).forEach(function (name) {+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {+ throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');+ }+ });++ // TODO: Add tag format check.+ this.tag = tag;+ this.kind = options['kind'] || null;+ this.resolve = options['resolve'] || function () { return true; };+ this.construct = options['construct'] || function (data) { return data; };+ this.instanceOf = options['instanceOf'] || null;+ this.predicate = options['predicate'] || null;+ this.represent = options['represent'] || null;+ this.defaultStyle = options['defaultStyle'] || null;+ this.styleAliases = compileStyleAliases(options['styleAliases'] || null);++ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {+ throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');+ }+}++var type = Type;++/*eslint-disable max-len*/+++++++function compileList(schema, name, result) {+ var exclude = [];++ schema.include.forEach(function (includedSchema) {+ result = compileList(includedSchema, name, result);+ });++ schema[name].forEach(function (currentType) {+ result.forEach(function (previousType, previousIndex) {+ if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {+ exclude.push(previousIndex);+ }+ });++ result.push(currentType);+ });++ return result.filter(function (type, index) {+ return exclude.indexOf(index) === -1;+ });+}+++function compileMap(/* lists... */) {+ var result = {+ scalar: {},+ sequence: {},+ mapping: {},+ fallback: {}+ }, index, length;++ function collectType(type) {+ result[type.kind][type.tag] = result['fallback'][type.tag] = type;+ }++ for (index = 0, length = arguments.length; index < length; index += 1) {+ arguments[index].forEach(collectType);+ }+ return result;+}+++function Schema(definition) {+ this.include = definition.include || [];+ this.implicit = definition.implicit || [];+ this.explicit = definition.explicit || [];++ this.implicit.forEach(function (type) {+ if (type.loadKind && type.loadKind !== 'scalar') {+ throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');+ }+ });++ this.compiledImplicit = compileList(this, 'implicit', []);+ this.compiledExplicit = compileList(this, 'explicit', []);+ this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);+}+++Schema.DEFAULT = null;+++Schema.create = function createSchema() {+ var schemas, types;++ switch (arguments.length) {+ case 1:+ schemas = Schema.DEFAULT;+ types = arguments[0];+ break;++ case 2:+ schemas = arguments[0];+ types = arguments[1];+ break;++ default:+ throw new exception('Wrong number of arguments for Schema.create function');+ }++ schemas = common$1.toArray(schemas);+ types = common$1.toArray(types);++ if (!schemas.every(function (schema) { return schema instanceof Schema; })) {+ throw new exception('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');+ }++ if (!types.every(function (type$1) { return type$1 instanceof type; })) {+ throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.');+ }++ return new Schema({+ include: schemas,+ explicit: types+ });+};+++var schema = Schema;++var str = new type('tag:yaml.org,2002:str', {+ kind: 'scalar',+ construct: function (data) { return data !== null ? data : ''; }+});++var seq = new type('tag:yaml.org,2002:seq', {+ kind: 'sequence',+ construct: function (data) { return data !== null ? data : []; }+});++var map = new type('tag:yaml.org,2002:map', {+ kind: 'mapping',+ construct: function (data) { return data !== null ? data : {}; }+});++var failsafe = new schema({+ explicit: [+ str,+ seq,+ map+ ]+});++function resolveYamlNull(data) {+ if (data === null) return true;++ var max = data.length;++ return (max === 1 && data === '~') ||+ (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));+}++function constructYamlNull() {+ return null;+}++function isNull(object) {+ return object === null;+}++var _null = new type('tag:yaml.org,2002:null', {+ kind: 'scalar',+ resolve: resolveYamlNull,+ construct: constructYamlNull,+ predicate: isNull,+ represent: {+ canonical: function () { return '~'; },+ lowercase: function () { return 'null'; },+ uppercase: function () { return 'NULL'; },+ camelcase: function () { return 'Null'; }+ },+ defaultStyle: 'lowercase'+});++function resolveYamlBoolean(data) {+ if (data === null) return false;++ var max = data.length;++ return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||+ (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));+}++function constructYamlBoolean(data) {+ return data === 'true' ||+ data === 'True' ||+ data === 'TRUE';+}++function isBoolean(object) {+ return Object.prototype.toString.call(object) === '[object Boolean]';+}++var bool = new type('tag:yaml.org,2002:bool', {+ kind: 'scalar',+ resolve: resolveYamlBoolean,+ construct: constructYamlBoolean,+ predicate: isBoolean,+ represent: {+ lowercase: function (object) { return object ? 'true' : 'false'; },+ uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },+ camelcase: function (object) { return object ? 'True' : 'False'; }+ },+ defaultStyle: 'lowercase'+});++function isHexCode(c) {+ return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||+ ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||+ ((0x61/* a */ <= c) && (c <= 0x66/* f */));+}++function isOctCode(c) {+ return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));+}++function isDecCode(c) {+ return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));+}++function resolveYamlInteger(data) {+ if (data === null) return false;++ var max = data.length,+ index = 0,+ hasDigits = false,+ ch;++ if (!max) return false;++ ch = data[index];++ // sign+ if (ch === '-' || ch === '+') {+ ch = data[++index];+ }++ if (ch === '0') {+ // 0+ if (index + 1 === max) return true;+ ch = data[++index];++ // base 2, base 8, base 16++ if (ch === 'b') {+ // base 2+ index++;++ for (; index < max; index++) {+ ch = data[index];+ if (ch === '_') continue;+ if (ch !== '0' && ch !== '1') return false;+ hasDigits = true;+ }+ return hasDigits && ch !== '_';+ }+++ if (ch === 'x') {+ // base 16+ index++;++ for (; index < max; index++) {+ ch = data[index];+ if (ch === '_') continue;+ if (!isHexCode(data.charCodeAt(index))) return false;+ hasDigits = true;+ }+ return hasDigits && ch !== '_';+ }++ // base 8+ for (; index < max; index++) {+ ch = data[index];+ if (ch === '_') continue;+ if (!isOctCode(data.charCodeAt(index))) return false;+ hasDigits = true;+ }+ return hasDigits && ch !== '_';+ }++ // base 10 (except 0) or base 60++ // value should not start with `_`;+ if (ch === '_') return false;++ for (; index < max; index++) {+ ch = data[index];+ if (ch === '_') continue;+ if (ch === ':') break;+ if (!isDecCode(data.charCodeAt(index))) {+ return false;+ }+ hasDigits = true;+ }++ // Should have digits and should not end with `_`+ if (!hasDigits || ch === '_') return false;++ // if !base60 - done;+ if (ch !== ':') return true;++ // base60 almost not used, no needs to optimize+ return /^(:[0-5]?[0-9])+$/.test(data.slice(index));+}++function constructYamlInteger(data) {+ var value = data, sign = 1, ch, base, digits = [];++ if (value.indexOf('_') !== -1) {+ value = value.replace(/_/g, '');+ }++ ch = value[0];++ if (ch === '-' || ch === '+') {+ if (ch === '-') sign = -1;+ value = value.slice(1);+ ch = value[0];+ }++ if (value === '0') return 0;++ if (ch === '0') {+ if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);+ if (value[1] === 'x') return sign * parseInt(value, 16);+ return sign * parseInt(value, 8);+ }++ if (value.indexOf(':') !== -1) {+ value.split(':').forEach(function (v) {+ digits.unshift(parseInt(v, 10));+ });++ value = 0;+ base = 1;++ digits.forEach(function (d) {+ value += (d * base);+ base *= 60;+ });++ return sign * value;++ }++ return sign * parseInt(value, 10);+}++function isInteger$1(object) {+ return (Object.prototype.toString.call(object)) === '[object Number]' &&+ (object % 1 === 0 && !common$1.isNegativeZero(object));+}++var int_1 = new type('tag:yaml.org,2002:int', {+ kind: 'scalar',+ resolve: resolveYamlInteger,+ construct: constructYamlInteger,+ predicate: isInteger$1,+ represent: {+ binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },+ octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); },+ decimal: function (obj) { return obj.toString(10); },+ /* eslint-disable max-len */+ hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); }+ },+ defaultStyle: 'decimal',+ styleAliases: {+ binary: [ 2, 'bin' ],+ octal: [ 8, 'oct' ],+ decimal: [ 10, 'dec' ],+ hexadecimal: [ 16, 'hex' ]+ }+});++var YAML_FLOAT_PATTERN = new RegExp(+ // 2.5e4, 2.5 and integers+ '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' ++ // .2e4, .2+ // special case, seems not from spec+ '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' ++ // 20:59+ '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' ++ // .inf+ '|[-+]?\\.(?:inf|Inf|INF)' ++ // .nan+ '|\\.(?:nan|NaN|NAN))$');++function resolveYamlFloat(data) {+ if (data === null) return false;++ if (!YAML_FLOAT_PATTERN.test(data) ||+ // Quick hack to not allow integers end with `_`+ // Probably should update regexp & check speed+ data[data.length - 1] === '_') {+ return false;+ }++ return true;+}++function constructYamlFloat(data) {+ var value, sign, base, digits;++ value = data.replace(/_/g, '').toLowerCase();+ sign = value[0] === '-' ? -1 : 1;+ digits = [];++ if ('+-'.indexOf(value[0]) >= 0) {+ value = value.slice(1);+ }++ if (value === '.inf') {+ return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;++ } else if (value === '.nan') {+ return NaN;++ } else if (value.indexOf(':') >= 0) {+ value.split(':').forEach(function (v) {+ digits.unshift(parseFloat(v, 10));+ });++ value = 0.0;+ base = 1;++ digits.forEach(function (d) {+ value += d * base;+ base *= 60;+ });++ return sign * value;++ }+ return sign * parseFloat(value, 10);+}+++var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;++function representYamlFloat(object, style) {+ var res;++ if (isNaN(object)) {+ switch (style) {+ case 'lowercase': return '.nan';+ case 'uppercase': return '.NAN';+ case 'camelcase': return '.NaN';+ }+ } else if (Number.POSITIVE_INFINITY === object) {+ switch (style) {+ case 'lowercase': return '.inf';+ case 'uppercase': return '.INF';+ case 'camelcase': return '.Inf';+ }+ } else if (Number.NEGATIVE_INFINITY === object) {+ switch (style) {+ case 'lowercase': return '-.inf';+ case 'uppercase': return '-.INF';+ case 'camelcase': return '-.Inf';+ }+ } else if (common$1.isNegativeZero(object)) {+ return '-0.0';+ }++ res = object.toString(10);++ // JS stringifier can build scientific format without dots: 5e-100,+ // while YAML requres dot: 5.e-100. Fix it with simple hack++ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;+}++function isFloat(object) {+ return (Object.prototype.toString.call(object) === '[object Number]') &&+ (object % 1 !== 0 || common$1.isNegativeZero(object));+}++var float_1 = new type('tag:yaml.org,2002:float', {+ kind: 'scalar',+ resolve: resolveYamlFloat,+ construct: constructYamlFloat,+ predicate: isFloat,+ represent: representYamlFloat,+ defaultStyle: 'lowercase'+});++var json$1 = new schema({+ include: [+ failsafe+ ],+ implicit: [+ _null,+ bool,+ int_1,+ float_1+ ]+});++var core = new schema({+ include: [+ json$1+ ]+});++var YAML_DATE_REGEXP = new RegExp(+ '^([0-9][0-9][0-9][0-9])' + // [1] year+ '-([0-9][0-9])' + // [2] month+ '-([0-9][0-9])$'); // [3] day++var YAML_TIMESTAMP_REGEXP = new RegExp(+ '^([0-9][0-9][0-9][0-9])' + // [1] year+ '-([0-9][0-9]?)' + // [2] month+ '-([0-9][0-9]?)' + // [3] day+ '(?:[Tt]|[ \\t]+)' + // ...+ '([0-9][0-9]?)' + // [4] hour+ ':([0-9][0-9])' + // [5] minute+ ':([0-9][0-9])' + // [6] second+ '(?:\\.([0-9]*))?' + // [7] fraction+ '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour+ '(?::([0-9][0-9]))?))?$'); // [11] tz_minute++function resolveYamlTimestamp(data) {+ if (data === null) return false;+ if (YAML_DATE_REGEXP.exec(data) !== null) return true;+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;+ return false;+}++function constructYamlTimestamp(data) {+ var match, year, month, day, hour, minute, second, fraction = 0,+ delta = null, tz_hour, tz_minute, date;++ match = YAML_DATE_REGEXP.exec(data);+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);++ if (match === null) throw new Error('Date resolve error');++ // match: [1] year [2] month [3] day++ year = +(match[1]);+ month = +(match[2]) - 1; // JS month starts with 0+ day = +(match[3]);++ if (!match[4]) { // no hour+ return new Date(Date.UTC(year, month, day));+ }++ // match: [4] hour [5] minute [6] second [7] fraction++ hour = +(match[4]);+ minute = +(match[5]);+ second = +(match[6]);++ if (match[7]) {+ fraction = match[7].slice(0, 3);+ while (fraction.length < 3) { // milli-seconds+ fraction += '0';+ }+ fraction = +fraction;+ }++ // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute++ if (match[9]) {+ tz_hour = +(match[10]);+ tz_minute = +(match[11] || 0);+ delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds+ if (match[9] === '-') delta = -delta;+ }++ date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));++ if (delta) date.setTime(date.getTime() - delta);++ return date;+}++function representYamlTimestamp(object /*, style*/) {+ return object.toISOString();+}++var timestamp = new type('tag:yaml.org,2002:timestamp', {+ kind: 'scalar',+ resolve: resolveYamlTimestamp,+ construct: constructYamlTimestamp,+ instanceOf: Date,+ represent: representYamlTimestamp+});++function resolveYamlMerge(data) {+ return data === '<<' || data === null;+}++var merge = new type('tag:yaml.org,2002:merge', {+ kind: 'scalar',+ resolve: resolveYamlMerge+});++/*eslint-disable no-bitwise*/++var NodeBuffer;++try {+ // A trick for browserified version, to not include `Buffer` shim+ var _require = commonjsRequire;+ NodeBuffer = _require('buffer').Buffer;+} catch (__) {}+++++// [ 64, 65, 66 ] -> [ padding, CR, LF ]+var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';+++function resolveYamlBinary(data) {+ if (data === null) return false;++ var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;++ // Convert one by one.+ for (idx = 0; idx < max; idx++) {+ code = map.indexOf(data.charAt(idx));++ // Skip CR/LF+ if (code > 64) continue;++ // Fail on illegal characters+ if (code < 0) return false;++ bitlen += 6;+ }++ // If there are any bits left, source was corrupted+ return (bitlen % 8) === 0;+}++function constructYamlBinary(data) {+ var idx, tailbits,+ input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan+ max = input.length,+ map = BASE64_MAP,+ bits = 0,+ result = [];++ // Collect by 6*4 bits (3 bytes)++ for (idx = 0; idx < max; idx++) {+ if ((idx % 4 === 0) && idx) {+ result.push((bits >> 16) & 0xFF);+ result.push((bits >> 8) & 0xFF);+ result.push(bits & 0xFF);+ }++ bits = (bits << 6) | map.indexOf(input.charAt(idx));+ }++ // Dump tail++ tailbits = (max % 4) * 6;++ if (tailbits === 0) {+ result.push((bits >> 16) & 0xFF);+ result.push((bits >> 8) & 0xFF);+ result.push(bits & 0xFF);+ } else if (tailbits === 18) {+ result.push((bits >> 10) & 0xFF);+ result.push((bits >> 2) & 0xFF);+ } else if (tailbits === 12) {+ result.push((bits >> 4) & 0xFF);+ }++ // Wrap into Buffer for NodeJS and leave Array for browser+ if (NodeBuffer) {+ // Support node 6.+ Buffer API when available+ return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);+ }++ return result;+}++function representYamlBinary(object /*, style*/) {+ var result = '', bits = 0, idx, tail,+ max = object.length,+ map = BASE64_MAP;++ // Convert every three bytes to 4 ASCII characters.++ for (idx = 0; idx < max; idx++) {+ if ((idx % 3 === 0) && idx) {+ result += map[(bits >> 18) & 0x3F];+ result += map[(bits >> 12) & 0x3F];+ result += map[(bits >> 6) & 0x3F];+ result += map[bits & 0x3F];+ }++ bits = (bits << 8) + object[idx];+ }++ // Dump tail++ tail = max % 3;++ if (tail === 0) {+ result += map[(bits >> 18) & 0x3F];+ result += map[(bits >> 12) & 0x3F];+ result += map[(bits >> 6) & 0x3F];+ result += map[bits & 0x3F];+ } else if (tail === 2) {+ result += map[(bits >> 10) & 0x3F];+ result += map[(bits >> 4) & 0x3F];+ result += map[(bits << 2) & 0x3F];+ result += map[64];+ } else if (tail === 1) {+ result += map[(bits >> 2) & 0x3F];+ result += map[(bits << 4) & 0x3F];+ result += map[64];+ result += map[64];+ }++ return result;+}++function isBinary(object) {+ return NodeBuffer && NodeBuffer.isBuffer(object);+}++var binary = new type('tag:yaml.org,2002:binary', {+ kind: 'scalar',+ resolve: resolveYamlBinary,+ construct: constructYamlBinary,+ predicate: isBinary,+ represent: representYamlBinary+});++var _hasOwnProperty = Object.prototype.hasOwnProperty;+var _toString = Object.prototype.toString;++function resolveYamlOmap(data) {+ if (data === null) return true;++ var objectKeys = [], index, length, pair, pairKey, pairHasKey,+ object = data;++ for (index = 0, length = object.length; index < length; index += 1) {+ pair = object[index];+ pairHasKey = false;++ if (_toString.call(pair) !== '[object Object]') return false;++ for (pairKey in pair) {+ if (_hasOwnProperty.call(pair, pairKey)) {+ if (!pairHasKey) pairHasKey = true;+ else return false;+ }+ }++ if (!pairHasKey) return false;++ if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);+ else return false;+ }++ return true;+}++function constructYamlOmap(data) {+ return data !== null ? data : [];+}++var omap = new type('tag:yaml.org,2002:omap', {+ kind: 'sequence',+ resolve: resolveYamlOmap,+ construct: constructYamlOmap+});++var _toString$1 = Object.prototype.toString;++function resolveYamlPairs(data) {+ if (data === null) return true;++ var index, length, pair, keys, result,+ object = data;++ result = new Array(object.length);++ for (index = 0, length = object.length; index < length; index += 1) {+ pair = object[index];++ if (_toString$1.call(pair) !== '[object Object]') return false;++ keys = Object.keys(pair);++ if (keys.length !== 1) return false;++ result[index] = [ keys[0], pair[keys[0]] ];+ }++ return true;+}++function constructYamlPairs(data) {+ if (data === null) return [];++ var index, length, pair, keys, result,+ object = data;++ result = new Array(object.length);++ for (index = 0, length = object.length; index < length; index += 1) {+ pair = object[index];++ keys = Object.keys(pair);++ result[index] = [ keys[0], pair[keys[0]] ];+ }++ return result;+}++var pairs = new type('tag:yaml.org,2002:pairs', {+ kind: 'sequence',+ resolve: resolveYamlPairs,+ construct: constructYamlPairs+});++var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;++function resolveYamlSet(data) {+ if (data === null) return true;++ var key, object = data;++ for (key in object) {+ if (_hasOwnProperty$1.call(object, key)) {+ if (object[key] !== null) return false;+ }+ }++ return true;+}++function constructYamlSet(data) {+ return data !== null ? data : {};+}++var set = new type('tag:yaml.org,2002:set', {+ kind: 'mapping',+ resolve: resolveYamlSet,+ construct: constructYamlSet+});++var default_safe = new schema({+ include: [+ core+ ],+ implicit: [+ timestamp,+ merge+ ],+ explicit: [+ binary,+ omap,+ pairs,+ set+ ]+});++function resolveJavascriptUndefined() {+ return true;+}++function constructJavascriptUndefined() {+ /*eslint-disable no-undefined*/+ return undefined;+}++function representJavascriptUndefined() {+ return '';+}++function isUndefined(object) {+ return typeof object === 'undefined';+}++var _undefined = new type('tag:yaml.org,2002:js/undefined', {+ kind: 'scalar',+ resolve: resolveJavascriptUndefined,+ construct: constructJavascriptUndefined,+ predicate: isUndefined,+ represent: representJavascriptUndefined+});++function resolveJavascriptRegExp(data) {+ if (data === null) return false;+ if (data.length === 0) return false;++ var regexp = data,+ tail = /\/([gim]*)$/.exec(data),+ modifiers = '';++ // if regexp starts with '/' it can have modifiers and must be properly closed+ // `/foo/gim` - modifiers tail can be maximum 3 chars+ if (regexp[0] === '/') {+ if (tail) modifiers = tail[1];++ if (modifiers.length > 3) return false;+ // if expression starts with /, is should be properly terminated+ if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;+ }++ return true;+}++function constructJavascriptRegExp(data) {+ var regexp = data,+ tail = /\/([gim]*)$/.exec(data),+ modifiers = '';++ // `/foo/gim` - tail can be maximum 4 chars+ if (regexp[0] === '/') {+ if (tail) modifiers = tail[1];+ regexp = regexp.slice(1, regexp.length - modifiers.length - 1);+ }++ return new RegExp(regexp, modifiers);+}++function representJavascriptRegExp(object /*, style*/) {+ var result = '/' + object.source + '/';++ if (object.global) result += 'g';+ if (object.multiline) result += 'm';+ if (object.ignoreCase) result += 'i';++ return result;+}++function isRegExp(object) {+ return Object.prototype.toString.call(object) === '[object RegExp]';+}++var regexp = new type('tag:yaml.org,2002:js/regexp', {+ kind: 'scalar',+ resolve: resolveJavascriptRegExp,+ construct: constructJavascriptRegExp,+ predicate: isRegExp,+ represent: representJavascriptRegExp+});++var esprima;++// Browserified version does not have esprima+//+// 1. For node.js just require module as deps+// 2. For browser try to require mudule via external AMD system.+// If not found - try to fallback to window.esprima. If not+// found too - then fail to parse.+//+try {+ // workaround to exclude package from browserify list.+ var _require$1 = commonjsRequire;+ esprima = _require$1('esprima');+} catch (_) {+ /* eslint-disable no-redeclare */+ /* global window */+ if (typeof window !== 'undefined') esprima = window.esprima;+}++++function resolveJavascriptFunction(data) {+ if (data === null) return false;++ try {+ var source = '(' + data + ')',+ ast = esprima.parse(source, { range: true });++ if (ast.type !== 'Program' ||+ ast.body.length !== 1 ||+ ast.body[0].type !== 'ExpressionStatement' ||+ (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&+ ast.body[0].expression.type !== 'FunctionExpression')) {+ return false;+ }++ return true;+ } catch (err) {+ return false;+ }+}++function constructJavascriptFunction(data) {+ /*jslint evil:true*/++ var source = '(' + data + ')',+ ast = esprima.parse(source, { range: true }),+ params = [],+ body;++ if (ast.type !== 'Program' ||+ ast.body.length !== 1 ||+ ast.body[0].type !== 'ExpressionStatement' ||+ (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&+ ast.body[0].expression.type !== 'FunctionExpression')) {+ throw new Error('Failed to resolve function');+ }++ ast.body[0].expression.params.forEach(function (param) {+ params.push(param.name);+ });++ body = ast.body[0].expression.body.range;++ // Esprima's ranges include the first '{' and the last '}' characters on+ // function expressions. So cut them out.+ if (ast.body[0].expression.body.type === 'BlockStatement') {+ /*eslint-disable no-new-func*/+ return new Function(params, source.slice(body[0] + 1, body[1] - 1));+ }+ // ES6 arrow functions can omit the BlockStatement. In that case, just return+ // the body.+ /*eslint-disable no-new-func*/+ return new Function(params, 'return ' + source.slice(body[0], body[1]));+}++function representJavascriptFunction(object /*, style*/) {+ return object.toString();+}++function isFunction(object) {+ return Object.prototype.toString.call(object) === '[object Function]';+}++var _function = new type('tag:yaml.org,2002:js/function', {+ kind: 'scalar',+ resolve: resolveJavascriptFunction,+ construct: constructJavascriptFunction,+ predicate: isFunction,+ represent: representJavascriptFunction+});++var default_full = schema.DEFAULT = new schema({+ include: [+ default_safe+ ],+ explicit: [+ _undefined,+ regexp,+ _function+ ]+});++/*eslint-disable max-len,no-use-before-define*/+++++++++var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;+++var CONTEXT_FLOW_IN = 1;+var CONTEXT_FLOW_OUT = 2;+var CONTEXT_BLOCK_IN = 3;+var CONTEXT_BLOCK_OUT = 4;+++var CHOMPING_CLIP = 1;+var CHOMPING_STRIP = 2;+var CHOMPING_KEEP = 3;+++var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;+var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;+var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;+var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;+var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;+++function _class(obj) { return Object.prototype.toString.call(obj); }++function is_EOL(c) {+ return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);+}++function is_WHITE_SPACE(c) {+ return (c === 0x09/* Tab */) || (c === 0x20/* Space */);+}++function is_WS_OR_EOL(c) {+ return (c === 0x09/* Tab */) ||+ (c === 0x20/* Space */) ||+ (c === 0x0A/* LF */) ||+ (c === 0x0D/* CR */);+}++function is_FLOW_INDICATOR(c) {+ return c === 0x2C/* , */ ||+ c === 0x5B/* [ */ ||+ c === 0x5D/* ] */ ||+ c === 0x7B/* { */ ||+ c === 0x7D/* } */;+}++function fromHexCode(c) {+ var lc;++ if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {+ return c - 0x30;+ }++ /*eslint-disable no-bitwise*/+ lc = c | 0x20;++ if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {+ return lc - 0x61 + 10;+ }++ return -1;+}++function escapedHexLen(c) {+ if (c === 0x78/* x */) { return 2; }+ if (c === 0x75/* u */) { return 4; }+ if (c === 0x55/* U */) { return 8; }+ return 0;+}++function fromDecimalCode(c) {+ if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {+ return c - 0x30;+ }++ return -1;+}++function simpleEscapeSequence(c) {+ /* eslint-disable indent */+ return (c === 0x30/* 0 */) ? '\x00' :+ (c === 0x61/* a */) ? '\x07' :+ (c === 0x62/* b */) ? '\x08' :+ (c === 0x74/* t */) ? '\x09' :+ (c === 0x09/* Tab */) ? '\x09' :+ (c === 0x6E/* n */) ? '\x0A' :+ (c === 0x76/* v */) ? '\x0B' :+ (c === 0x66/* f */) ? '\x0C' :+ (c === 0x72/* r */) ? '\x0D' :+ (c === 0x65/* e */) ? '\x1B' :+ (c === 0x20/* Space */) ? ' ' :+ (c === 0x22/* " */) ? '\x22' :+ (c === 0x2F/* / */) ? '/' :+ (c === 0x5C/* \ */) ? '\x5C' :+ (c === 0x4E/* N */) ? '\x85' :+ (c === 0x5F/* _ */) ? '\xA0' :+ (c === 0x4C/* L */) ? '\u2028' :+ (c === 0x50/* P */) ? '\u2029' : '';+}++function charFromCodepoint(c) {+ if (c <= 0xFFFF) {+ return String.fromCharCode(c);+ }+ // Encode UTF-16 surrogate pair+ // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF+ return String.fromCharCode(+ ((c - 0x010000) >> 10) + 0xD800,+ ((c - 0x010000) & 0x03FF) + 0xDC00+ );+}++var simpleEscapeCheck = new Array(256); // integer, for fast access+var simpleEscapeMap = new Array(256);+for (var i = 0; i < 256; i++) {+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;+ simpleEscapeMap[i] = simpleEscapeSequence(i);+}+++function State(input, options) {+ this.input = input;++ this.filename = options['filename'] || null;+ this.schema = options['schema'] || default_full;+ this.onWarning = options['onWarning'] || null;+ this.legacy = options['legacy'] || false;+ this.json = options['json'] || false;+ this.listener = options['listener'] || null;++ this.implicitTypes = this.schema.compiledImplicit;+ this.typeMap = this.schema.compiledTypeMap;++ this.length = input.length;+ this.position = 0;+ this.line = 0;+ this.lineStart = 0;+ this.lineIndent = 0;++ this.documents = [];++ /*+ this.version;+ this.checkLineBreaks;+ this.tagMap;+ this.anchorMap;+ this.tag;+ this.anchor;+ this.kind;+ this.result;*/++}+++function generateError(state, message) {+ return new exception(+ message,+ new mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));+}++function throwError$1(state, message) {+ throw generateError(state, message);+}++function throwWarning(state, message) {+ if (state.onWarning) {+ state.onWarning.call(null, generateError(state, message));+ }+}+++var directiveHandlers = {++ YAML: function handleYamlDirective(state, name, args) {++ var match, major, minor;++ if (state.version !== null) {+ throwError$1(state, 'duplication of %YAML directive');+ }++ if (args.length !== 1) {+ throwError$1(state, 'YAML directive accepts exactly one argument');+ }++ match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);++ if (match === null) {+ throwError$1(state, 'ill-formed argument of the YAML directive');+ }++ major = parseInt(match[1], 10);+ minor = parseInt(match[2], 10);++ if (major !== 1) {+ throwError$1(state, 'unacceptable YAML version of the document');+ }++ state.version = args[0];+ state.checkLineBreaks = (minor < 2);++ if (minor !== 1 && minor !== 2) {+ throwWarning(state, 'unsupported YAML version of the document');+ }+ },++ TAG: function handleTagDirective(state, name, args) {++ var handle, prefix;++ if (args.length !== 2) {+ throwError$1(state, 'TAG directive accepts exactly two arguments');+ }++ handle = args[0];+ prefix = args[1];++ if (!PATTERN_TAG_HANDLE.test(handle)) {+ throwError$1(state, 'ill-formed tag handle (first argument) of the TAG directive');+ }++ if (_hasOwnProperty$2.call(state.tagMap, handle)) {+ throwError$1(state, 'there is a previously declared suffix for "' + handle + '" tag handle');+ }++ if (!PATTERN_TAG_URI.test(prefix)) {+ throwError$1(state, 'ill-formed tag prefix (second argument) of the TAG directive');+ }++ state.tagMap[handle] = prefix;+ }+};+++function captureSegment(state, start, end, checkJson) {+ var _position, _length, _character, _result;++ if (start < end) {+ _result = state.input.slice(start, end);++ if (checkJson) {+ for (_position = 0, _length = _result.length; _position < _length; _position += 1) {+ _character = _result.charCodeAt(_position);+ if (!(_character === 0x09 ||+ (0x20 <= _character && _character <= 0x10FFFF))) {+ throwError$1(state, 'expected valid JSON character');+ }+ }+ } else if (PATTERN_NON_PRINTABLE.test(_result)) {+ throwError$1(state, 'the stream contains non-printable characters');+ }++ state.result += _result;+ }+}++function mergeMappings(state, destination, source, overridableKeys) {+ var sourceKeys, key, index, quantity;++ if (!common$1.isObject(source)) {+ throwError$1(state, 'cannot merge mappings; the provided source object is unacceptable');+ }++ sourceKeys = Object.keys(source);++ for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {+ key = sourceKeys[index];++ if (!_hasOwnProperty$2.call(destination, key)) {+ destination[key] = source[key];+ overridableKeys[key] = true;+ }+ }+}++function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {+ var index, quantity;++ // The output is a plain object here, so keys can only be strings.+ // We need to convert keyNode to a string, but doing so can hang the process+ // (deeply nested arrays that explode exponentially using aliases).+ if (Array.isArray(keyNode)) {+ keyNode = Array.prototype.slice.call(keyNode);++ for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {+ if (Array.isArray(keyNode[index])) {+ throwError$1(state, 'nested arrays are not supported inside keys');+ }++ if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {+ keyNode[index] = '[object Object]';+ }+ }+ }++ // Avoid code execution in load() via toString property+ // (still use its own toString for arrays, timestamps,+ // and whatever user schema extensions happen to have @@toStringTag)+ if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {+ keyNode = '[object Object]';+ }+++ keyNode = String(keyNode);++ if (_result === null) {+ _result = {};+ }++ if (keyTag === 'tag:yaml.org,2002:merge') {+ if (Array.isArray(valueNode)) {+ for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {+ mergeMappings(state, _result, valueNode[index], overridableKeys);+ }+ } else {+ mergeMappings(state, _result, valueNode, overridableKeys);+ }+ } else {+ if (!state.json &&+ !_hasOwnProperty$2.call(overridableKeys, keyNode) &&+ _hasOwnProperty$2.call(_result, keyNode)) {+ state.line = startLine || state.line;+ state.position = startPos || state.position;+ throwError$1(state, 'duplicated mapping key');+ }+ _result[keyNode] = valueNode;+ delete overridableKeys[keyNode];+ }++ return _result;+}++function readLineBreak(state) {+ var ch;++ ch = state.input.charCodeAt(state.position);++ if (ch === 0x0A/* LF */) {+ state.position++;+ } else if (ch === 0x0D/* CR */) {+ state.position++;+ if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {+ state.position++;+ }+ } else {+ throwError$1(state, 'a line break is expected');+ }++ state.line += 1;+ state.lineStart = state.position;+}++function skipSeparationSpace(state, allowComments, checkIndent) {+ var lineBreaks = 0,+ ch = state.input.charCodeAt(state.position);++ while (ch !== 0) {+ while (is_WHITE_SPACE(ch)) {+ ch = state.input.charCodeAt(++state.position);+ }++ if (allowComments && ch === 0x23/* # */) {+ do {+ ch = state.input.charCodeAt(++state.position);+ } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);+ }++ if (is_EOL(ch)) {+ readLineBreak(state);++ ch = state.input.charCodeAt(state.position);+ lineBreaks++;+ state.lineIndent = 0;++ while (ch === 0x20/* Space */) {+ state.lineIndent++;+ ch = state.input.charCodeAt(++state.position);+ }+ } else {+ break;+ }+ }++ if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {+ throwWarning(state, 'deficient indentation');+ }++ return lineBreaks;+}++function testDocumentSeparator(state) {+ var _position = state.position,+ ch;++ ch = state.input.charCodeAt(_position);++ // Condition state.position === state.lineStart is tested+ // in parent on each call, for efficiency. No needs to test here again.+ if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&+ ch === state.input.charCodeAt(_position + 1) &&+ ch === state.input.charCodeAt(_position + 2)) {++ _position += 3;++ ch = state.input.charCodeAt(_position);++ if (ch === 0 || is_WS_OR_EOL(ch)) {+ return true;+ }+ }++ return false;+}++function writeFoldedLines(state, count) {+ if (count === 1) {+ state.result += ' ';+ } else if (count > 1) {+ state.result += common$1.repeat('\n', count - 1);+ }+}+++function readPlainScalar(state, nodeIndent, withinFlowCollection) {+ var preceding,+ following,+ captureStart,+ captureEnd,+ hasPendingContent,+ _line,+ _lineStart,+ _lineIndent,+ _kind = state.kind,+ _result = state.result,+ ch;++ ch = state.input.charCodeAt(state.position);++ if (is_WS_OR_EOL(ch) ||+ is_FLOW_INDICATOR(ch) ||+ ch === 0x23/* # */ ||+ ch === 0x26/* & */ ||+ ch === 0x2A/* * */ ||+ ch === 0x21/* ! */ ||+ ch === 0x7C/* | */ ||+ ch === 0x3E/* > */ ||+ ch === 0x27/* ' */ ||+ ch === 0x22/* " */ ||+ ch === 0x25/* % */ ||+ ch === 0x40/* @ */ ||+ ch === 0x60/* ` */) {+ return false;+ }++ if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {+ following = state.input.charCodeAt(state.position + 1);++ if (is_WS_OR_EOL(following) ||+ withinFlowCollection && is_FLOW_INDICATOR(following)) {+ return false;+ }+ }++ state.kind = 'scalar';+ state.result = '';+ captureStart = captureEnd = state.position;+ hasPendingContent = false;++ while (ch !== 0) {+ if (ch === 0x3A/* : */) {+ following = state.input.charCodeAt(state.position + 1);++ if (is_WS_OR_EOL(following) ||+ withinFlowCollection && is_FLOW_INDICATOR(following)) {+ break;+ }++ } else if (ch === 0x23/* # */) {+ preceding = state.input.charCodeAt(state.position - 1);++ if (is_WS_OR_EOL(preceding)) {+ break;+ }++ } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||+ withinFlowCollection && is_FLOW_INDICATOR(ch)) {+ break;++ } else if (is_EOL(ch)) {+ _line = state.line;+ _lineStart = state.lineStart;+ _lineIndent = state.lineIndent;+ skipSeparationSpace(state, false, -1);++ if (state.lineIndent >= nodeIndent) {+ hasPendingContent = true;+ ch = state.input.charCodeAt(state.position);+ continue;+ } else {+ state.position = captureEnd;+ state.line = _line;+ state.lineStart = _lineStart;+ state.lineIndent = _lineIndent;+ break;+ }+ }++ if (hasPendingContent) {+ captureSegment(state, captureStart, captureEnd, false);+ writeFoldedLines(state, state.line - _line);+ captureStart = captureEnd = state.position;+ hasPendingContent = false;+ }++ if (!is_WHITE_SPACE(ch)) {+ captureEnd = state.position + 1;+ }++ ch = state.input.charCodeAt(++state.position);+ }++ captureSegment(state, captureStart, captureEnd, false);++ if (state.result) {+ return true;+ }++ state.kind = _kind;+ state.result = _result;+ return false;+}++function readSingleQuotedScalar(state, nodeIndent) {+ var ch,+ captureStart, captureEnd;++ ch = state.input.charCodeAt(state.position);++ if (ch !== 0x27/* ' */) {+ return false;+ }++ state.kind = 'scalar';+ state.result = '';+ state.position++;+ captureStart = captureEnd = state.position;++ while ((ch = state.input.charCodeAt(state.position)) !== 0) {+ if (ch === 0x27/* ' */) {+ captureSegment(state, captureStart, state.position, true);+ ch = state.input.charCodeAt(++state.position);++ if (ch === 0x27/* ' */) {+ captureStart = state.position;+ state.position++;+ captureEnd = state.position;+ } else {+ return true;+ }++ } else if (is_EOL(ch)) {+ captureSegment(state, captureStart, captureEnd, true);+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));+ captureStart = captureEnd = state.position;++ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {+ throwError$1(state, 'unexpected end of the document within a single quoted scalar');++ } else {+ state.position++;+ captureEnd = state.position;+ }+ }++ throwError$1(state, 'unexpected end of the stream within a single quoted scalar');+}++function readDoubleQuotedScalar(state, nodeIndent) {+ var captureStart,+ captureEnd,+ hexLength,+ hexResult,+ tmp,+ ch;++ ch = state.input.charCodeAt(state.position);++ if (ch !== 0x22/* " */) {+ return false;+ }++ state.kind = 'scalar';+ state.result = '';+ state.position++;+ captureStart = captureEnd = state.position;++ while ((ch = state.input.charCodeAt(state.position)) !== 0) {+ if (ch === 0x22/* " */) {+ captureSegment(state, captureStart, state.position, true);+ state.position++;+ return true;++ } else if (ch === 0x5C/* \ */) {+ captureSegment(state, captureStart, state.position, true);+ ch = state.input.charCodeAt(++state.position);++ if (is_EOL(ch)) {+ skipSeparationSpace(state, false, nodeIndent);++ // TODO: rework to inline fn with no type cast?+ } else if (ch < 256 && simpleEscapeCheck[ch]) {+ state.result += simpleEscapeMap[ch];+ state.position++;++ } else if ((tmp = escapedHexLen(ch)) > 0) {+ hexLength = tmp;+ hexResult = 0;++ for (; hexLength > 0; hexLength--) {+ ch = state.input.charCodeAt(++state.position);++ if ((tmp = fromHexCode(ch)) >= 0) {+ hexResult = (hexResult << 4) + tmp;++ } else {+ throwError$1(state, 'expected hexadecimal character');+ }+ }++ state.result += charFromCodepoint(hexResult);++ state.position++;++ } else {+ throwError$1(state, 'unknown escape sequence');+ }++ captureStart = captureEnd = state.position;++ } else if (is_EOL(ch)) {+ captureSegment(state, captureStart, captureEnd, true);+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));+ captureStart = captureEnd = state.position;++ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {+ throwError$1(state, 'unexpected end of the document within a double quoted scalar');++ } else {+ state.position++;+ captureEnd = state.position;+ }+ }++ throwError$1(state, 'unexpected end of the stream within a double quoted scalar');+}++function readFlowCollection(state, nodeIndent) {+ var readNext = true,+ _line,+ _tag = state.tag,+ _result,+ _anchor = state.anchor,+ following,+ terminator,+ isPair,+ isExplicitPair,+ isMapping,+ overridableKeys = {},+ keyNode,+ keyTag,+ valueNode,+ ch;++ ch = state.input.charCodeAt(state.position);++ if (ch === 0x5B/* [ */) {+ terminator = 0x5D;/* ] */+ isMapping = false;+ _result = [];+ } else if (ch === 0x7B/* { */) {+ terminator = 0x7D;/* } */+ isMapping = true;+ _result = {};+ } else {+ return false;+ }++ if (state.anchor !== null) {+ state.anchorMap[state.anchor] = _result;+ }++ ch = state.input.charCodeAt(++state.position);++ while (ch !== 0) {+ skipSeparationSpace(state, true, nodeIndent);++ ch = state.input.charCodeAt(state.position);++ if (ch === terminator) {+ state.position++;+ state.tag = _tag;+ state.anchor = _anchor;+ state.kind = isMapping ? 'mapping' : 'sequence';+ state.result = _result;+ return true;+ } else if (!readNext) {+ throwError$1(state, 'missed comma between flow collection entries');+ }++ keyTag = keyNode = valueNode = null;+ isPair = isExplicitPair = false;++ if (ch === 0x3F/* ? */) {+ following = state.input.charCodeAt(state.position + 1);++ if (is_WS_OR_EOL(following)) {+ isPair = isExplicitPair = true;+ state.position++;+ skipSeparationSpace(state, true, nodeIndent);+ }+ }++ _line = state.line;+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);+ keyTag = state.tag;+ keyNode = state.result;+ skipSeparationSpace(state, true, nodeIndent);++ ch = state.input.charCodeAt(state.position);++ if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {+ isPair = true;+ ch = state.input.charCodeAt(++state.position);+ skipSeparationSpace(state, true, nodeIndent);+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);+ valueNode = state.result;+ }++ if (isMapping) {+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);+ } else if (isPair) {+ _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));+ } else {+ _result.push(keyNode);+ }++ skipSeparationSpace(state, true, nodeIndent);++ ch = state.input.charCodeAt(state.position);++ if (ch === 0x2C/* , */) {+ readNext = true;+ ch = state.input.charCodeAt(++state.position);+ } else {+ readNext = false;+ }+ }++ throwError$1(state, 'unexpected end of the stream within a flow collection');+}++function readBlockScalar(state, nodeIndent) {+ var captureStart,+ folding,+ chomping = CHOMPING_CLIP,+ didReadContent = false,+ detectedIndent = false,+ textIndent = nodeIndent,+ emptyLines = 0,+ atMoreIndented = false,+ tmp,+ ch;++ ch = state.input.charCodeAt(state.position);++ if (ch === 0x7C/* | */) {+ folding = false;+ } else if (ch === 0x3E/* > */) {+ folding = true;+ } else {+ return false;+ }++ state.kind = 'scalar';+ state.result = '';++ while (ch !== 0) {+ ch = state.input.charCodeAt(++state.position);++ if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {+ if (CHOMPING_CLIP === chomping) {+ chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;+ } else {+ throwError$1(state, 'repeat of a chomping mode identifier');+ }++ } else if ((tmp = fromDecimalCode(ch)) >= 0) {+ if (tmp === 0) {+ throwError$1(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');+ } else if (!detectedIndent) {+ textIndent = nodeIndent + tmp - 1;+ detectedIndent = true;+ } else {+ throwError$1(state, 'repeat of an indentation width identifier');+ }++ } else {+ break;+ }+ }++ if (is_WHITE_SPACE(ch)) {+ do { ch = state.input.charCodeAt(++state.position); }+ while (is_WHITE_SPACE(ch));++ if (ch === 0x23/* # */) {+ do { ch = state.input.charCodeAt(++state.position); }+ while (!is_EOL(ch) && (ch !== 0));+ }+ }++ while (ch !== 0) {+ readLineBreak(state);+ state.lineIndent = 0;++ ch = state.input.charCodeAt(state.position);++ while ((!detectedIndent || state.lineIndent < textIndent) &&+ (ch === 0x20/* Space */)) {+ state.lineIndent++;+ ch = state.input.charCodeAt(++state.position);+ }++ if (!detectedIndent && state.lineIndent > textIndent) {+ textIndent = state.lineIndent;+ }++ if (is_EOL(ch)) {+ emptyLines++;+ continue;+ }++ // End of the scalar.+ if (state.lineIndent < textIndent) {++ // Perform the chomping.+ if (chomping === CHOMPING_KEEP) {+ state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);+ } else if (chomping === CHOMPING_CLIP) {+ if (didReadContent) { // i.e. only if the scalar is not empty.+ state.result += '\n';+ }+ }++ // Break this `while` cycle and go to the funciton's epilogue.+ break;+ }++ // Folded style: use fancy rules to handle line breaks.+ if (folding) {++ // Lines starting with white space characters (more-indented lines) are not folded.+ if (is_WHITE_SPACE(ch)) {+ atMoreIndented = true;+ // except for the first content line (cf. Example 8.1)+ state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);++ // End of more-indented block.+ } else if (atMoreIndented) {+ atMoreIndented = false;+ state.result += common$1.repeat('\n', emptyLines + 1);++ // Just one line break - perceive as the same line.+ } else if (emptyLines === 0) {+ if (didReadContent) { // i.e. only if we have already read some scalar content.+ state.result += ' ';+ }++ // Several line breaks - perceive as different lines.+ } else {+ state.result += common$1.repeat('\n', emptyLines);+ }++ // Literal style: just add exact number of line breaks between content lines.+ } else {+ // Keep all line breaks except the header line break.+ state.result += common$1.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);+ }++ didReadContent = true;+ detectedIndent = true;+ emptyLines = 0;+ captureStart = state.position;++ while (!is_EOL(ch) && (ch !== 0)) {+ ch = state.input.charCodeAt(++state.position);+ }++ captureSegment(state, captureStart, state.position, false);+ }++ return true;+}++function readBlockSequence(state, nodeIndent) {+ var _line,+ _tag = state.tag,+ _anchor = state.anchor,+ _result = [],+ following,+ detected = false,+ ch;++ if (state.anchor !== null) {+ state.anchorMap[state.anchor] = _result;+ }++ ch = state.input.charCodeAt(state.position);++ while (ch !== 0) {++ if (ch !== 0x2D/* - */) {+ break;+ }++ following = state.input.charCodeAt(state.position + 1);++ if (!is_WS_OR_EOL(following)) {+ break;+ }++ detected = true;+ state.position++;++ if (skipSeparationSpace(state, true, -1)) {+ if (state.lineIndent <= nodeIndent) {+ _result.push(null);+ ch = state.input.charCodeAt(state.position);+ continue;+ }+ }++ _line = state.line;+ composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);+ _result.push(state.result);+ skipSeparationSpace(state, true, -1);++ ch = state.input.charCodeAt(state.position);++ if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {+ throwError$1(state, 'bad indentation of a sequence entry');+ } else if (state.lineIndent < nodeIndent) {+ break;+ }+ }++ if (detected) {+ state.tag = _tag;+ state.anchor = _anchor;+ state.kind = 'sequence';+ state.result = _result;+ return true;+ }+ return false;+}++function readBlockMapping(state, nodeIndent, flowIndent) {+ var following,+ allowCompact,+ _line,+ _pos,+ _tag = state.tag,+ _anchor = state.anchor,+ _result = {},+ overridableKeys = {},+ keyTag = null,+ keyNode = null,+ valueNode = null,+ atExplicitKey = false,+ detected = false,+ ch;++ if (state.anchor !== null) {+ state.anchorMap[state.anchor] = _result;+ }++ ch = state.input.charCodeAt(state.position);++ while (ch !== 0) {+ following = state.input.charCodeAt(state.position + 1);+ _line = state.line; // Save the current line.+ _pos = state.position;++ //+ // Explicit notation case. There are two separate blocks:+ // first for the key (denoted by "?") and second for the value (denoted by ":")+ //+ if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {++ if (ch === 0x3F/* ? */) {+ if (atExplicitKey) {+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);+ keyTag = keyNode = valueNode = null;+ }++ detected = true;+ atExplicitKey = true;+ allowCompact = true;++ } else if (atExplicitKey) {+ // i.e. 0x3A/* : */ === character after the explicit key.+ atExplicitKey = false;+ allowCompact = true;++ } else {+ throwError$1(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');+ }++ state.position += 1;+ ch = following;++ //+ // Implicit notation case. Flow-style node as the key first, then ":", and the value.+ //+ } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {++ if (state.line === _line) {+ ch = state.input.charCodeAt(state.position);++ while (is_WHITE_SPACE(ch)) {+ ch = state.input.charCodeAt(++state.position);+ }++ if (ch === 0x3A/* : */) {+ ch = state.input.charCodeAt(++state.position);++ if (!is_WS_OR_EOL(ch)) {+ throwError$1(state, 'a whitespace character is expected after the key-value separator within a block mapping');+ }++ if (atExplicitKey) {+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);+ keyTag = keyNode = valueNode = null;+ }++ detected = true;+ atExplicitKey = false;+ allowCompact = false;+ keyTag = state.tag;+ keyNode = state.result;++ } else if (detected) {+ throwError$1(state, 'can not read an implicit mapping pair; a colon is missed');++ } else {+ state.tag = _tag;+ state.anchor = _anchor;+ return true; // Keep the result of `composeNode`.+ }++ } else if (detected) {+ throwError$1(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');++ } else {+ state.tag = _tag;+ state.anchor = _anchor;+ return true; // Keep the result of `composeNode`.+ }++ } else {+ break; // Reading is done. Go to the epilogue.+ }++ //+ // Common reading code for both explicit and implicit notations.+ //+ if (state.line === _line || state.lineIndent > nodeIndent) {+ if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {+ if (atExplicitKey) {+ keyNode = state.result;+ } else {+ valueNode = state.result;+ }+ }++ if (!atExplicitKey) {+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);+ keyTag = keyNode = valueNode = null;+ }++ skipSeparationSpace(state, true, -1);+ ch = state.input.charCodeAt(state.position);+ }++ if (state.lineIndent > nodeIndent && (ch !== 0)) {+ throwError$1(state, 'bad indentation of a mapping entry');+ } else if (state.lineIndent < nodeIndent) {+ break;+ }+ }++ //+ // Epilogue.+ //++ // Special case: last mapping's node contains only the key in explicit notation.+ if (atExplicitKey) {+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);+ }++ // Expose the resulting mapping.+ if (detected) {+ state.tag = _tag;+ state.anchor = _anchor;+ state.kind = 'mapping';+ state.result = _result;+ }++ return detected;+}++function readTagProperty(state) {+ var _position,+ isVerbatim = false,+ isNamed = false,+ tagHandle,+ tagName,+ ch;++ ch = state.input.charCodeAt(state.position);++ if (ch !== 0x21/* ! */) return false;++ if (state.tag !== null) {+ throwError$1(state, 'duplication of a tag property');+ }++ ch = state.input.charCodeAt(++state.position);++ if (ch === 0x3C/* < */) {+ isVerbatim = true;+ ch = state.input.charCodeAt(++state.position);++ } else if (ch === 0x21/* ! */) {+ isNamed = true;+ tagHandle = '!!';+ ch = state.input.charCodeAt(++state.position);++ } else {+ tagHandle = '!';+ }++ _position = state.position;++ if (isVerbatim) {+ do { ch = state.input.charCodeAt(++state.position); }+ while (ch !== 0 && ch !== 0x3E/* > */);++ if (state.position < state.length) {+ tagName = state.input.slice(_position, state.position);+ ch = state.input.charCodeAt(++state.position);+ } else {+ throwError$1(state, 'unexpected end of the stream within a verbatim tag');+ }+ } else {+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {++ if (ch === 0x21/* ! */) {+ if (!isNamed) {+ tagHandle = state.input.slice(_position - 1, state.position + 1);++ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {+ throwError$1(state, 'named tag handle cannot contain such characters');+ }++ isNamed = true;+ _position = state.position + 1;+ } else {+ throwError$1(state, 'tag suffix cannot contain exclamation marks');+ }+ }++ ch = state.input.charCodeAt(++state.position);+ }++ tagName = state.input.slice(_position, state.position);++ if (PATTERN_FLOW_INDICATORS.test(tagName)) {+ throwError$1(state, 'tag suffix cannot contain flow indicator characters');+ }+ }++ if (tagName && !PATTERN_TAG_URI.test(tagName)) {+ throwError$1(state, 'tag name cannot contain such characters: ' + tagName);+ }++ if (isVerbatim) {+ state.tag = tagName;++ } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) {+ state.tag = state.tagMap[tagHandle] + tagName;++ } else if (tagHandle === '!') {+ state.tag = '!' + tagName;++ } else if (tagHandle === '!!') {+ state.tag = 'tag:yaml.org,2002:' + tagName;++ } else {+ throwError$1(state, 'undeclared tag handle "' + tagHandle + '"');+ }++ return true;+}++function readAnchorProperty(state) {+ var _position,+ ch;++ ch = state.input.charCodeAt(state.position);++ if (ch !== 0x26/* & */) return false;++ if (state.anchor !== null) {+ throwError$1(state, 'duplication of an anchor property');+ }++ ch = state.input.charCodeAt(++state.position);+ _position = state.position;++ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {+ ch = state.input.charCodeAt(++state.position);+ }++ if (state.position === _position) {+ throwError$1(state, 'name of an anchor node must contain at least one character');+ }++ state.anchor = state.input.slice(_position, state.position);+ return true;+}++function readAlias(state) {+ var _position, alias,+ ch;++ ch = state.input.charCodeAt(state.position);++ if (ch !== 0x2A/* * */) return false;++ ch = state.input.charCodeAt(++state.position);+ _position = state.position;++ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {+ ch = state.input.charCodeAt(++state.position);+ }++ if (state.position === _position) {+ throwError$1(state, 'name of an alias node must contain at least one character');+ }++ alias = state.input.slice(_position, state.position);++ if (!state.anchorMap.hasOwnProperty(alias)) {+ throwError$1(state, 'unidentified alias "' + alias + '"');+ }++ state.result = state.anchorMap[alias];+ skipSeparationSpace(state, true, -1);+ return true;+}++function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {+ var allowBlockStyles,+ allowBlockScalars,+ allowBlockCollections,+ indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent+ atNewLine = false,+ hasContent = false,+ typeIndex,+ typeQuantity,+ type,+ flowIndent,+ blockIndent;++ if (state.listener !== null) {+ state.listener('open', state);+ }++ state.tag = null;+ state.anchor = null;+ state.kind = null;+ state.result = null;++ allowBlockStyles = allowBlockScalars = allowBlockCollections =+ CONTEXT_BLOCK_OUT === nodeContext ||+ CONTEXT_BLOCK_IN === nodeContext;++ if (allowToSeek) {+ if (skipSeparationSpace(state, true, -1)) {+ atNewLine = true;++ if (state.lineIndent > parentIndent) {+ indentStatus = 1;+ } else if (state.lineIndent === parentIndent) {+ indentStatus = 0;+ } else if (state.lineIndent < parentIndent) {+ indentStatus = -1;+ }+ }+ }++ if (indentStatus === 1) {+ while (readTagProperty(state) || readAnchorProperty(state)) {+ if (skipSeparationSpace(state, true, -1)) {+ atNewLine = true;+ allowBlockCollections = allowBlockStyles;++ if (state.lineIndent > parentIndent) {+ indentStatus = 1;+ } else if (state.lineIndent === parentIndent) {+ indentStatus = 0;+ } else if (state.lineIndent < parentIndent) {+ indentStatus = -1;+ }+ } else {+ allowBlockCollections = false;+ }+ }+ }++ if (allowBlockCollections) {+ allowBlockCollections = atNewLine || allowCompact;+ }++ if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {+ if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {+ flowIndent = parentIndent;+ } else {+ flowIndent = parentIndent + 1;+ }++ blockIndent = state.position - state.lineStart;++ if (indentStatus === 1) {+ if (allowBlockCollections &&+ (readBlockSequence(state, blockIndent) ||+ readBlockMapping(state, blockIndent, flowIndent)) ||+ readFlowCollection(state, flowIndent)) {+ hasContent = true;+ } else {+ if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||+ readSingleQuotedScalar(state, flowIndent) ||+ readDoubleQuotedScalar(state, flowIndent)) {+ hasContent = true;++ } else if (readAlias(state)) {+ hasContent = true;++ if (state.tag !== null || state.anchor !== null) {+ throwError$1(state, 'alias node should not have any properties');+ }++ } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {+ hasContent = true;++ if (state.tag === null) {+ state.tag = '?';+ }+ }++ if (state.anchor !== null) {+ state.anchorMap[state.anchor] = state.result;+ }+ }+ } else if (indentStatus === 0) {+ // Special case: block sequences are allowed to have same indentation level as the parent.+ // http://www.yaml.org/spec/1.2/spec.html#id2799784+ hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);+ }+ }++ if (state.tag !== null && state.tag !== '!') {+ if (state.tag === '?') {+ // Implicit resolving is not allowed for non-scalar types, and '?'+ // non-specific tag is only automatically assigned to plain scalars.+ //+ // We only need to check kind conformity in case user explicitly assigns '?'+ // tag, for example like this: "!<?> [0]"+ //+ if (state.result !== null && state.kind !== 'scalar') {+ throwError$1(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');+ }++ for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {+ type = state.implicitTypes[typeIndex];++ if (type.resolve(state.result)) { // `state.result` updated in resolver if matched+ state.result = type.construct(state.result);+ state.tag = type.tag;+ if (state.anchor !== null) {+ state.anchorMap[state.anchor] = state.result;+ }+ break;+ }+ }+ } else if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) {+ type = state.typeMap[state.kind || 'fallback'][state.tag];++ if (state.result !== null && type.kind !== state.kind) {+ throwError$1(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');+ }++ if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched+ throwError$1(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');+ } else {+ state.result = type.construct(state.result);+ if (state.anchor !== null) {+ state.anchorMap[state.anchor] = state.result;+ }+ }+ } else {+ throwError$1(state, 'unknown tag !<' + state.tag + '>');+ }+ }++ if (state.listener !== null) {+ state.listener('close', state);+ }+ return state.tag !== null || state.anchor !== null || hasContent;+}++function readDocument(state) {+ var documentStart = state.position,+ _position,+ directiveName,+ directiveArgs,+ hasDirectives = false,+ ch;++ state.version = null;+ state.checkLineBreaks = state.legacy;+ state.tagMap = {};+ state.anchorMap = {};++ while ((ch = state.input.charCodeAt(state.position)) !== 0) {+ skipSeparationSpace(state, true, -1);++ ch = state.input.charCodeAt(state.position);++ if (state.lineIndent > 0 || ch !== 0x25/* % */) {+ break;+ }++ hasDirectives = true;+ ch = state.input.charCodeAt(++state.position);+ _position = state.position;++ while (ch !== 0 && !is_WS_OR_EOL(ch)) {+ ch = state.input.charCodeAt(++state.position);+ }++ directiveName = state.input.slice(_position, state.position);+ directiveArgs = [];++ if (directiveName.length < 1) {+ throwError$1(state, 'directive name must not be less than one character in length');+ }++ while (ch !== 0) {+ while (is_WHITE_SPACE(ch)) {+ ch = state.input.charCodeAt(++state.position);+ }++ if (ch === 0x23/* # */) {+ do { ch = state.input.charCodeAt(++state.position); }+ while (ch !== 0 && !is_EOL(ch));+ break;+ }++ if (is_EOL(ch)) break;++ _position = state.position;++ while (ch !== 0 && !is_WS_OR_EOL(ch)) {+ ch = state.input.charCodeAt(++state.position);+ }++ directiveArgs.push(state.input.slice(_position, state.position));+ }++ if (ch !== 0) readLineBreak(state);++ if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) {+ directiveHandlers[directiveName](state, directiveName, directiveArgs);+ } else {+ throwWarning(state, 'unknown document directive "' + directiveName + '"');+ }+ }++ skipSeparationSpace(state, true, -1);++ if (state.lineIndent === 0 &&+ state.input.charCodeAt(state.position) === 0x2D/* - */ &&+ state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&+ state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {+ state.position += 3;+ skipSeparationSpace(state, true, -1);++ } else if (hasDirectives) {+ throwError$1(state, 'directives end mark is expected');+ }++ composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);+ skipSeparationSpace(state, true, -1);++ if (state.checkLineBreaks &&+ PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {+ throwWarning(state, 'non-ASCII line breaks are interpreted as content');+ }++ state.documents.push(state.result);++ if (state.position === state.lineStart && testDocumentSeparator(state)) {++ if (state.input.charCodeAt(state.position) === 0x2E/* . */) {+ state.position += 3;+ skipSeparationSpace(state, true, -1);+ }+ return;+ }++ if (state.position < (state.length - 1)) {+ throwError$1(state, 'end of the stream or a document separator is expected');+ } else {+ return;+ }+}+++function loadDocuments$1(input, options) {+ input = String(input);+ options = options || {};++ if (input.length !== 0) {++ // Add tailing `\n` if not exists+ if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&+ input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {+ input += '\n';+ }++ // Strip BOM+ if (input.charCodeAt(0) === 0xFEFF) {+ input = input.slice(1);+ }+ }++ var state = new State(input, options);++ var nullpos = input.indexOf('\0');++ if (nullpos !== -1) {+ state.position = nullpos;+ throwError$1(state, 'null byte is not allowed in input');+ }++ // Use 0 as string terminator. That significantly simplifies bounds check.+ state.input += '\0';++ while (state.input.charCodeAt(state.position) === 0x20/* Space */) {+ state.lineIndent += 1;+ state.position += 1;+ }++ while (state.position < (state.length - 1)) {+ readDocument(state);+ }++ return state.documents;+}+++function loadAll(input, iterator, options) {+ if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {+ options = iterator;+ iterator = null;+ }++ var documents = loadDocuments$1(input, options);++ if (typeof iterator !== 'function') {+ return documents;+ }++ for (var index = 0, length = documents.length; index < length; index += 1) {+ iterator(documents[index]);+ }+}+++function load(input, options) {+ var documents = loadDocuments$1(input, options);++ if (documents.length === 0) {+ /*eslint-disable no-undefined*/+ return undefined;+ } else if (documents.length === 1) {+ return documents[0];+ }+ throw new exception('expected a single document in the stream, but found more');+}+++function safeLoadAll(input, iterator, options) {+ if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {+ options = iterator;+ iterator = null;+ }++ return loadAll(input, iterator, common$1.extend({ schema: default_safe }, options));+}+++function safeLoad(input, options) {+ return load(input, common$1.extend({ schema: default_safe }, options));+}+++var loadAll_1 = loadAll;+var load_1 = load;+var safeLoadAll_1 = safeLoadAll;+var safeLoad_1 = safeLoad;++var loader = {+ loadAll: loadAll_1,+ load: load_1,+ safeLoadAll: safeLoadAll_1,+ safeLoad: safeLoad_1+};++/*eslint-disable no-use-before-define*/+++++++var _toString$2 = Object.prototype.toString;+var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;++var CHAR_TAB = 0x09; /* Tab */+var CHAR_LINE_FEED = 0x0A; /* LF */+var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */+var CHAR_SPACE = 0x20; /* Space */+var CHAR_EXCLAMATION = 0x21; /* ! */+var CHAR_DOUBLE_QUOTE$1 = 0x22; /* " */+var CHAR_SHARP = 0x23; /* # */+var CHAR_PERCENT = 0x25; /* % */+var CHAR_AMPERSAND = 0x26; /* & */+var CHAR_SINGLE_QUOTE$1 = 0x27; /* ' */+var CHAR_ASTERISK$1 = 0x2A; /* * */+var CHAR_COMMA$2 = 0x2C; /* , */+var CHAR_MINUS = 0x2D; /* - */+var CHAR_COLON = 0x3A; /* : */+var CHAR_EQUALS = 0x3D; /* = */+var CHAR_GREATER_THAN = 0x3E; /* > */+var CHAR_QUESTION = 0x3F; /* ? */+var CHAR_COMMERCIAL_AT = 0x40; /* @ */+var CHAR_LEFT_SQUARE_BRACKET$2 = 0x5B; /* [ */+var CHAR_RIGHT_SQUARE_BRACKET$2 = 0x5D; /* ] */+var CHAR_GRAVE_ACCENT = 0x60; /* ` */+var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */+var CHAR_VERTICAL_LINE = 0x7C; /* | */+var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */++var ESCAPE_SEQUENCES = {};++ESCAPE_SEQUENCES[0x00] = '\\0';+ESCAPE_SEQUENCES[0x07] = '\\a';+ESCAPE_SEQUENCES[0x08] = '\\b';+ESCAPE_SEQUENCES[0x09] = '\\t';+ESCAPE_SEQUENCES[0x0A] = '\\n';+ESCAPE_SEQUENCES[0x0B] = '\\v';+ESCAPE_SEQUENCES[0x0C] = '\\f';+ESCAPE_SEQUENCES[0x0D] = '\\r';+ESCAPE_SEQUENCES[0x1B] = '\\e';+ESCAPE_SEQUENCES[0x22] = '\\"';+ESCAPE_SEQUENCES[0x5C] = '\\\\';+ESCAPE_SEQUENCES[0x85] = '\\N';+ESCAPE_SEQUENCES[0xA0] = '\\_';+ESCAPE_SEQUENCES[0x2028] = '\\L';+ESCAPE_SEQUENCES[0x2029] = '\\P';++var DEPRECATED_BOOLEANS_SYNTAX = [+ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',+ 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'+];++function compileStyleMap(schema, map) {+ var result, keys, index, length, tag, style, type;++ if (map === null) return {};++ result = {};+ keys = Object.keys(map);++ for (index = 0, length = keys.length; index < length; index += 1) {+ tag = keys[index];+ style = String(map[tag]);++ if (tag.slice(0, 2) === '!!') {+ tag = 'tag:yaml.org,2002:' + tag.slice(2);+ }+ type = schema.compiledTypeMap['fallback'][tag];++ if (type && _hasOwnProperty$3.call(type.styleAliases, style)) {+ style = type.styleAliases[style];+ }++ result[tag] = style;+ }++ return result;+}++function encodeHex(character) {+ var string, handle, length;++ string = character.toString(16).toUpperCase();++ if (character <= 0xFF) {+ handle = 'x';+ length = 2;+ } else if (character <= 0xFFFF) {+ handle = 'u';+ length = 4;+ } else if (character <= 0xFFFFFFFF) {+ handle = 'U';+ length = 8;+ } else {+ throw new exception('code point within a string may not be greater than 0xFFFFFFFF');+ }++ return '\\' + handle + common$1.repeat('0', length - string.length) + string;+}++function State$1(options) {+ this.schema = options['schema'] || default_full;+ this.indent = Math.max(1, (options['indent'] || 2));+ this.noArrayIndent = options['noArrayIndent'] || false;+ this.skipInvalid = options['skipInvalid'] || false;+ this.flowLevel = (common$1.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);+ this.styleMap = compileStyleMap(this.schema, options['styles'] || null);+ this.sortKeys = options['sortKeys'] || false;+ this.lineWidth = options['lineWidth'] || 80;+ this.noRefs = options['noRefs'] || false;+ this.noCompatMode = options['noCompatMode'] || false;+ this.condenseFlow = options['condenseFlow'] || false;++ this.implicitTypes = this.schema.compiledImplicit;+ this.explicitTypes = this.schema.compiledExplicit;++ this.tag = null;+ this.result = '';++ this.duplicates = [];+ this.usedDuplicates = null;+}++// Indents every line in a string. Empty lines (\n only) are not indented.+function indentString$2(string, spaces) {+ var ind = common$1.repeat(' ', spaces),+ position = 0,+ next = -1,+ result = '',+ line,+ length = string.length;++ while (position < length) {+ next = string.indexOf('\n', position);+ if (next === -1) {+ line = string.slice(position);+ position = length;+ } else {+ line = string.slice(position, next + 1);+ position = next + 1;+ }++ if (line.length && line !== '\n') result += ind;++ result += line;+ }++ return result;+}++function generateNextLine(state, level) {+ return '\n' + common$1.repeat(' ', state.indent * level);+}++function testImplicitResolving(state, str) {+ var index, length, type;++ for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {+ type = state.implicitTypes[index];++ if (type.resolve(str)) {+ return true;+ }+ }++ return false;+}++// [33] s-white ::= s-space | s-tab+function isWhitespace(c) {+ return c === CHAR_SPACE || c === CHAR_TAB;+}++// Returns true if the character can be printed without escaping.+// From YAML 1.2: "any allowed characters known to be non-printable+// should also be escaped. [However,] This isn’t mandatory"+// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.+function isPrintable(c) {+ return (0x00020 <= c && c <= 0x00007E)+ || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)+ || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)+ || (0x10000 <= c && c <= 0x10FFFF);+}++// [34] ns-char ::= nb-char - s-white+// [27] nb-char ::= c-printable - b-char - c-byte-order-mark+// [26] b-char ::= b-line-feed | b-carriage-return+// [24] b-line-feed ::= #xA /* LF */+// [25] b-carriage-return ::= #xD /* CR */+// [3] c-byte-order-mark ::= #xFEFF+function isNsChar(c) {+ return isPrintable(c) && !isWhitespace(c)+ // byte-order-mark+ && c !== 0xFEFF+ // b-char+ && c !== CHAR_CARRIAGE_RETURN+ && c !== CHAR_LINE_FEED;+}++// Simplified test for values allowed after the first character in plain style.+function isPlainSafe(c, prev) {+ // Uses a subset of nb-char - c-flow-indicator - ":" - "#"+ // where nb-char ::= c-printable - b-char - c-byte-order-mark.+ return isPrintable(c) && c !== 0xFEFF+ // - c-flow-indicator+ && c !== CHAR_COMMA$2+ && c !== CHAR_LEFT_SQUARE_BRACKET$2+ && c !== CHAR_RIGHT_SQUARE_BRACKET$2+ && c !== CHAR_LEFT_CURLY_BRACKET+ && c !== CHAR_RIGHT_CURLY_BRACKET+ // - ":" - "#"+ // /* An ns-char preceding */ "#"+ && c !== CHAR_COLON+ && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));+}++// Simplified test for values allowed as the first character in plain style.+function isPlainSafeFirst(c) {+ // Uses a subset of ns-char - c-indicator+ // where ns-char = nb-char - s-white.+ return isPrintable(c) && c !== 0xFEFF+ && !isWhitespace(c) // - s-white+ // - (c-indicator ::=+ // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”+ && c !== CHAR_MINUS+ && c !== CHAR_QUESTION+ && c !== CHAR_COLON+ && c !== CHAR_COMMA$2+ && c !== CHAR_LEFT_SQUARE_BRACKET$2+ && c !== CHAR_RIGHT_SQUARE_BRACKET$2+ && c !== CHAR_LEFT_CURLY_BRACKET+ && c !== CHAR_RIGHT_CURLY_BRACKET+ // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”+ && c !== CHAR_SHARP+ && c !== CHAR_AMPERSAND+ && c !== CHAR_ASTERISK$1+ && c !== CHAR_EXCLAMATION+ && c !== CHAR_VERTICAL_LINE+ && c !== CHAR_EQUALS+ && c !== CHAR_GREATER_THAN+ && c !== CHAR_SINGLE_QUOTE$1+ && c !== CHAR_DOUBLE_QUOTE$1+ // | “%” | “@” | “`”)+ && c !== CHAR_PERCENT+ && c !== CHAR_COMMERCIAL_AT+ && c !== CHAR_GRAVE_ACCENT;+}++// Determines whether block indentation indicator is required.+function needIndentIndicator(string) {+ var leadingSpaceRe = /^\n* /;+ return leadingSpaceRe.test(string);+}++var STYLE_PLAIN = 1,+ STYLE_SINGLE = 2,+ STYLE_LITERAL = 3,+ STYLE_FOLDED = 4,+ STYLE_DOUBLE = 5;++// Determines which scalar styles are possible and returns the preferred style.+// lineWidth = -1 => no limit.+// Pre-conditions: str.length > 0.+// Post-conditions:+// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.+// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).+// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).+function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {+ var i;+ var char, prev_char;+ var hasLineBreak = false;+ var hasFoldableLine = false; // only checked if shouldTrackWidth+ var shouldTrackWidth = lineWidth !== -1;+ var previousLineBreak = -1; // count the first line correctly+ var plain = isPlainSafeFirst(string.charCodeAt(0))+ && !isWhitespace(string.charCodeAt(string.length - 1));++ if (singleLineOnly) {+ // Case: no block styles.+ // Check for disallowed characters to rule out plain and single.+ for (i = 0; i < string.length; i++) {+ char = string.charCodeAt(i);+ if (!isPrintable(char)) {+ return STYLE_DOUBLE;+ }+ prev_char = i > 0 ? string.charCodeAt(i - 1) : null;+ plain = plain && isPlainSafe(char, prev_char);+ }+ } else {+ // Case: block styles permitted.+ for (i = 0; i < string.length; i++) {+ char = string.charCodeAt(i);+ if (char === CHAR_LINE_FEED) {+ hasLineBreak = true;+ // Check if any line can be folded.+ if (shouldTrackWidth) {+ hasFoldableLine = hasFoldableLine ||+ // Foldable line = too long, and not more-indented.+ (i - previousLineBreak - 1 > lineWidth &&+ string[previousLineBreak + 1] !== ' ');+ previousLineBreak = i;+ }+ } else if (!isPrintable(char)) {+ return STYLE_DOUBLE;+ }+ prev_char = i > 0 ? string.charCodeAt(i - 1) : null;+ plain = plain && isPlainSafe(char, prev_char);+ }+ // in case the end is missing a \n+ hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&+ (i - previousLineBreak - 1 > lineWidth &&+ string[previousLineBreak + 1] !== ' '));+ }+ // Although every style can represent \n without escaping, prefer block styles+ // for multiline, since they're more readable and they don't add empty lines.+ // Also prefer folding a super-long line.+ if (!hasLineBreak && !hasFoldableLine) {+ // Strings interpretable as another type have to be quoted;+ // e.g. the string 'true' vs. the boolean true.+ return plain && !testAmbiguousType(string)+ ? STYLE_PLAIN : STYLE_SINGLE;+ }+ // Edge case: block indentation indicator can only have one digit.+ if (indentPerLevel > 9 && needIndentIndicator(string)) {+ return STYLE_DOUBLE;+ }+ // At this point we know block styles are valid.+ // Prefer literal style unless we want to fold.+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;+}++// Note: line breaking/folding is implemented for only the folded style.+// NB. We drop the last trailing newline (if any) of a returned block scalar+// since the dumper adds its own newline. This always works:+// • No ending newline => unaffected; already using strip "-" chomping.+// • Ending newline => removed then restored.+// Importantly, this keeps the "+" chomp indicator from gaining an extra line.+function writeScalar(state, string, level, iskey) {+ state.dump = (function () {+ if (string.length === 0) {+ return "''";+ }+ if (!state.noCompatMode &&+ DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {+ return "'" + string + "'";+ }++ var indent = state.indent * Math.max(1, level); // no 0-indent scalars+ // As indentation gets deeper, let the width decrease monotonically+ // to the lower bound min(state.lineWidth, 40).+ // Note that this implies+ // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.+ // state.lineWidth > 40 + state.indent: width decreases until the lower bound.+ // This behaves better than a constant minimum width which disallows narrower options,+ // or an indent threshold which causes the width to suddenly increase.+ var lineWidth = state.lineWidth === -1+ ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);++ // Without knowing if keys are implicit/explicit, assume implicit for safety.+ var singleLineOnly = iskey+ // No block styles in flow mode.+ || (state.flowLevel > -1 && level >= state.flowLevel);+ function testAmbiguity(string) {+ return testImplicitResolving(state, string);+ }++ switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {+ case STYLE_PLAIN:+ return string;+ case STYLE_SINGLE:+ return "'" + string.replace(/'/g, "''") + "'";+ case STYLE_LITERAL:+ return '|' + blockHeader(string, state.indent)+ + dropEndingNewline(indentString$2(string, indent));+ case STYLE_FOLDED:+ return '>' + blockHeader(string, state.indent)+ + dropEndingNewline(indentString$2(foldString(string, lineWidth), indent));+ case STYLE_DOUBLE:+ return '"' + escapeString(string) + '"';+ default:+ throw new exception('impossible error: invalid scalar style');+ }+ }());+}++// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.+function blockHeader(string, indentPerLevel) {+ var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';++ // note the special case: the string '\n' counts as a "trailing" empty line.+ var clip = string[string.length - 1] === '\n';+ var keep = clip && (string[string.length - 2] === '\n' || string === '\n');+ var chomp = keep ? '+' : (clip ? '' : '-');++ return indentIndicator + chomp + '\n';+}++// (See the note for writeScalar.)+function dropEndingNewline(string) {+ return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;+}++// Note: a long line without a suitable break point will exceed the width limit.+// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.+function foldString(string, width) {+ // In folded style, $k$ consecutive newlines output as $k+1$ newlines—+ // unless they're before or after a more-indented line, or at the very+ // beginning or end, in which case $k$ maps to $k$.+ // Therefore, parse each chunk as newline(s) followed by a content line.+ var lineRe = /(\n+)([^\n]*)/g;++ // first line (possibly an empty line)+ var result = (function () {+ var nextLF = string.indexOf('\n');+ nextLF = nextLF !== -1 ? nextLF : string.length;+ lineRe.lastIndex = nextLF;+ return foldLine(string.slice(0, nextLF), width);+ }());+ // If we haven't reached the first content line yet, don't add an extra \n.+ var prevMoreIndented = string[0] === '\n' || string[0] === ' ';+ var moreIndented;++ // rest of the lines+ var match;+ while ((match = lineRe.exec(string))) {+ var prefix = match[1], line = match[2];+ moreIndented = (line[0] === ' ');+ result += prefix+ + (!prevMoreIndented && !moreIndented && line !== ''+ ? '\n' : '')+ + foldLine(line, width);+ prevMoreIndented = moreIndented;+ }++ return result;+}++// Greedy line breaking.+// Picks the longest line under the limit each time,+// otherwise settles for the shortest line over the limit.+// NB. More-indented lines *cannot* be folded, as that would add an extra \n.+function foldLine(line, width) {+ if (line === '' || line[0] === ' ') return line;++ // Since a more-indented line adds a \n, breaks can't be followed by a space.+ var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.+ var match;+ // start is an inclusive index. end, curr, and next are exclusive.+ var start = 0, end, curr = 0, next = 0;+ var result = '';++ // Invariants: 0 <= start <= length-1.+ // 0 <= curr <= next <= max(0, length-2). curr - start <= width.+ // Inside the loop:+ // A match implies length >= 2, so curr and next are <= length-2.+ while ((match = breakRe.exec(line))) {+ next = match.index;+ // maintain invariant: curr - start <= width+ if (next - start > width) {+ end = (curr > start) ? curr : next; // derive end <= length-2+ result += '\n' + line.slice(start, end);+ // skip the space that was output as \n+ start = end + 1; // derive start <= length-1+ }+ curr = next;+ }++ // By the invariants, start <= length-1, so there is something left over.+ // It is either the whole string or a part starting from non-whitespace.+ result += '\n';+ // Insert a break if the remainder is too long and there is a break available.+ if (line.length - start > width && curr > start) {+ result += line.slice(start, curr) + '\n' + line.slice(curr + 1);+ } else {+ result += line.slice(start);+ }++ return result.slice(1); // drop extra \n joiner+}++// Escapes a double-quoted string.+function escapeString(string) {+ var result = '';+ var char, nextChar;+ var escapeSeq;++ for (var i = 0; i < string.length; i++) {+ char = string.charCodeAt(i);+ // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates").+ if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {+ nextChar = string.charCodeAt(i + 1);+ if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {+ // Combine the surrogate pair and store it escaped.+ result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);+ // Advance index one extra since we already used that char here.+ i++; continue;+ }+ }+ escapeSeq = ESCAPE_SEQUENCES[char];+ result += !escapeSeq && isPrintable(char)+ ? string[i]+ : escapeSeq || encodeHex(char);+ }++ return result;+}++function writeFlowSequence(state, level, object) {+ var _result = '',+ _tag = state.tag,+ index,+ length;++ for (index = 0, length = object.length; index < length; index += 1) {+ // Write only valid elements.+ if (writeNode(state, level, object[index], false, false)) {+ if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');+ _result += state.dump;+ }+ }++ state.tag = _tag;+ state.dump = '[' + _result + ']';+}++function writeBlockSequence(state, level, object, compact) {+ var _result = '',+ _tag = state.tag,+ index,+ length;++ for (index = 0, length = object.length; index < length; index += 1) {+ // Write only valid elements.+ if (writeNode(state, level + 1, object[index], true, true)) {+ if (!compact || index !== 0) {+ _result += generateNextLine(state, level);+ }++ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {+ _result += '-';+ } else {+ _result += '- ';+ }++ _result += state.dump;+ }+ }++ state.tag = _tag;+ state.dump = _result || '[]'; // Empty sequence if no valid values.+}++function writeFlowMapping(state, level, object) {+ var _result = '',+ _tag = state.tag,+ objectKeyList = Object.keys(object),+ index,+ length,+ objectKey,+ objectValue,+ pairBuffer;++ for (index = 0, length = objectKeyList.length; index < length; index += 1) {++ pairBuffer = '';+ if (index !== 0) pairBuffer += ', ';++ if (state.condenseFlow) pairBuffer += '"';++ objectKey = objectKeyList[index];+ objectValue = object[objectKey];++ if (!writeNode(state, level, objectKey, false, false)) {+ continue; // Skip this pair because of invalid key;+ }++ if (state.dump.length > 1024) pairBuffer += '? ';++ pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');++ if (!writeNode(state, level, objectValue, false, false)) {+ continue; // Skip this pair because of invalid value.+ }++ pairBuffer += state.dump;++ // Both key and value are valid.+ _result += pairBuffer;+ }++ state.tag = _tag;+ state.dump = '{' + _result + '}';+}++function writeBlockMapping(state, level, object, compact) {+ var _result = '',+ _tag = state.tag,+ objectKeyList = Object.keys(object),+ index,+ length,+ objectKey,+ objectValue,+ explicitPair,+ pairBuffer;++ // Allow sorting keys so that the output file is deterministic+ if (state.sortKeys === true) {+ // Default sorting+ objectKeyList.sort();+ } else if (typeof state.sortKeys === 'function') {+ // Custom sort function+ objectKeyList.sort(state.sortKeys);+ } else if (state.sortKeys) {+ // Something is wrong+ throw new exception('sortKeys must be a boolean or a function');+ }++ for (index = 0, length = objectKeyList.length; index < length; index += 1) {+ pairBuffer = '';++ if (!compact || index !== 0) {+ pairBuffer += generateNextLine(state, level);+ }++ objectKey = objectKeyList[index];+ objectValue = object[objectKey];++ if (!writeNode(state, level + 1, objectKey, true, true, true)) {+ continue; // Skip this pair because of invalid key.+ }++ explicitPair = (state.tag !== null && state.tag !== '?') ||+ (state.dump && state.dump.length > 1024);++ if (explicitPair) {+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {+ pairBuffer += '?';+ } else {+ pairBuffer += '? ';+ }+ }++ pairBuffer += state.dump;++ if (explicitPair) {+ pairBuffer += generateNextLine(state, level);+ }++ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {+ continue; // Skip this pair because of invalid value.+ }++ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {+ pairBuffer += ':';+ } else {+ pairBuffer += ': ';+ }++ pairBuffer += state.dump;++ // Both key and value are valid.+ _result += pairBuffer;+ }++ state.tag = _tag;+ state.dump = _result || '{}'; // Empty mapping if no valid pairs.+}++function detectType(state, object, explicit) {+ var _result, typeList, index, length, type, style;++ typeList = explicit ? state.explicitTypes : state.implicitTypes;++ for (index = 0, length = typeList.length; index < length; index += 1) {+ type = typeList[index];++ if ((type.instanceOf || type.predicate) &&+ (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&+ (!type.predicate || type.predicate(object))) {++ state.tag = explicit ? type.tag : '?';++ if (type.represent) {+ style = state.styleMap[type.tag] || type.defaultStyle;++ if (_toString$2.call(type.represent) === '[object Function]') {+ _result = type.represent(object, style);+ } else if (_hasOwnProperty$3.call(type.represent, style)) {+ _result = type.represent[style](object, style);+ } else {+ throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');+ }++ state.dump = _result;+ }++ return true;+ }+ }++ return false;+}++// Serializes `object` and writes it to global `result`.+// Returns true on success, or false on invalid object.+//+function writeNode(state, level, object, block, compact, iskey) {+ state.tag = null;+ state.dump = object;++ if (!detectType(state, object, false)) {+ detectType(state, object, true);+ }++ var type = _toString$2.call(state.dump);++ if (block) {+ block = (state.flowLevel < 0 || state.flowLevel > level);+ }++ var objectOrArray = type === '[object Object]' || type === '[object Array]',+ duplicateIndex,+ duplicate;++ if (objectOrArray) {+ duplicateIndex = state.duplicates.indexOf(object);+ duplicate = duplicateIndex !== -1;+ }++ if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {+ compact = false;+ }++ if (duplicate && state.usedDuplicates[duplicateIndex]) {+ state.dump = '*ref_' + duplicateIndex;+ } else {+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {+ state.usedDuplicates[duplicateIndex] = true;+ }+ if (type === '[object Object]') {+ if (block && (Object.keys(state.dump).length !== 0)) {+ writeBlockMapping(state, level, state.dump, compact);+ if (duplicate) {+ state.dump = '&ref_' + duplicateIndex + state.dump;+ }+ } else {+ writeFlowMapping(state, level, state.dump);+ if (duplicate) {+ state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;+ }+ }+ } else if (type === '[object Array]') {+ var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;+ if (block && (state.dump.length !== 0)) {+ writeBlockSequence(state, arrayLevel, state.dump, compact);+ if (duplicate) {+ state.dump = '&ref_' + duplicateIndex + state.dump;+ }+ } else {+ writeFlowSequence(state, arrayLevel, state.dump);+ if (duplicate) {+ state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;+ }+ }+ } else if (type === '[object String]') {+ if (state.tag !== '?') {+ writeScalar(state, state.dump, level, iskey);+ }+ } else {+ if (state.skipInvalid) return false;+ throw new exception('unacceptable kind of an object to dump ' + type);+ }++ if (state.tag !== null && state.tag !== '?') {+ state.dump = '!<' + state.tag + '> ' + state.dump;+ }+ }++ return true;+}++function getDuplicateReferences(object, state) {+ var objects = [],+ duplicatesIndexes = [],+ index,+ length;++ inspectNode(object, objects, duplicatesIndexes);++ for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {+ state.duplicates.push(objects[duplicatesIndexes[index]]);+ }+ state.usedDuplicates = new Array(length);+}++function inspectNode(object, objects, duplicatesIndexes) {+ var objectKeyList,+ index,+ length;++ if (object !== null && typeof object === 'object') {+ index = objects.indexOf(object);+ if (index !== -1) {+ if (duplicatesIndexes.indexOf(index) === -1) {+ duplicatesIndexes.push(index);+ }+ } else {+ objects.push(object);++ if (Array.isArray(object)) {+ for (index = 0, length = object.length; index < length; index += 1) {+ inspectNode(object[index], objects, duplicatesIndexes);+ }+ } else {+ objectKeyList = Object.keys(object);++ for (index = 0, length = objectKeyList.length; index < length; index += 1) {+ inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);+ }+ }+ }+ }+}++function dump(input, options) {+ options = options || {};++ var state = new State$1(options);++ if (!state.noRefs) getDuplicateReferences(input, state);++ if (writeNode(state, 0, input, true, true)) return state.dump + '\n';++ return '';+}++function safeDump(input, options) {+ return dump(input, common$1.extend({ schema: default_safe }, options));+}++var dump_1 = dump;+var safeDump_1 = safeDump;++var dumper = {+ dump: dump_1,+ safeDump: safeDump_1+};++function deprecated(name) {+ return function () {+ throw new Error('Function ' + name + ' is deprecated and cannot be used.');+ };+}+++var Type$1 = type;+var Schema$1 = schema;+var FAILSAFE_SCHEMA = failsafe;+var JSON_SCHEMA = json$1;+var CORE_SCHEMA = core;+var DEFAULT_SAFE_SCHEMA = default_safe;+var DEFAULT_FULL_SCHEMA = default_full;+var load$1 = loader.load;+var loadAll$1 = loader.loadAll;+var safeLoad$1 = loader.safeLoad;+var safeLoadAll$1 = loader.safeLoadAll;+var dump$1 = dumper.dump;+var safeDump$1 = dumper.safeDump;+var YAMLException$1 = exception;++// Deprecated schema names from JS-YAML 2.0.x+var MINIMAL_SCHEMA = failsafe;+var SAFE_SCHEMA = default_safe;+var DEFAULT_SCHEMA = default_full;++// Deprecated functions from JS-YAML 1.x.x+var scan$1 = deprecated('scan');+var parse$4 = deprecated('parse');+var compose = deprecated('compose');+var addConstructor = deprecated('addConstructor');++var jsYaml = {+ Type: Type$1,+ Schema: Schema$1,+ FAILSAFE_SCHEMA: FAILSAFE_SCHEMA,+ JSON_SCHEMA: JSON_SCHEMA,+ CORE_SCHEMA: CORE_SCHEMA,+ DEFAULT_SAFE_SCHEMA: DEFAULT_SAFE_SCHEMA,+ DEFAULT_FULL_SCHEMA: DEFAULT_FULL_SCHEMA,+ load: load$1,+ loadAll: loadAll$1,+ safeLoad: safeLoad$1,+ safeLoadAll: safeLoadAll$1,+ dump: dump$1,+ safeDump: safeDump$1,+ YAMLException: YAMLException$1,+ MINIMAL_SCHEMA: MINIMAL_SCHEMA,+ SAFE_SCHEMA: SAFE_SCHEMA,+ DEFAULT_SCHEMA: DEFAULT_SCHEMA,+ scan: scan$1,+ parse: parse$4,+ compose: compose,+ addConstructor: addConstructor+};++var jsYaml$1 = jsYaml;++function _extends() {+ _extends = Object.assign || function (target) {+ for (var i = 1; i < arguments.length; i++) {+ var source = arguments[i];++ for (var key in source) {+ if (Object.prototype.hasOwnProperty.call(source, key)) {+ target[key] = source[key];+ }+ }+ }++ return target;+ };++ return _extends.apply(this, arguments);+}++function _defineProperties$5(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);+ }+}++function _createClass$5(Constructor, protoProps, staticProps) {+ if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);+ if (staticProps) _defineProperties$5(Constructor, staticProps);+ return Constructor;+}++/** Used for built-in method references. */+var objectProto = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$1 = objectProto.hasOwnProperty;++/**+ * The base implementation of `_.has` without support for deep paths.+ *+ * @private+ * @param {Object} [object] The object to query.+ * @param {Array|string} key The key to check.+ * @returns {boolean} Returns `true` if `key` exists, else `false`.+ */+function baseHas(object, key) {+ return object != null && hasOwnProperty$1.call(object, key);+}++/**+ * Checks if `value` is classified as an `Array` object.+ *+ * @static+ * @memberOf _+ * @since 0.1.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is an array, else `false`.+ * @example+ *+ * _.isArray([1, 2, 3]);+ * // => true+ *+ * _.isArray(document.body.children);+ * // => false+ *+ * _.isArray('abc');+ * // => false+ *+ * _.isArray(_.noop);+ * // => false+ */+var isArray = Array.isArray;++/** Detect free variable `global` from Node.js. */+var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;++/** Detect free variable `self`. */+var freeSelf = typeof self == 'object' && self && self.Object === Object && self;++/** Used as a reference to the global object. */+var root$1 = freeGlobal || freeSelf || Function('return this')();++/** Built-in value references. */+var Symbol$1 = root$1.Symbol;++/** Used for built-in method references. */+var objectProto$1 = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$2 = objectProto$1.hasOwnProperty;++/**+ * Used to resolve the+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)+ * of values.+ */+var nativeObjectToString = objectProto$1.toString;++/** Built-in value references. */+var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;++/**+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.+ *+ * @private+ * @param {*} value The value to query.+ * @returns {string} Returns the raw `toStringTag`.+ */+function getRawTag(value) {+ var isOwn = hasOwnProperty$2.call(value, symToStringTag),+ tag = value[symToStringTag];++ try {+ value[symToStringTag] = undefined;+ var unmasked = true;+ } catch (e) {}++ var result = nativeObjectToString.call(value);+ if (unmasked) {+ if (isOwn) {+ value[symToStringTag] = tag;+ } else {+ delete value[symToStringTag];+ }+ }+ return result;+}++/** Used for built-in method references. */+var objectProto$2 = Object.prototype;++/**+ * Used to resolve the+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)+ * of values.+ */+var nativeObjectToString$1 = objectProto$2.toString;++/**+ * Converts `value` to a string using `Object.prototype.toString`.+ *+ * @private+ * @param {*} value The value to convert.+ * @returns {string} Returns the converted string.+ */+function objectToString(value) {+ return nativeObjectToString$1.call(value);+}++/** `Object#toString` result references. */+var nullTag = '[object Null]',+ undefinedTag = '[object Undefined]';++/** Built-in value references. */+var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;++/**+ * The base implementation of `getTag` without fallbacks for buggy environments.+ *+ * @private+ * @param {*} value The value to query.+ * @returns {string} Returns the `toStringTag`.+ */+function baseGetTag(value) {+ if (value == null) {+ return value === undefined ? undefinedTag : nullTag;+ }+ return (symToStringTag$1 && symToStringTag$1 in Object(value))+ ? getRawTag(value)+ : objectToString(value);+}++/**+ * Checks if `value` is object-like. A value is object-like if it's not `null`+ * and has a `typeof` result of "object".+ *+ * @static+ * @memberOf _+ * @since 4.0.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.+ * @example+ *+ * _.isObjectLike({});+ * // => true+ *+ * _.isObjectLike([1, 2, 3]);+ * // => true+ *+ * _.isObjectLike(_.noop);+ * // => false+ *+ * _.isObjectLike(null);+ * // => false+ */+function isObjectLike$1(value) {+ return value != null && typeof value == 'object';+}++/** `Object#toString` result references. */+var symbolTag = '[object Symbol]';++/**+ * Checks if `value` is classified as a `Symbol` primitive or object.+ *+ * @static+ * @memberOf _+ * @since 4.0.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.+ * @example+ *+ * _.isSymbol(Symbol.iterator);+ * // => true+ *+ * _.isSymbol('abc');+ * // => false+ */+function isSymbol(value) {+ return typeof value == 'symbol' ||+ (isObjectLike$1(value) && baseGetTag(value) == symbolTag);+}++/** Used to match property names within property paths. */+var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,+ reIsPlainProp = /^\w*$/;++/**+ * Checks if `value` is a property name and not a property path.+ *+ * @private+ * @param {*} value The value to check.+ * @param {Object} [object] The object to query keys on.+ * @returns {boolean} Returns `true` if `value` is a property name, else `false`.+ */+function isKey(value, object) {+ if (isArray(value)) {+ return false;+ }+ var type = typeof value;+ if (type == 'number' || type == 'symbol' || type == 'boolean' ||+ value == null || isSymbol(value)) {+ return true;+ }+ return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||+ (object != null && value in Object(object));+}++/**+ * Checks if `value` is the+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)+ *+ * @static+ * @memberOf _+ * @since 0.1.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.+ * @example+ *+ * _.isObject({});+ * // => true+ *+ * _.isObject([1, 2, 3]);+ * // => true+ *+ * _.isObject(_.noop);+ * // => true+ *+ * _.isObject(null);+ * // => false+ */+function isObject$4(value) {+ var type = typeof value;+ return value != null && (type == 'object' || type == 'function');+}++/** `Object#toString` result references. */+var asyncTag = '[object AsyncFunction]',+ funcTag = '[object Function]',+ genTag = '[object GeneratorFunction]',+ proxyTag = '[object Proxy]';++/**+ * Checks if `value` is classified as a `Function` object.+ *+ * @static+ * @memberOf _+ * @since 0.1.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.+ * @example+ *+ * _.isFunction(_);+ * // => true+ *+ * _.isFunction(/abc/);+ * // => false+ */+function isFunction$1(value) {+ if (!isObject$4(value)) {+ return false;+ }+ // The use of `Object#toString` avoids issues with the `typeof` operator+ // in Safari 9 which returns 'object' for typed arrays and other constructors.+ var tag = baseGetTag(value);+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;+}++/** Used to detect overreaching core-js shims. */+var coreJsData = root$1['__core-js_shared__'];++/** Used to detect methods masquerading as native. */+var maskSrcKey = (function() {+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');+ return uid ? ('Symbol(src)_1.' + uid) : '';+}());++/**+ * Checks if `func` has its source masked.+ *+ * @private+ * @param {Function} func The function to check.+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.+ */+function isMasked(func) {+ return !!maskSrcKey && (maskSrcKey in func);+}++/** Used for built-in method references. */+var funcProto = Function.prototype;++/** Used to resolve the decompiled source of functions. */+var funcToString = funcProto.toString;++/**+ * Converts `func` to its source code.+ *+ * @private+ * @param {Function} func The function to convert.+ * @returns {string} Returns the source code.+ */+function toSource(func) {+ if (func != null) {+ try {+ return funcToString.call(func);+ } catch (e) {}+ try {+ return (func + '');+ } catch (e) {}+ }+ return '';+}++/**+ * Used to match `RegExp`+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).+ */+var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;++/** Used to detect host constructors (Safari). */+var reIsHostCtor = /^\[object .+?Constructor\]$/;++/** Used for built-in method references. */+var funcProto$1 = Function.prototype,+ objectProto$3 = Object.prototype;++/** Used to resolve the decompiled source of functions. */+var funcToString$1 = funcProto$1.toString;++/** Used to check objects for own properties. */+var hasOwnProperty$3 = objectProto$3.hasOwnProperty;++/** Used to detect if a method is native. */+var reIsNative = RegExp('^' ++ funcToString$1.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&')+ .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'+);++/**+ * The base implementation of `_.isNative` without bad shim checks.+ *+ * @private+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a native function,+ * else `false`.+ */+function baseIsNative(value) {+ if (!isObject$4(value) || isMasked(value)) {+ return false;+ }+ var pattern = isFunction$1(value) ? reIsNative : reIsHostCtor;+ return pattern.test(toSource(value));+}++/**+ * Gets the value at `key` of `object`.+ *+ * @private+ * @param {Object} [object] The object to query.+ * @param {string} key The key of the property to get.+ * @returns {*} Returns the property value.+ */+function getValue(object, key) {+ return object == null ? undefined : object[key];+}++/**+ * Gets the native function at `key` of `object`.+ *+ * @private+ * @param {Object} object The object to query.+ * @param {string} key The key of the method to get.+ * @returns {*} Returns the function if it's native, else `undefined`.+ */+function getNative(object, key) {+ var value = getValue(object, key);+ return baseIsNative(value) ? value : undefined;+}++/* Built-in method references that are verified to be native. */+var nativeCreate = getNative(Object, 'create');++/**+ * Removes all key-value entries from the hash.+ *+ * @private+ * @name clear+ * @memberOf Hash+ */+function hashClear() {+ this.__data__ = nativeCreate ? nativeCreate(null) : {};+ this.size = 0;+}++/**+ * Removes `key` and its value from the hash.+ *+ * @private+ * @name delete+ * @memberOf Hash+ * @param {Object} hash The hash to modify.+ * @param {string} key The key of the value to remove.+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.+ */+function hashDelete(key) {+ var result = this.has(key) && delete this.__data__[key];+ this.size -= result ? 1 : 0;+ return result;+}++/** Used to stand-in for `undefined` hash values. */+var HASH_UNDEFINED = '__lodash_hash_undefined__';++/** Used for built-in method references. */+var objectProto$4 = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$4 = objectProto$4.hasOwnProperty;++/**+ * Gets the hash value for `key`.+ *+ * @private+ * @name get+ * @memberOf Hash+ * @param {string} key The key of the value to get.+ * @returns {*} Returns the entry value.+ */+function hashGet(key) {+ var data = this.__data__;+ if (nativeCreate) {+ var result = data[key];+ return result === HASH_UNDEFINED ? undefined : result;+ }+ return hasOwnProperty$4.call(data, key) ? data[key] : undefined;+}++/** Used for built-in method references. */+var objectProto$5 = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$5 = objectProto$5.hasOwnProperty;++/**+ * Checks if a hash value for `key` exists.+ *+ * @private+ * @name has+ * @memberOf Hash+ * @param {string} key The key of the entry to check.+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.+ */+function hashHas(key) {+ var data = this.__data__;+ return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$5.call(data, key);+}++/** Used to stand-in for `undefined` hash values. */+var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';++/**+ * Sets the hash `key` to `value`.+ *+ * @private+ * @name set+ * @memberOf Hash+ * @param {string} key The key of the value to set.+ * @param {*} value The value to set.+ * @returns {Object} Returns the hash instance.+ */+function hashSet(key, value) {+ var data = this.__data__;+ this.size += this.has(key) ? 0 : 1;+ data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;+ return this;+}++/**+ * Creates a hash object.+ *+ * @private+ * @constructor+ * @param {Array} [entries] The key-value pairs to cache.+ */+function Hash(entries) {+ var index = -1,+ length = entries == null ? 0 : entries.length;++ this.clear();+ while (++index < length) {+ var entry = entries[index];+ this.set(entry[0], entry[1]);+ }+}++// Add methods to `Hash`.+Hash.prototype.clear = hashClear;+Hash.prototype['delete'] = hashDelete;+Hash.prototype.get = hashGet;+Hash.prototype.has = hashHas;+Hash.prototype.set = hashSet;++/**+ * Removes all key-value entries from the list cache.+ *+ * @private+ * @name clear+ * @memberOf ListCache+ */+function listCacheClear() {+ this.__data__ = [];+ this.size = 0;+}++/**+ * Performs a+ * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)+ * comparison between two values to determine if they are equivalent.+ *+ * @static+ * @memberOf _+ * @since 4.0.0+ * @category Lang+ * @param {*} value The value to compare.+ * @param {*} other The other value to compare.+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.+ * @example+ *+ * var object = { 'a': 1 };+ * var other = { 'a': 1 };+ *+ * _.eq(object, object);+ * // => true+ *+ * _.eq(object, other);+ * // => false+ *+ * _.eq('a', 'a');+ * // => true+ *+ * _.eq('a', Object('a'));+ * // => false+ *+ * _.eq(NaN, NaN);+ * // => true+ */+function eq(value, other) {+ return value === other || (value !== value && other !== other);+}++/**+ * Gets the index at which the `key` is found in `array` of key-value pairs.+ *+ * @private+ * @param {Array} array The array to inspect.+ * @param {*} key The key to search for.+ * @returns {number} Returns the index of the matched value, else `-1`.+ */+function assocIndexOf(array, key) {+ var length = array.length;+ while (length--) {+ if (eq(array[length][0], key)) {+ return length;+ }+ }+ return -1;+}++/** Used for built-in method references. */+var arrayProto = Array.prototype;++/** Built-in value references. */+var splice = arrayProto.splice;++/**+ * Removes `key` and its value from the list cache.+ *+ * @private+ * @name delete+ * @memberOf ListCache+ * @param {string} key The key of the value to remove.+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.+ */+function listCacheDelete(key) {+ var data = this.__data__,+ index = assocIndexOf(data, key);++ if (index < 0) {+ return false;+ }+ var lastIndex = data.length - 1;+ if (index == lastIndex) {+ data.pop();+ } else {+ splice.call(data, index, 1);+ }+ --this.size;+ return true;+}++/**+ * Gets the list cache value for `key`.+ *+ * @private+ * @name get+ * @memberOf ListCache+ * @param {string} key The key of the value to get.+ * @returns {*} Returns the entry value.+ */+function listCacheGet(key) {+ var data = this.__data__,+ index = assocIndexOf(data, key);++ return index < 0 ? undefined : data[index][1];+}++/**+ * Checks if a list cache value for `key` exists.+ *+ * @private+ * @name has+ * @memberOf ListCache+ * @param {string} key The key of the entry to check.+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.+ */+function listCacheHas(key) {+ return assocIndexOf(this.__data__, key) > -1;+}++/**+ * Sets the list cache `key` to `value`.+ *+ * @private+ * @name set+ * @memberOf ListCache+ * @param {string} key The key of the value to set.+ * @param {*} value The value to set.+ * @returns {Object} Returns the list cache instance.+ */+function listCacheSet(key, value) {+ var data = this.__data__,+ index = assocIndexOf(data, key);++ if (index < 0) {+ ++this.size;+ data.push([key, value]);+ } else {+ data[index][1] = value;+ }+ return this;+}++/**+ * Creates an list cache object.+ *+ * @private+ * @constructor+ * @param {Array} [entries] The key-value pairs to cache.+ */+function ListCache(entries) {+ var index = -1,+ length = entries == null ? 0 : entries.length;++ this.clear();+ while (++index < length) {+ var entry = entries[index];+ this.set(entry[0], entry[1]);+ }+}++// Add methods to `ListCache`.+ListCache.prototype.clear = listCacheClear;+ListCache.prototype['delete'] = listCacheDelete;+ListCache.prototype.get = listCacheGet;+ListCache.prototype.has = listCacheHas;+ListCache.prototype.set = listCacheSet;++/* Built-in method references that are verified to be native. */+var Map$1 = getNative(root$1, 'Map');++/**+ * Removes all key-value entries from the map.+ *+ * @private+ * @name clear+ * @memberOf MapCache+ */+function mapCacheClear() {+ this.size = 0;+ this.__data__ = {+ 'hash': new Hash,+ 'map': new (Map$1 || ListCache),+ 'string': new Hash+ };+}++/**+ * Checks if `value` is suitable for use as unique object key.+ *+ * @private+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is suitable, else `false`.+ */+function isKeyable(value) {+ var type = typeof value;+ return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')+ ? (value !== '__proto__')+ : (value === null);+}++/**+ * Gets the data for `map`.+ *+ * @private+ * @param {Object} map The map to query.+ * @param {string} key The reference key.+ * @returns {*} Returns the map data.+ */+function getMapData(map, key) {+ var data = map.__data__;+ return isKeyable(key)+ ? data[typeof key == 'string' ? 'string' : 'hash']+ : data.map;+}++/**+ * Removes `key` and its value from the map.+ *+ * @private+ * @name delete+ * @memberOf MapCache+ * @param {string} key The key of the value to remove.+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.+ */+function mapCacheDelete(key) {+ var result = getMapData(this, key)['delete'](key);+ this.size -= result ? 1 : 0;+ return result;+}++/**+ * Gets the map value for `key`.+ *+ * @private+ * @name get+ * @memberOf MapCache+ * @param {string} key The key of the value to get.+ * @returns {*} Returns the entry value.+ */+function mapCacheGet(key) {+ return getMapData(this, key).get(key);+}++/**+ * Checks if a map value for `key` exists.+ *+ * @private+ * @name has+ * @memberOf MapCache+ * @param {string} key The key of the entry to check.+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.+ */+function mapCacheHas(key) {+ return getMapData(this, key).has(key);+}++/**+ * Sets the map `key` to `value`.+ *+ * @private+ * @name set+ * @memberOf MapCache+ * @param {string} key The key of the value to set.+ * @param {*} value The value to set.+ * @returns {Object} Returns the map cache instance.+ */+function mapCacheSet(key, value) {+ var data = getMapData(this, key),+ size = data.size;++ data.set(key, value);+ this.size += data.size == size ? 0 : 1;+ return this;+}++/**+ * Creates a map cache object to store key-value pairs.+ *+ * @private+ * @constructor+ * @param {Array} [entries] The key-value pairs to cache.+ */+function MapCache(entries) {+ var index = -1,+ length = entries == null ? 0 : entries.length;++ this.clear();+ while (++index < length) {+ var entry = entries[index];+ this.set(entry[0], entry[1]);+ }+}++// Add methods to `MapCache`.+MapCache.prototype.clear = mapCacheClear;+MapCache.prototype['delete'] = mapCacheDelete;+MapCache.prototype.get = mapCacheGet;+MapCache.prototype.has = mapCacheHas;+MapCache.prototype.set = mapCacheSet;++/** Error message constants. */+var FUNC_ERROR_TEXT = 'Expected a function';++/**+ * Creates a function that memoizes the result of `func`. If `resolver` is+ * provided, it determines the cache key for storing the result based on the+ * arguments provided to the memoized function. By default, the first argument+ * provided to the memoized function is used as the map cache key. The `func`+ * is invoked with the `this` binding of the memoized function.+ *+ * **Note:** The cache is exposed as the `cache` property on the memoized+ * function. Its creation may be customized by replacing the `_.memoize.Cache`+ * constructor with one whose instances implement the+ * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)+ * method interface of `clear`, `delete`, `get`, `has`, and `set`.+ *+ * @static+ * @memberOf _+ * @since 0.1.0+ * @category Function+ * @param {Function} func The function to have its output memoized.+ * @param {Function} [resolver] The function to resolve the cache key.+ * @returns {Function} Returns the new memoized function.+ * @example+ *+ * var object = { 'a': 1, 'b': 2 };+ * var other = { 'c': 3, 'd': 4 };+ *+ * var values = _.memoize(_.values);+ * values(object);+ * // => [1, 2]+ *+ * values(other);+ * // => [3, 4]+ *+ * object.a = 2;+ * values(object);+ * // => [1, 2]+ *+ * // Modify the result cache.+ * values.cache.set(object, ['a', 'b']);+ * values(object);+ * // => ['a', 'b']+ *+ * // Replace `_.memoize.Cache`.+ * _.memoize.Cache = WeakMap;+ */+function memoize(func, resolver) {+ if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {+ throw new TypeError(FUNC_ERROR_TEXT);+ }+ var memoized = function() {+ var args = arguments,+ key = resolver ? resolver.apply(this, args) : args[0],+ cache = memoized.cache;++ if (cache.has(key)) {+ return cache.get(key);+ }+ var result = func.apply(this, args);+ memoized.cache = cache.set(key, result) || cache;+ return result;+ };+ memoized.cache = new (memoize.Cache || MapCache);+ return memoized;+}++// Expose `MapCache`.+memoize.Cache = MapCache;++/** Used as the maximum memoize cache size. */+var MAX_MEMOIZE_SIZE = 500;++/**+ * A specialized version of `_.memoize` which clears the memoized function's+ * cache when it exceeds `MAX_MEMOIZE_SIZE`.+ *+ * @private+ * @param {Function} func The function to have its output memoized.+ * @returns {Function} Returns the new memoized function.+ */+function memoizeCapped(func) {+ var result = memoize(func, function(key) {+ if (cache.size === MAX_MEMOIZE_SIZE) {+ cache.clear();+ }+ return key;+ });++ var cache = result.cache;+ return result;+}++/** Used to match property names within property paths. */+var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;++/** Used to match backslashes in property paths. */+var reEscapeChar = /\\(\\)?/g;++/**+ * Converts `string` to a property path array.+ *+ * @private+ * @param {string} string The string to convert.+ * @returns {Array} Returns the property path array.+ */+var stringToPath = memoizeCapped(function(string) {+ var result = [];+ if (string.charCodeAt(0) === 46 /* . */) {+ result.push('');+ }+ string.replace(rePropName, function(match, number, quote, subString) {+ result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));+ });+ return result;+});++/**+ * A specialized version of `_.map` for arrays without support for iteratee+ * shorthands.+ *+ * @private+ * @param {Array} [array] The array to iterate over.+ * @param {Function} iteratee The function invoked per iteration.+ * @returns {Array} Returns the new mapped array.+ */+function arrayMap(array, iteratee) {+ var index = -1,+ length = array == null ? 0 : array.length,+ result = Array(length);++ while (++index < length) {+ result[index] = iteratee(array[index], index, array);+ }+ return result;+}++/** Used as references for various `Number` constants. */+var INFINITY = 1 / 0;++/** Used to convert symbols to primitives and strings. */+var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,+ symbolToString = symbolProto ? symbolProto.toString : undefined;++/**+ * The base implementation of `_.toString` which doesn't convert nullish+ * values to empty strings.+ *+ * @private+ * @param {*} value The value to process.+ * @returns {string} Returns the string.+ */+function baseToString(value) {+ // Exit early for strings to avoid a performance hit in some environments.+ if (typeof value == 'string') {+ return value;+ }+ if (isArray(value)) {+ // Recursively convert values (susceptible to call stack limits).+ return arrayMap(value, baseToString) + '';+ }+ if (isSymbol(value)) {+ return symbolToString ? symbolToString.call(value) : '';+ }+ var result = (value + '');+ return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;+}++/**+ * Converts `value` to a string. An empty string is returned for `null`+ * and `undefined` values. The sign of `-0` is preserved.+ *+ * @static+ * @memberOf _+ * @since 4.0.0+ * @category Lang+ * @param {*} value The value to convert.+ * @returns {string} Returns the converted string.+ * @example+ *+ * _.toString(null);+ * // => ''+ *+ * _.toString(-0);+ * // => '-0'+ *+ * _.toString([1, 2, 3]);+ * // => '1,2,3'+ */+function toString(value) {+ return value == null ? '' : baseToString(value);+}++/**+ * Casts `value` to a path array if it's not one.+ *+ * @private+ * @param {*} value The value to inspect.+ * @param {Object} [object] The object to query keys on.+ * @returns {Array} Returns the cast property path array.+ */+function castPath(value, object) {+ if (isArray(value)) {+ return value;+ }+ return isKey(value, object) ? [value] : stringToPath(toString(value));+}++/** `Object#toString` result references. */+var argsTag = '[object Arguments]';++/**+ * The base implementation of `_.isArguments`.+ *+ * @private+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,+ */+function baseIsArguments(value) {+ return isObjectLike$1(value) && baseGetTag(value) == argsTag;+}++/** Used for built-in method references. */+var objectProto$6 = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$6 = objectProto$6.hasOwnProperty;++/** Built-in value references. */+var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;++/**+ * Checks if `value` is likely an `arguments` object.+ *+ * @static+ * @memberOf _+ * @since 0.1.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,+ * else `false`.+ * @example+ *+ * _.isArguments(function() { return arguments; }());+ * // => true+ *+ * _.isArguments([1, 2, 3]);+ * // => false+ */+var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {+ return isObjectLike$1(value) && hasOwnProperty$6.call(value, 'callee') &&+ !propertyIsEnumerable.call(value, 'callee');+};++/** Used as references for various `Number` constants. */+var MAX_SAFE_INTEGER = 9007199254740991;++/** Used to detect unsigned integer values. */+var reIsUint = /^(?:0|[1-9]\d*)$/;++/**+ * Checks if `value` is a valid array-like index.+ *+ * @private+ * @param {*} value The value to check.+ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.+ * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.+ */+function isIndex(value, length) {+ var type = typeof value;+ length = length == null ? MAX_SAFE_INTEGER : length;++ return !!length &&+ (type == 'number' ||+ (type != 'symbol' && reIsUint.test(value))) &&+ (value > -1 && value % 1 == 0 && value < length);+}++/** Used as references for various `Number` constants. */+var MAX_SAFE_INTEGER$1 = 9007199254740991;++/**+ * Checks if `value` is a valid array-like length.+ *+ * **Note:** This method is loosely based on+ * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).+ *+ * @static+ * @memberOf _+ * @since 4.0.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.+ * @example+ *+ * _.isLength(3);+ * // => true+ *+ * _.isLength(Number.MIN_VALUE);+ * // => false+ *+ * _.isLength(Infinity);+ * // => false+ *+ * _.isLength('3');+ * // => false+ */+function isLength(value) {+ return typeof value == 'number' &&+ value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;+}++/** Used as references for various `Number` constants. */+var INFINITY$1 = 1 / 0;++/**+ * Converts `value` to a string key if it's not a string or symbol.+ *+ * @private+ * @param {*} value The value to inspect.+ * @returns {string|symbol} Returns the key.+ */+function toKey(value) {+ if (typeof value == 'string' || isSymbol(value)) {+ return value;+ }+ var result = (value + '');+ return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;+}++/**+ * Checks if `path` exists on `object`.+ *+ * @private+ * @param {Object} object The object to query.+ * @param {Array|string} path The path to check.+ * @param {Function} hasFunc The function to check properties.+ * @returns {boolean} Returns `true` if `path` exists, else `false`.+ */+function hasPath(object, path, hasFunc) {+ path = castPath(path, object);++ var index = -1,+ length = path.length,+ result = false;++ while (++index < length) {+ var key = toKey(path[index]);+ if (!(result = object != null && hasFunc(object, key))) {+ break;+ }+ object = object[key];+ }+ if (result || ++index != length) {+ return result;+ }+ length = object == null ? 0 : object.length;+ return !!length && isLength(length) && isIndex(key, length) &&+ (isArray(object) || isArguments(object));+}++/**+ * Checks if `path` is a direct property of `object`.+ *+ * @static+ * @since 0.1.0+ * @memberOf _+ * @category Object+ * @param {Object} object The object to query.+ * @param {Array|string} path The path to check.+ * @returns {boolean} Returns `true` if `path` exists, else `false`.+ * @example+ *+ * var object = { 'a': { 'b': 2 } };+ * var other = _.create({ 'a': _.create({ 'b': 2 }) });+ *+ * _.has(object, 'a');+ * // => true+ *+ * _.has(object, 'a.b');+ * // => true+ *+ * _.has(object, ['a', 'b']);+ * // => true+ *+ * _.has(other, 'a');+ * // => false+ */+function has(object, path) {+ return object != null && hasPath(object, path, baseHas);+}++/**+ * Removes all key-value entries from the stack.+ *+ * @private+ * @name clear+ * @memberOf Stack+ */+function stackClear() {+ this.__data__ = new ListCache;+ this.size = 0;+}++/**+ * Removes `key` and its value from the stack.+ *+ * @private+ * @name delete+ * @memberOf Stack+ * @param {string} key The key of the value to remove.+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.+ */+function stackDelete(key) {+ var data = this.__data__,+ result = data['delete'](key);++ this.size = data.size;+ return result;+}++/**+ * Gets the stack value for `key`.+ *+ * @private+ * @name get+ * @memberOf Stack+ * @param {string} key The key of the value to get.+ * @returns {*} Returns the entry value.+ */+function stackGet(key) {+ return this.__data__.get(key);+}++/**+ * Checks if a stack value for `key` exists.+ *+ * @private+ * @name has+ * @memberOf Stack+ * @param {string} key The key of the entry to check.+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.+ */+function stackHas(key) {+ return this.__data__.has(key);+}++/** Used as the size to enable large array optimizations. */+var LARGE_ARRAY_SIZE = 200;++/**+ * Sets the stack `key` to `value`.+ *+ * @private+ * @name set+ * @memberOf Stack+ * @param {string} key The key of the value to set.+ * @param {*} value The value to set.+ * @returns {Object} Returns the stack cache instance.+ */+function stackSet(key, value) {+ var data = this.__data__;+ if (data instanceof ListCache) {+ var pairs = data.__data__;+ if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE - 1)) {+ pairs.push([key, value]);+ this.size = ++data.size;+ return this;+ }+ data = this.__data__ = new MapCache(pairs);+ }+ data.set(key, value);+ this.size = data.size;+ return this;+}++/**+ * Creates a stack cache object to store key-value pairs.+ *+ * @private+ * @constructor+ * @param {Array} [entries] The key-value pairs to cache.+ */+function Stack(entries) {+ var data = this.__data__ = new ListCache(entries);+ this.size = data.size;+}++// Add methods to `Stack`.+Stack.prototype.clear = stackClear;+Stack.prototype['delete'] = stackDelete;+Stack.prototype.get = stackGet;+Stack.prototype.has = stackHas;+Stack.prototype.set = stackSet;++/**+ * A specialized version of `_.forEach` for arrays without support for+ * iteratee shorthands.+ *+ * @private+ * @param {Array} [array] The array to iterate over.+ * @param {Function} iteratee The function invoked per iteration.+ * @returns {Array} Returns `array`.+ */+function arrayEach(array, iteratee) {+ var index = -1,+ length = array == null ? 0 : array.length;++ while (++index < length) {+ if (iteratee(array[index], index, array) === false) {+ break;+ }+ }+ return array;+}++var defineProperty = (function() {+ try {+ var func = getNative(Object, 'defineProperty');+ func({}, '', {});+ return func;+ } catch (e) {}+}());++/**+ * The base implementation of `assignValue` and `assignMergeValue` without+ * value checks.+ *+ * @private+ * @param {Object} object The object to modify.+ * @param {string} key The key of the property to assign.+ * @param {*} value The value to assign.+ */+function baseAssignValue(object, key, value) {+ if (key == '__proto__' && defineProperty) {+ defineProperty(object, key, {+ 'configurable': true,+ 'enumerable': true,+ 'value': value,+ 'writable': true+ });+ } else {+ object[key] = value;+ }+}++/** Used for built-in method references. */+var objectProto$7 = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$7 = objectProto$7.hasOwnProperty;++/**+ * Assigns `value` to `key` of `object` if the existing value is not equivalent+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)+ * for equality comparisons.+ *+ * @private+ * @param {Object} object The object to modify.+ * @param {string} key The key of the property to assign.+ * @param {*} value The value to assign.+ */+function assignValue(object, key, value) {+ var objValue = object[key];+ if (!(hasOwnProperty$7.call(object, key) && eq(objValue, value)) ||+ (value === undefined && !(key in object))) {+ baseAssignValue(object, key, value);+ }+}++/**+ * Copies properties of `source` to `object`.+ *+ * @private+ * @param {Object} source The object to copy properties from.+ * @param {Array} props The property identifiers to copy.+ * @param {Object} [object={}] The object to copy properties to.+ * @param {Function} [customizer] The function to customize copied values.+ * @returns {Object} Returns `object`.+ */+function copyObject(source, props, object, customizer) {+ var isNew = !object;+ object || (object = {});++ var index = -1,+ length = props.length;++ while (++index < length) {+ var key = props[index];++ var newValue = customizer+ ? customizer(object[key], source[key], key, object, source)+ : undefined;++ if (newValue === undefined) {+ newValue = source[key];+ }+ if (isNew) {+ baseAssignValue(object, key, newValue);+ } else {+ assignValue(object, key, newValue);+ }+ }+ return object;+}++/**+ * The base implementation of `_.times` without support for iteratee shorthands+ * or max array length checks.+ *+ * @private+ * @param {number} n The number of times to invoke `iteratee`.+ * @param {Function} iteratee The function invoked per iteration.+ * @returns {Array} Returns the array of results.+ */+function baseTimes(n, iteratee) {+ var index = -1,+ result = Array(n);++ while (++index < n) {+ result[index] = iteratee(index);+ }+ return result;+}++/**+ * This method returns `false`.+ *+ * @static+ * @memberOf _+ * @since 4.13.0+ * @category Util+ * @returns {boolean} Returns `false`.+ * @example+ *+ * _.times(2, _.stubFalse);+ * // => [false, false]+ */+function stubFalse() {+ return false;+}++/** Detect free variable `exports`. */+var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;++/** Detect free variable `module`. */+var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;++/** Detect the popular CommonJS extension `module.exports`. */+var moduleExports = freeModule && freeModule.exports === freeExports;++/** Built-in value references. */+var Buffer$1 = moduleExports ? root$1.Buffer : undefined;++/* Built-in method references for those with the same name as other `lodash` methods. */+var nativeIsBuffer = Buffer$1 ? Buffer$1.isBuffer : undefined;++/**+ * Checks if `value` is a buffer.+ *+ * @static+ * @memberOf _+ * @since 4.3.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.+ * @example+ *+ * _.isBuffer(new Buffer(2));+ * // => true+ *+ * _.isBuffer(new Uint8Array(2));+ * // => false+ */+var isBuffer = nativeIsBuffer || stubFalse;++/** `Object#toString` result references. */+var argsTag$1 = '[object Arguments]',+ arrayTag = '[object Array]',+ boolTag = '[object Boolean]',+ dateTag = '[object Date]',+ errorTag = '[object Error]',+ funcTag$1 = '[object Function]',+ mapTag = '[object Map]',+ numberTag = '[object Number]',+ objectTag = '[object Object]',+ regexpTag = '[object RegExp]',+ setTag = '[object Set]',+ stringTag = '[object String]',+ weakMapTag = '[object WeakMap]';++var arrayBufferTag = '[object ArrayBuffer]',+ dataViewTag = '[object DataView]',+ float32Tag = '[object Float32Array]',+ float64Tag = '[object Float64Array]',+ int8Tag = '[object Int8Array]',+ int16Tag = '[object Int16Array]',+ int32Tag = '[object Int32Array]',+ uint8Tag = '[object Uint8Array]',+ uint8ClampedTag = '[object Uint8ClampedArray]',+ uint16Tag = '[object Uint16Array]',+ uint32Tag = '[object Uint32Array]';++/** Used to identify `toStringTag` values of typed arrays. */+var typedArrayTags = {};+typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =+typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =+typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =+typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =+typedArrayTags[uint32Tag] = true;+typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =+typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =+typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =+typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =+typedArrayTags[mapTag] = typedArrayTags[numberTag] =+typedArrayTags[objectTag] = typedArrayTags[regexpTag] =+typedArrayTags[setTag] = typedArrayTags[stringTag] =+typedArrayTags[weakMapTag] = false;++/**+ * The base implementation of `_.isTypedArray` without Node.js optimizations.+ *+ * @private+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.+ */+function baseIsTypedArray(value) {+ return isObjectLike$1(value) &&+ isLength(value.length) && !!typedArrayTags[baseGetTag(value)];+}++/**+ * The base implementation of `_.unary` without support for storing metadata.+ *+ * @private+ * @param {Function} func The function to cap arguments for.+ * @returns {Function} Returns the new capped function.+ */+function baseUnary(func) {+ return function(value) {+ return func(value);+ };+}++/** Detect free variable `exports`. */+var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;++/** Detect free variable `module`. */+var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;++/** Detect the popular CommonJS extension `module.exports`. */+var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;++/** Detect free variable `process` from Node.js. */+var freeProcess = moduleExports$1 && freeGlobal.process;++/** Used to access faster Node.js helpers. */+var nodeUtil = (function() {+ try {+ // Use `util.types` for Node.js 10+.+ var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types;++ if (types) {+ return types;+ }++ // Legacy `process.binding('util')` for Node.js < 10.+ return freeProcess && freeProcess.binding && freeProcess.binding('util');+ } catch (e) {}+}());++/* Node.js helper references. */+var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;++/**+ * Checks if `value` is classified as a typed array.+ *+ * @static+ * @memberOf _+ * @since 3.0.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.+ * @example+ *+ * _.isTypedArray(new Uint8Array);+ * // => true+ *+ * _.isTypedArray([]);+ * // => false+ */+var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;++/** Used for built-in method references. */+var objectProto$8 = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$8 = objectProto$8.hasOwnProperty;++/**+ * Creates an array of the enumerable property names of the array-like `value`.+ *+ * @private+ * @param {*} value The value to query.+ * @param {boolean} inherited Specify returning inherited property names.+ * @returns {Array} Returns the array of property names.+ */+function arrayLikeKeys(value, inherited) {+ var isArr = isArray(value),+ isArg = !isArr && isArguments(value),+ isBuff = !isArr && !isArg && isBuffer(value),+ isType = !isArr && !isArg && !isBuff && isTypedArray(value),+ skipIndexes = isArr || isArg || isBuff || isType,+ result = skipIndexes ? baseTimes(value.length, String) : [],+ length = result.length;++ for (var key in value) {+ if ((inherited || hasOwnProperty$8.call(value, key)) &&+ !(skipIndexes && (+ // Safari 9 has enumerable `arguments.length` in strict mode.+ key == 'length' ||+ // Node.js 0.10 has enumerable non-index properties on buffers.+ (isBuff && (key == 'offset' || key == 'parent')) ||+ // PhantomJS 2 has enumerable non-index properties on typed arrays.+ (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||+ // Skip index properties.+ isIndex(key, length)+ ))) {+ result.push(key);+ }+ }+ return result;+}++/** Used for built-in method references. */+var objectProto$9 = Object.prototype;++/**+ * Checks if `value` is likely a prototype object.+ *+ * @private+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.+ */+function isPrototype(value) {+ var Ctor = value && value.constructor,+ proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9;++ return value === proto;+}++/**+ * Creates a unary function that invokes `func` with its argument transformed.+ *+ * @private+ * @param {Function} func The function to wrap.+ * @param {Function} transform The argument transform.+ * @returns {Function} Returns the new function.+ */+function overArg(func, transform) {+ return function(arg) {+ return func(transform(arg));+ };+}++/* Built-in method references for those with the same name as other `lodash` methods. */+var nativeKeys = overArg(Object.keys, Object);++/** Used for built-in method references. */+var objectProto$a = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$9 = objectProto$a.hasOwnProperty;++/**+ * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.+ *+ * @private+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of property names.+ */+function baseKeys(object) {+ if (!isPrototype(object)) {+ return nativeKeys(object);+ }+ var result = [];+ for (var key in Object(object)) {+ if (hasOwnProperty$9.call(object, key) && key != 'constructor') {+ result.push(key);+ }+ }+ return result;+}++/**+ * Checks if `value` is array-like. A value is considered array-like if it's+ * not a function and has a `value.length` that's an integer greater than or+ * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.+ *+ * @static+ * @memberOf _+ * @since 4.0.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.+ * @example+ *+ * _.isArrayLike([1, 2, 3]);+ * // => true+ *+ * _.isArrayLike(document.body.children);+ * // => true+ *+ * _.isArrayLike('abc');+ * // => true+ *+ * _.isArrayLike(_.noop);+ * // => false+ */+function isArrayLike$2(value) {+ return value != null && isLength(value.length) && !isFunction$1(value);+}++/**+ * Creates an array of the own enumerable property names of `object`.+ *+ * **Note:** Non-object values are coerced to objects. See the+ * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)+ * for more details.+ *+ * @static+ * @since 0.1.0+ * @memberOf _+ * @category Object+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of property names.+ * @example+ *+ * function Foo() {+ * this.a = 1;+ * this.b = 2;+ * }+ *+ * Foo.prototype.c = 3;+ *+ * _.keys(new Foo);+ * // => ['a', 'b'] (iteration order is not guaranteed)+ *+ * _.keys('hi');+ * // => ['0', '1']+ */+function keys(object) {+ return isArrayLike$2(object) ? arrayLikeKeys(object) : baseKeys(object);+}++/**+ * The base implementation of `_.assign` without support for multiple sources+ * or `customizer` functions.+ *+ * @private+ * @param {Object} object The destination object.+ * @param {Object} source The source object.+ * @returns {Object} Returns `object`.+ */+function baseAssign(object, source) {+ return object && copyObject(source, keys(source), object);+}++/**+ * This function is like+ * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)+ * except that it includes inherited enumerable properties.+ *+ * @private+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of property names.+ */+function nativeKeysIn(object) {+ var result = [];+ if (object != null) {+ for (var key in Object(object)) {+ result.push(key);+ }+ }+ return result;+}++/** Used for built-in method references. */+var objectProto$b = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$a = objectProto$b.hasOwnProperty;++/**+ * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.+ *+ * @private+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of property names.+ */+function baseKeysIn(object) {+ if (!isObject$4(object)) {+ return nativeKeysIn(object);+ }+ var isProto = isPrototype(object),+ result = [];++ for (var key in object) {+ if (!(key == 'constructor' && (isProto || !hasOwnProperty$a.call(object, key)))) {+ result.push(key);+ }+ }+ return result;+}++/**+ * Creates an array of the own and inherited enumerable property names of `object`.+ *+ * **Note:** Non-object values are coerced to objects.+ *+ * @static+ * @memberOf _+ * @since 3.0.0+ * @category Object+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of property names.+ * @example+ *+ * function Foo() {+ * this.a = 1;+ * this.b = 2;+ * }+ *+ * Foo.prototype.c = 3;+ *+ * _.keysIn(new Foo);+ * // => ['a', 'b', 'c'] (iteration order is not guaranteed)+ */+function keysIn$1(object) {+ return isArrayLike$2(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);+}++/**+ * The base implementation of `_.assignIn` without support for multiple sources+ * or `customizer` functions.+ *+ * @private+ * @param {Object} object The destination object.+ * @param {Object} source The source object.+ * @returns {Object} Returns `object`.+ */+function baseAssignIn(object, source) {+ return object && copyObject(source, keysIn$1(source), object);+}++/** Detect free variable `exports`. */+var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports;++/** Detect free variable `module`. */+var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module;++/** Detect the popular CommonJS extension `module.exports`. */+var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2;++/** Built-in value references. */+var Buffer$2 = moduleExports$2 ? root$1.Buffer : undefined,+ allocUnsafe = Buffer$2 ? Buffer$2.allocUnsafe : undefined;++/**+ * Creates a clone of `buffer`.+ *+ * @private+ * @param {Buffer} buffer The buffer to clone.+ * @param {boolean} [isDeep] Specify a deep clone.+ * @returns {Buffer} Returns the cloned buffer.+ */+function cloneBuffer(buffer, isDeep) {+ if (isDeep) {+ return buffer.slice();+ }+ var length = buffer.length,+ result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);++ buffer.copy(result);+ return result;+}++/**+ * Copies the values of `source` to `array`.+ *+ * @private+ * @param {Array} source The array to copy values from.+ * @param {Array} [array=[]] The array to copy values to.+ * @returns {Array} Returns `array`.+ */+function copyArray(source, array) {+ var index = -1,+ length = source.length;++ array || (array = Array(length));+ while (++index < length) {+ array[index] = source[index];+ }+ return array;+}++/**+ * A specialized version of `_.filter` for arrays without support for+ * iteratee shorthands.+ *+ * @private+ * @param {Array} [array] The array to iterate over.+ * @param {Function} predicate The function invoked per iteration.+ * @returns {Array} Returns the new filtered array.+ */+function arrayFilter(array, predicate) {+ var index = -1,+ length = array == null ? 0 : array.length,+ resIndex = 0,+ result = [];++ while (++index < length) {+ var value = array[index];+ if (predicate(value, index, array)) {+ result[resIndex++] = value;+ }+ }+ return result;+}++/**+ * This method returns a new empty array.+ *+ * @static+ * @memberOf _+ * @since 4.13.0+ * @category Util+ * @returns {Array} Returns the new empty array.+ * @example+ *+ * var arrays = _.times(2, _.stubArray);+ *+ * console.log(arrays);+ * // => [[], []]+ *+ * console.log(arrays[0] === arrays[1]);+ * // => false+ */+function stubArray() {+ return [];+}++/** Used for built-in method references. */+var objectProto$c = Object.prototype;++/** Built-in value references. */+var propertyIsEnumerable$1 = objectProto$c.propertyIsEnumerable;++/* Built-in method references for those with the same name as other `lodash` methods. */+var nativeGetSymbols = Object.getOwnPropertySymbols;++/**+ * Creates an array of the own enumerable symbols of `object`.+ *+ * @private+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of symbols.+ */+var getSymbols = !nativeGetSymbols ? stubArray : function(object) {+ if (object == null) {+ return [];+ }+ object = Object(object);+ return arrayFilter(nativeGetSymbols(object), function(symbol) {+ return propertyIsEnumerable$1.call(object, symbol);+ });+};++/**+ * Copies own symbols of `source` to `object`.+ *+ * @private+ * @param {Object} source The object to copy symbols from.+ * @param {Object} [object={}] The object to copy symbols to.+ * @returns {Object} Returns `object`.+ */+function copySymbols(source, object) {+ return copyObject(source, getSymbols(source), object);+}++/**+ * Appends the elements of `values` to `array`.+ *+ * @private+ * @param {Array} array The array to modify.+ * @param {Array} values The values to append.+ * @returns {Array} Returns `array`.+ */+function arrayPush(array, values) {+ var index = -1,+ length = values.length,+ offset = array.length;++ while (++index < length) {+ array[offset + index] = values[index];+ }+ return array;+}++/** Built-in value references. */+var getPrototype = overArg(Object.getPrototypeOf, Object);++/* Built-in method references for those with the same name as other `lodash` methods. */+var nativeGetSymbols$1 = Object.getOwnPropertySymbols;++/**+ * Creates an array of the own and inherited enumerable symbols of `object`.+ *+ * @private+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of symbols.+ */+var getSymbolsIn = !nativeGetSymbols$1 ? stubArray : function(object) {+ var result = [];+ while (object) {+ arrayPush(result, getSymbols(object));+ object = getPrototype(object);+ }+ return result;+};++/**+ * Copies own and inherited symbols of `source` to `object`.+ *+ * @private+ * @param {Object} source The object to copy symbols from.+ * @param {Object} [object={}] The object to copy symbols to.+ * @returns {Object} Returns `object`.+ */+function copySymbolsIn(source, object) {+ return copyObject(source, getSymbolsIn(source), object);+}++/**+ * The base implementation of `getAllKeys` and `getAllKeysIn` which uses+ * `keysFunc` and `symbolsFunc` to get the enumerable property names and+ * symbols of `object`.+ *+ * @private+ * @param {Object} object The object to query.+ * @param {Function} keysFunc The function to get the keys of `object`.+ * @param {Function} symbolsFunc The function to get the symbols of `object`.+ * @returns {Array} Returns the array of property names and symbols.+ */+function baseGetAllKeys(object, keysFunc, symbolsFunc) {+ var result = keysFunc(object);+ return isArray(object) ? result : arrayPush(result, symbolsFunc(object));+}++/**+ * Creates an array of own enumerable property names and symbols of `object`.+ *+ * @private+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of property names and symbols.+ */+function getAllKeys(object) {+ return baseGetAllKeys(object, keys, getSymbols);+}++/**+ * Creates an array of own and inherited enumerable property names and+ * symbols of `object`.+ *+ * @private+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of property names and symbols.+ */+function getAllKeysIn(object) {+ return baseGetAllKeys(object, keysIn$1, getSymbolsIn);+}++/* Built-in method references that are verified to be native. */+var DataView = getNative(root$1, 'DataView');++/* Built-in method references that are verified to be native. */+var Promise$1 = getNative(root$1, 'Promise');++/* Built-in method references that are verified to be native. */+var Set$1 = getNative(root$1, 'Set');++/* Built-in method references that are verified to be native. */+var WeakMap$1 = getNative(root$1, 'WeakMap');++/** `Object#toString` result references. */+var mapTag$1 = '[object Map]',+ objectTag$1 = '[object Object]',+ promiseTag = '[object Promise]',+ setTag$1 = '[object Set]',+ weakMapTag$1 = '[object WeakMap]';++var dataViewTag$1 = '[object DataView]';++/** Used to detect maps, sets, and weakmaps. */+var dataViewCtorString = toSource(DataView),+ mapCtorString = toSource(Map$1),+ promiseCtorString = toSource(Promise$1),+ setCtorString = toSource(Set$1),+ weakMapCtorString = toSource(WeakMap$1);++/**+ * Gets the `toStringTag` of `value`.+ *+ * @private+ * @param {*} value The value to query.+ * @returns {string} Returns the `toStringTag`.+ */+var getTag = baseGetTag;++// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.+if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$1) ||+ (Map$1 && getTag(new Map$1) != mapTag$1) ||+ (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) ||+ (Set$1 && getTag(new Set$1) != setTag$1) ||+ (WeakMap$1 && getTag(new WeakMap$1) != weakMapTag$1)) {+ getTag = function(value) {+ var result = baseGetTag(value),+ Ctor = result == objectTag$1 ? value.constructor : undefined,+ ctorString = Ctor ? toSource(Ctor) : '';++ if (ctorString) {+ switch (ctorString) {+ case dataViewCtorString: return dataViewTag$1;+ case mapCtorString: return mapTag$1;+ case promiseCtorString: return promiseTag;+ case setCtorString: return setTag$1;+ case weakMapCtorString: return weakMapTag$1;+ }+ }+ return result;+ };+}++var getTag$1 = getTag;++/** Used for built-in method references. */+var objectProto$d = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$b = objectProto$d.hasOwnProperty;++/**+ * Initializes an array clone.+ *+ * @private+ * @param {Array} array The array to clone.+ * @returns {Array} Returns the initialized clone.+ */+function initCloneArray(array) {+ var length = array.length,+ result = new array.constructor(length);++ // Add properties assigned by `RegExp#exec`.+ if (length && typeof array[0] == 'string' && hasOwnProperty$b.call(array, 'index')) {+ result.index = array.index;+ result.input = array.input;+ }+ return result;+}++/** Built-in value references. */+var Uint8Array = root$1.Uint8Array;++/**+ * Creates a clone of `arrayBuffer`.+ *+ * @private+ * @param {ArrayBuffer} arrayBuffer The array buffer to clone.+ * @returns {ArrayBuffer} Returns the cloned array buffer.+ */+function cloneArrayBuffer(arrayBuffer) {+ var result = new arrayBuffer.constructor(arrayBuffer.byteLength);+ new Uint8Array(result).set(new Uint8Array(arrayBuffer));+ return result;+}++/**+ * Creates a clone of `dataView`.+ *+ * @private+ * @param {Object} dataView The data view to clone.+ * @param {boolean} [isDeep] Specify a deep clone.+ * @returns {Object} Returns the cloned data view.+ */+function cloneDataView(dataView, isDeep) {+ var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;+ return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);+}++/** Used to match `RegExp` flags from their coerced string values. */+var reFlags = /\w*$/;++/**+ * Creates a clone of `regexp`.+ *+ * @private+ * @param {Object} regexp The regexp to clone.+ * @returns {Object} Returns the cloned regexp.+ */+function cloneRegExp(regexp) {+ var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));+ result.lastIndex = regexp.lastIndex;+ return result;+}++/** Used to convert symbols to primitives and strings. */+var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined,+ symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;++/**+ * Creates a clone of the `symbol` object.+ *+ * @private+ * @param {Object} symbol The symbol object to clone.+ * @returns {Object} Returns the cloned symbol object.+ */+function cloneSymbol(symbol) {+ return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};+}++/**+ * Creates a clone of `typedArray`.+ *+ * @private+ * @param {Object} typedArray The typed array to clone.+ * @param {boolean} [isDeep] Specify a deep clone.+ * @returns {Object} Returns the cloned typed array.+ */+function cloneTypedArray(typedArray, isDeep) {+ var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;+ return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);+}++/** `Object#toString` result references. */+var boolTag$1 = '[object Boolean]',+ dateTag$1 = '[object Date]',+ mapTag$2 = '[object Map]',+ numberTag$1 = '[object Number]',+ regexpTag$1 = '[object RegExp]',+ setTag$2 = '[object Set]',+ stringTag$1 = '[object String]',+ symbolTag$1 = '[object Symbol]';++var arrayBufferTag$1 = '[object ArrayBuffer]',+ dataViewTag$2 = '[object DataView]',+ float32Tag$1 = '[object Float32Array]',+ float64Tag$1 = '[object Float64Array]',+ int8Tag$1 = '[object Int8Array]',+ int16Tag$1 = '[object Int16Array]',+ int32Tag$1 = '[object Int32Array]',+ uint8Tag$1 = '[object Uint8Array]',+ uint8ClampedTag$1 = '[object Uint8ClampedArray]',+ uint16Tag$1 = '[object Uint16Array]',+ uint32Tag$1 = '[object Uint32Array]';++/**+ * Initializes an object clone based on its `toStringTag`.+ *+ * **Note:** This function only supports cloning values with tags of+ * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.+ *+ * @private+ * @param {Object} object The object to clone.+ * @param {string} tag The `toStringTag` of the object to clone.+ * @param {boolean} [isDeep] Specify a deep clone.+ * @returns {Object} Returns the initialized clone.+ */+function initCloneByTag(object, tag, isDeep) {+ var Ctor = object.constructor;+ switch (tag) {+ case arrayBufferTag$1:+ return cloneArrayBuffer(object);++ case boolTag$1:+ case dateTag$1:+ return new Ctor(+object);++ case dataViewTag$2:+ return cloneDataView(object, isDeep);++ case float32Tag$1: case float64Tag$1:+ case int8Tag$1: case int16Tag$1: case int32Tag$1:+ case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:+ return cloneTypedArray(object, isDeep);++ case mapTag$2:+ return new Ctor;++ case numberTag$1:+ case stringTag$1:+ return new Ctor(object);++ case regexpTag$1:+ return cloneRegExp(object);++ case setTag$2:+ return new Ctor;++ case symbolTag$1:+ return cloneSymbol(object);+ }+}++/** Built-in value references. */+var objectCreate = Object.create;++/**+ * The base implementation of `_.create` without support for assigning+ * properties to the created object.+ *+ * @private+ * @param {Object} proto The object to inherit from.+ * @returns {Object} Returns the new object.+ */+var baseCreate = (function() {+ function object() {}+ return function(proto) {+ if (!isObject$4(proto)) {+ return {};+ }+ if (objectCreate) {+ return objectCreate(proto);+ }+ object.prototype = proto;+ var result = new object;+ object.prototype = undefined;+ return result;+ };+}());++/**+ * Initializes an object clone.+ *+ * @private+ * @param {Object} object The object to clone.+ * @returns {Object} Returns the initialized clone.+ */+function initCloneObject(object) {+ return (typeof object.constructor == 'function' && !isPrototype(object))+ ? baseCreate(getPrototype(object))+ : {};+}++/** `Object#toString` result references. */+var mapTag$3 = '[object Map]';++/**+ * The base implementation of `_.isMap` without Node.js optimizations.+ *+ * @private+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a map, else `false`.+ */+function baseIsMap(value) {+ return isObjectLike$1(value) && getTag$1(value) == mapTag$3;+}++/* Node.js helper references. */+var nodeIsMap = nodeUtil && nodeUtil.isMap;++/**+ * Checks if `value` is classified as a `Map` object.+ *+ * @static+ * @memberOf _+ * @since 4.3.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a map, else `false`.+ * @example+ *+ * _.isMap(new Map);+ * // => true+ *+ * _.isMap(new WeakMap);+ * // => false+ */+var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;++/** `Object#toString` result references. */+var setTag$3 = '[object Set]';++/**+ * The base implementation of `_.isSet` without Node.js optimizations.+ *+ * @private+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a set, else `false`.+ */+function baseIsSet(value) {+ return isObjectLike$1(value) && getTag$1(value) == setTag$3;+}++/* Node.js helper references. */+var nodeIsSet = nodeUtil && nodeUtil.isSet;++/**+ * Checks if `value` is classified as a `Set` object.+ *+ * @static+ * @memberOf _+ * @since 4.3.0+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a set, else `false`.+ * @example+ *+ * _.isSet(new Set);+ * // => true+ *+ * _.isSet(new WeakSet);+ * // => false+ */+var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;++/** Used to compose bitmasks for cloning. */+var CLONE_DEEP_FLAG = 1,+ CLONE_FLAT_FLAG = 2,+ CLONE_SYMBOLS_FLAG = 4;++/** `Object#toString` result references. */+var argsTag$2 = '[object Arguments]',+ arrayTag$1 = '[object Array]',+ boolTag$2 = '[object Boolean]',+ dateTag$2 = '[object Date]',+ errorTag$1 = '[object Error]',+ funcTag$2 = '[object Function]',+ genTag$1 = '[object GeneratorFunction]',+ mapTag$4 = '[object Map]',+ numberTag$2 = '[object Number]',+ objectTag$2 = '[object Object]',+ regexpTag$2 = '[object RegExp]',+ setTag$4 = '[object Set]',+ stringTag$2 = '[object String]',+ symbolTag$2 = '[object Symbol]',+ weakMapTag$2 = '[object WeakMap]';++var arrayBufferTag$2 = '[object ArrayBuffer]',+ dataViewTag$3 = '[object DataView]',+ float32Tag$2 = '[object Float32Array]',+ float64Tag$2 = '[object Float64Array]',+ int8Tag$2 = '[object Int8Array]',+ int16Tag$2 = '[object Int16Array]',+ int32Tag$2 = '[object Int32Array]',+ uint8Tag$2 = '[object Uint8Array]',+ uint8ClampedTag$2 = '[object Uint8ClampedArray]',+ uint16Tag$2 = '[object Uint16Array]',+ uint32Tag$2 = '[object Uint32Array]';++/** Used to identify `toStringTag` values supported by `_.clone`. */+var cloneableTags = {};+cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] =+cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] =+cloneableTags[boolTag$2] = cloneableTags[dateTag$2] =+cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =+cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =+cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] =+cloneableTags[numberTag$2] = cloneableTags[objectTag$2] =+cloneableTags[regexpTag$2] = cloneableTags[setTag$4] =+cloneableTags[stringTag$2] = cloneableTags[symbolTag$2] =+cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =+cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;+cloneableTags[errorTag$1] = cloneableTags[funcTag$2] =+cloneableTags[weakMapTag$2] = false;++/**+ * The base implementation of `_.clone` and `_.cloneDeep` which tracks+ * traversed objects.+ *+ * @private+ * @param {*} value The value to clone.+ * @param {boolean} bitmask The bitmask flags.+ * 1 - Deep clone+ * 2 - Flatten inherited properties+ * 4 - Clone symbols+ * @param {Function} [customizer] The function to customize cloning.+ * @param {string} [key] The key of `value`.+ * @param {Object} [object] The parent object of `value`.+ * @param {Object} [stack] Tracks traversed objects and their clone counterparts.+ * @returns {*} Returns the cloned value.+ */+function baseClone(value, bitmask, customizer, key, object, stack) {+ var result,+ isDeep = bitmask & CLONE_DEEP_FLAG,+ isFlat = bitmask & CLONE_FLAT_FLAG,+ isFull = bitmask & CLONE_SYMBOLS_FLAG;++ if (customizer) {+ result = object ? customizer(value, key, object, stack) : customizer(value);+ }+ if (result !== undefined) {+ return result;+ }+ if (!isObject$4(value)) {+ return value;+ }+ var isArr = isArray(value);+ if (isArr) {+ result = initCloneArray(value);+ if (!isDeep) {+ return copyArray(value, result);+ }+ } else {+ var tag = getTag$1(value),+ isFunc = tag == funcTag$2 || tag == genTag$1;++ if (isBuffer(value)) {+ return cloneBuffer(value, isDeep);+ }+ if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) {+ result = (isFlat || isFunc) ? {} : initCloneObject(value);+ if (!isDeep) {+ return isFlat+ ? copySymbolsIn(value, baseAssignIn(result, value))+ : copySymbols(value, baseAssign(result, value));+ }+ } else {+ if (!cloneableTags[tag]) {+ return object ? value : {};+ }+ result = initCloneByTag(value, tag, isDeep);+ }+ }+ // Check for circular references and return its corresponding clone.+ stack || (stack = new Stack);+ var stacked = stack.get(value);+ if (stacked) {+ return stacked;+ }+ stack.set(value, result);++ if (isSet(value)) {+ value.forEach(function(subValue) {+ result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));+ });+ } else if (isMap(value)) {+ value.forEach(function(subValue, key) {+ result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));+ });+ }++ var keysFunc = isFull+ ? (isFlat ? getAllKeysIn : getAllKeys)+ : (isFlat ? keysIn : keys);++ var props = isArr ? undefined : keysFunc(value);+ arrayEach(props || value, function(subValue, key) {+ if (props) {+ key = subValue;+ subValue = value[key];+ }+ // Recursively populate clone (susceptible to call stack limits).+ assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));+ });+ return result;+}++/** Used to compose bitmasks for cloning. */+var CLONE_DEEP_FLAG$1 = 1,+ CLONE_SYMBOLS_FLAG$1 = 4;++/**+ * This method is like `_.cloneWith` except that it recursively clones `value`.+ *+ * @static+ * @memberOf _+ * @since 4.0.0+ * @category Lang+ * @param {*} value The value to recursively clone.+ * @param {Function} [customizer] The function to customize cloning.+ * @returns {*} Returns the deep cloned value.+ * @see _.cloneWith+ * @example+ *+ * function customizer(value) {+ * if (_.isElement(value)) {+ * return value.cloneNode(true);+ * }+ * }+ *+ * var el = _.cloneDeepWith(document.body, customizer);+ *+ * console.log(el === document.body);+ * // => false+ * console.log(el.nodeName);+ * // => 'BODY'+ * console.log(el.childNodes.length);+ * // => 20+ */+function cloneDeepWith(value, customizer) {+ customizer = typeof customizer == 'function' ? customizer : undefined;+ return baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$1, customizer);+}++/** `Object#toString` result references. */+var stringTag$3 = '[object String]';++/**+ * Checks if `value` is classified as a `String` primitive or object.+ *+ * @static+ * @since 0.1.0+ * @memberOf _+ * @category Lang+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` is a string, else `false`.+ * @example+ *+ * _.isString('abc');+ * // => true+ *+ * _.isString(1);+ * // => false+ */+function isString$1(value) {+ return typeof value == 'string' ||+ (!isArray(value) && isObjectLike$1(value) && baseGetTag(value) == stringTag$3);+}++/**+ * Converts `iterator` to an array.+ *+ * @private+ * @param {Object} iterator The iterator to convert.+ * @returns {Array} Returns the converted array.+ */+function iteratorToArray(iterator) {+ var data,+ result = [];++ while (!(data = iterator.next()).done) {+ result.push(data.value);+ }+ return result;+}++/**+ * Converts `map` to its key-value pairs.+ *+ * @private+ * @param {Object} map The map to convert.+ * @returns {Array} Returns the key-value pairs.+ */+function mapToArray(map) {+ var index = -1,+ result = Array(map.size);++ map.forEach(function(value, key) {+ result[++index] = [key, value];+ });+ return result;+}++/**+ * Converts `set` to an array of its values.+ *+ * @private+ * @param {Object} set The set to convert.+ * @returns {Array} Returns the values.+ */+function setToArray(set) {+ var index = -1,+ result = Array(set.size);++ set.forEach(function(value) {+ result[++index] = value;+ });+ return result;+}++/**+ * Converts an ASCII `string` to an array.+ *+ * @private+ * @param {string} string The string to convert.+ * @returns {Array} Returns the converted array.+ */+function asciiToArray(string) {+ return string.split('');+}++/** Used to compose unicode character classes. */+var rsAstralRange = '\\ud800-\\udfff',+ rsComboMarksRange = '\\u0300-\\u036f',+ reComboHalfMarksRange = '\\ufe20-\\ufe2f',+ rsComboSymbolsRange = '\\u20d0-\\u20ff',+ rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,+ rsVarRange = '\\ufe0e\\ufe0f';++/** Used to compose unicode capture groups. */+var rsZWJ = '\\u200d';++/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */+var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');++/**+ * Checks if `string` contains Unicode symbols.+ *+ * @private+ * @param {string} string The string to inspect.+ * @returns {boolean} Returns `true` if a symbol is found, else `false`.+ */+function hasUnicode(string) {+ return reHasUnicode.test(string);+}++/** Used to compose unicode character classes. */+var rsAstralRange$1 = '\\ud800-\\udfff',+ rsComboMarksRange$1 = '\\u0300-\\u036f',+ reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f',+ rsComboSymbolsRange$1 = '\\u20d0-\\u20ff',+ rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1,+ rsVarRange$1 = '\\ufe0e\\ufe0f';++/** Used to compose unicode capture groups. */+var rsAstral = '[' + rsAstralRange$1 + ']',+ rsCombo = '[' + rsComboRange$1 + ']',+ rsFitz = '\\ud83c[\\udffb-\\udfff]',+ rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',+ rsNonAstral = '[^' + rsAstralRange$1 + ']',+ rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',+ rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',+ rsZWJ$1 = '\\u200d';++/** Used to compose unicode regexes. */+var reOptMod = rsModifier + '?',+ rsOptVar = '[' + rsVarRange$1 + ']?',+ rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',+ rsSeq = rsOptVar + reOptMod + rsOptJoin,+ rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';++/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */+var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');++/**+ * Converts a Unicode `string` to an array.+ *+ * @private+ * @param {string} string The string to convert.+ * @returns {Array} Returns the converted array.+ */+function unicodeToArray(string) {+ return string.match(reUnicode) || [];+}++/**+ * Converts `string` to an array.+ *+ * @private+ * @param {string} string The string to convert.+ * @returns {Array} Returns the converted array.+ */+function stringToArray$1(string) {+ return hasUnicode(string)+ ? unicodeToArray(string)+ : asciiToArray(string);+}++/**+ * The base implementation of `_.values` and `_.valuesIn` which creates an+ * array of `object` property values corresponding to the property names+ * of `props`.+ *+ * @private+ * @param {Object} object The object to query.+ * @param {Array} props The property names to get values for.+ * @returns {Object} Returns the array of property values.+ */+function baseValues(object, props) {+ return arrayMap(props, function(key) {+ return object[key];+ });+}++/**+ * Creates an array of the own enumerable string keyed property values of `object`.+ *+ * **Note:** Non-object values are coerced to objects.+ *+ * @static+ * @since 0.1.0+ * @memberOf _+ * @category Object+ * @param {Object} object The object to query.+ * @returns {Array} Returns the array of property values.+ * @example+ *+ * function Foo() {+ * this.a = 1;+ * this.b = 2;+ * }+ *+ * Foo.prototype.c = 3;+ *+ * _.values(new Foo);+ * // => [1, 2] (iteration order is not guaranteed)+ *+ * _.values('hi');+ * // => ['h', 'i']+ */+function values(object) {+ return object == null ? [] : baseValues(object, keys(object));+}++/** `Object#toString` result references. */+var mapTag$5 = '[object Map]',+ setTag$5 = '[object Set]';++/** Built-in value references. */+var symIterator = Symbol$1 ? Symbol$1.iterator : undefined;++/**+ * Converts `value` to an array.+ *+ * @static+ * @since 0.1.0+ * @memberOf _+ * @category Lang+ * @param {*} value The value to convert.+ * @returns {Array} Returns the converted array.+ * @example+ *+ * _.toArray({ 'a': 1, 'b': 2 });+ * // => [1, 2]+ *+ * _.toArray('abc');+ * // => ['a', 'b', 'c']+ *+ * _.toArray(1);+ * // => []+ *+ * _.toArray(null);+ * // => []+ */+function toArray$1(value) {+ if (!value) {+ return [];+ }+ if (isArrayLike$2(value)) {+ return isString$1(value) ? stringToArray$1(value) : copyArray(value);+ }+ if (symIterator && value[symIterator]) {+ return iteratorToArray(value[symIterator]());+ }+ var tag = getTag$1(value),+ func = tag == mapTag$5 ? mapToArray : (tag == setTag$5 ? setToArray : values);++ return func(value);+}++var toString$1 = Object.prototype.toString;+var errorToString = Error.prototype.toString;+var regExpToString = RegExp.prototype.toString;+var symbolToString$1 = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : function () {+ return '';+};+var SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;++function printNumber(val) {+ if (val != +val) return 'NaN';+ var isNegativeZero = val === 0 && 1 / val < 0;+ return isNegativeZero ? '-0' : '' + val;+}++function printSimpleValue(val, quoteStrings) {+ if (quoteStrings === void 0) {+ quoteStrings = false;+ }++ if (val == null || val === true || val === false) return '' + val;+ var typeOf = typeof val;+ if (typeOf === 'number') return printNumber(val);+ if (typeOf === 'string') return quoteStrings ? "\"" + val + "\"" : val;+ if (typeOf === 'function') return '[Function ' + (val.name || 'anonymous') + ']';+ if (typeOf === 'symbol') return symbolToString$1.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');+ var tag = toString$1.call(val).slice(8, -1);+ if (tag === 'Date') return isNaN(val.getTime()) ? '' + val : val.toISOString(val);+ if (tag === 'Error' || val instanceof Error) return '[' + errorToString.call(val) + ']';+ if (tag === 'RegExp') return regExpToString.call(val);+ return null;+}++function printValue(value, quoteStrings) {+ var result = printSimpleValue(value, quoteStrings);+ if (result !== null) return result;+ return JSON.stringify(value, function (key, value) {+ var result = printSimpleValue(this[key], quoteStrings);+ if (result !== null) return result;+ return value;+ }, 2);+}++var mixed = {+ default: '${path} is invalid',+ required: '${path} is a required field',+ oneOf: '${path} must be one of the following values: ${values}',+ notOneOf: '${path} must not be one of the following values: ${values}',+ notType: function notType(_ref) {+ var path = _ref.path,+ type = _ref.type,+ value = _ref.value,+ originalValue = _ref.originalValue;+ var isCast = originalValue != null && originalValue !== value;+ var msg = path + " must be a `" + type + "` type, " + ("but the final value was: `" + printValue(value, true) + "`") + (isCast ? " (cast from the value `" + printValue(originalValue, true) + "`)." : '.');++ if (value === null) {+ msg += "\n If \"null\" is intended as an empty value be sure to mark the schema as `.nullable()`";+ }++ return msg;+ },+ defined: '${path} must be defined'+};+var string$1 = {+ length: '${path} must be exactly ${length} characters',+ min: '${path} must be at least ${min} characters',+ max: '${path} must be at most ${max} characters',+ matches: '${path} must match the following: "${regex}"',+ email: '${path} must be a valid email',+ url: '${path} must be a valid URL',+ uuid: '${path} must be a valid UUID',+ trim: '${path} must be a trimmed string',+ lowercase: '${path} must be a lowercase string',+ uppercase: '${path} must be a upper case string'+};+var number = {+ min: '${path} must be greater than or equal to ${min}',+ max: '${path} must be less than or equal to ${max}',+ lessThan: '${path} must be less than ${less}',+ moreThan: '${path} must be greater than ${more}',+ notEqual: '${path} must be not equal to ${notEqual}',+ positive: '${path} must be a positive number',+ negative: '${path} must be a negative number',+ integer: '${path} must be an integer'+};+var date = {+ min: '${path} field must be later than ${min}',+ max: '${path} field must be at earlier than ${max}'+};+var object = {+ noUnknown: '${path} field has unspecified keys: ${unknown}'+};+var array$1 = {+ min: '${path} field must have at least ${min} items',+ max: '${path} field must have less than or equal to ${max} items'+};++var isSchema$1 = (function (obj) {+ return obj && obj.__isYupSchema__;+});++var Condition = /*#__PURE__*/function () {+ function Condition(refs, options) {+ this.refs = refs;++ if (typeof options === 'function') {+ this.fn = options;+ return;+ }++ if (!has(options, 'is')) throw new TypeError('`is:` is required for `when()` conditions');+ if (!options.then && !options.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');+ var is = options.is,+ then = options.then,+ otherwise = options.otherwise;+ var check = typeof is === 'function' ? is : function () {+ for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {+ values[_key] = arguments[_key];+ }++ return values.every(function (value) {+ return value === is;+ });+ };++ this.fn = function () {+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {+ args[_key2] = arguments[_key2];+ }++ var options = args.pop();+ var schema = args.pop();+ var branch = check.apply(void 0, args) ? then : otherwise;+ if (!branch) return undefined;+ if (typeof branch === 'function') return branch(schema);+ return schema.concat(branch.resolve(options));+ };+ }++ var _proto = Condition.prototype;++ _proto.resolve = function resolve(base, options) {+ var values = this.refs.map(function (ref) {+ return ref.getValue(options);+ });+ var schema = this.fn.apply(base, values.concat(base, options));+ if (schema === undefined || schema === base) return base;+ if (!isSchema$1(schema)) throw new TypeError('conditions must return a schema object');+ return schema.resolve(options);+ };++ return Condition;+}();++function _objectWithoutPropertiesLoose(source, excluded) {+ if (source == null) return {};+ var target = {};+ var sourceKeys = Object.keys(source);+ var key, i;++ for (i = 0; i < sourceKeys.length; i++) {+ key = sourceKeys[i];+ if (excluded.indexOf(key) >= 0) continue;+ target[key] = source[key];+ }++ return target;+}++/* jshint node: true */ +function makeArrayFrom(obj) { + return Array.prototype.slice.apply(obj); +} +var + PENDING = "pending", + RESOLVED = "resolved", + REJECTED = "rejected"; + +function SynchronousPromise(handler) { + this.status = PENDING; + this._continuations = []; + this._parent = null; + this._paused = false; + if (handler) { + handler.call( + this, + this._continueWith.bind(this), + this._failWith.bind(this) + ); + } +} + +function looksLikeAPromise(obj) { + return obj && typeof (obj.then) === "function"; +} + +function passThrough(value) { + return value; +} + +SynchronousPromise.prototype = { + then: function (nextFn, catchFn) { + var next = SynchronousPromise.unresolved()._setParent(this); + if (this._isRejected()) { + if (this._paused) { + this._continuations.push({ + promise: next, + nextFn: nextFn, + catchFn: catchFn + }); + return next; + } + if (catchFn) { + try { + var catchResult = catchFn(this._error); + if (looksLikeAPromise(catchResult)) { + this._chainPromiseData(catchResult, next); + return next; + } else { + return SynchronousPromise.resolve(catchResult)._setParent(this); + } + } catch (e) { + return SynchronousPromise.reject(e)._setParent(this); + } + } + return SynchronousPromise.reject(this._error)._setParent(this); + } + this._continuations.push({ + promise: next, + nextFn: nextFn, + catchFn: catchFn + }); + this._runResolutions(); + return next; + }, + catch: function (handler) { + if (this._isResolved()) { + return SynchronousPromise.resolve(this._data)._setParent(this); + } + var next = SynchronousPromise.unresolved()._setParent(this); + this._continuations.push({ + promise: next, + catchFn: handler + }); + this._runRejections(); + return next; + }, + finally: function(callback) { + var ran = false; + function runFinally(result, err) { + if (!ran) { + ran = true; + if (!callback) { + callback = passThrough; + } + var callbackResult = callback(result); + if (looksLikeAPromise(callbackResult)) { + return callbackResult.then(function() { + if (err) { + throw err; + } + return result; + }); + } else { + return result; + } + } + } + return this + .then(function(result) { + return runFinally(result); + }) + .catch(function(err) { + return runFinally(null, err); + }); + }, + pause: function () { + this._paused = true; + return this; + }, + resume: function () { + var firstPaused = this._findFirstPaused(); + if (firstPaused) { + firstPaused._paused = false; + firstPaused._runResolutions(); + firstPaused._runRejections(); + } + return this; + }, + _findAncestry: function () { + return this._continuations.reduce(function (acc, cur) { + if (cur.promise) { + var node = { + promise: cur.promise, + children: cur.promise._findAncestry() + }; + acc.push(node); + } + return acc; + }, []); + }, + _setParent: function (parent) { + if (this._parent) { + throw new Error("parent already set"); + } + this._parent = parent; + return this; + }, + _continueWith: function (data) { + var firstPending = this._findFirstPending(); + if (firstPending) { + firstPending._data = data; + firstPending._setResolved(); + } + }, + _findFirstPending: function () { + return this._findFirstAncestor(function (test) { + return test._isPending && test._isPending(); + }); + }, + _findFirstPaused: function () { + return this._findFirstAncestor(function (test) { + return test._paused; + }); + }, + _findFirstAncestor: function (matching) { + var test = this; + var result; + while (test) { + if (matching(test)) { + result = test; + } + test = test._parent; + } + return result; + }, + _failWith: function (error) { + var firstRejected = this._findFirstPending(); + if (firstRejected) { + firstRejected._error = error; + firstRejected._setRejected(); + } + }, + _takeContinuations: function () { + return this._continuations.splice(0, this._continuations.length); + }, + _runRejections: function () { + if (this._paused || !this._isRejected()) { + return; + } + var + error = this._error, + continuations = this._takeContinuations(), + self = this; + continuations.forEach(function (cont) { + if (cont.catchFn) { + try { + var catchResult = cont.catchFn(error); + self._handleUserFunctionResult(catchResult, cont.promise); + } catch (e) { + cont.promise.reject(e); + } + } else { + cont.promise.reject(error); + } + }); + }, + _runResolutions: function () { + if (this._paused || !this._isResolved() || this._isPending()) { + return; + } + var continuations = this._takeContinuations(); + if (looksLikeAPromise(this._data)) { + return this._handleWhenResolvedDataIsPromise(this._data); + } + var data = this._data; + var self = this; + continuations.forEach(function (cont) { + if (cont.nextFn) { + try { + var result = cont.nextFn(data); + self._handleUserFunctionResult(result, cont.promise); + } catch (e) { + self._handleResolutionError(e, cont); + } + } else if (cont.promise) { + cont.promise.resolve(data); + } + }); + }, + _handleResolutionError: function (e, continuation) { + this._setRejected(); + if (continuation.catchFn) { + try { + continuation.catchFn(e); + return; + } catch (e2) { + e = e2; + } + } + if (continuation.promise) { + continuation.promise.reject(e); + } + }, + _handleWhenResolvedDataIsPromise: function (data) { + var self = this; + return data.then(function (result) { + self._data = result; + self._runResolutions(); + }).catch(function (error) { + self._error = error; + self._setRejected(); + self._runRejections(); + }); + }, + _handleUserFunctionResult: function (data, nextSynchronousPromise) { + if (looksLikeAPromise(data)) { + this._chainPromiseData(data, nextSynchronousPromise); + } else { + nextSynchronousPromise.resolve(data); + } + }, + _chainPromiseData: function (promiseData, nextSynchronousPromise) { + promiseData.then(function (newData) { + nextSynchronousPromise.resolve(newData); + }).catch(function (newError) { + nextSynchronousPromise.reject(newError); + }); + }, + _setResolved: function () { + this.status = RESOLVED; + if (!this._paused) { + this._runResolutions(); + } + }, + _setRejected: function () { + this.status = REJECTED; + if (!this._paused) { + this._runRejections(); + } + }, + _isPending: function () { + return this.status === PENDING; + }, + _isResolved: function () { + return this.status === RESOLVED; + }, + _isRejected: function () { + return this.status === REJECTED; + } +}; + +SynchronousPromise.resolve = function (result) { + return new SynchronousPromise(function (resolve, reject) { + if (looksLikeAPromise(result)) { + result.then(function (newResult) { + resolve(newResult); + }).catch(function (error) { + reject(error); + }); + } else { + resolve(result); + } + }); +}; + +SynchronousPromise.reject = function (result) { + return new SynchronousPromise(function (resolve, reject) { + reject(result); + }); +}; + +SynchronousPromise.unresolved = function () { + return new SynchronousPromise(function (resolve, reject) { + this.resolve = resolve; + this.reject = reject; + }); +}; + +SynchronousPromise.all = function () { + var args = makeArrayFrom(arguments); + if (Array.isArray(args[0])) { + args = args[0]; + } + if (!args.length) { + return SynchronousPromise.resolve([]); + } + return new SynchronousPromise(function (resolve, reject) { + var + allData = [], + numResolved = 0, + doResolve = function () { + if (numResolved === args.length) { + resolve(allData); + } + }, + rejected = false, + doReject = function (err) { + if (rejected) { + return; + } + rejected = true; + reject(err); + }; + args.forEach(function (arg, idx) { + SynchronousPromise.resolve(arg).then(function (thisResult) { + allData[idx] = thisResult; + numResolved += 1; + doResolve(); + }).catch(function (err) { + doReject(err); + }); + }); + }); +}; + +/* jshint ignore:start */ +if (Promise === SynchronousPromise) { + throw new Error("Please use SynchronousPromise.installGlobally() to install globally"); +} +var RealPromise = Promise; +SynchronousPromise.installGlobally = function(__awaiter) { + if (Promise === SynchronousPromise) { + return __awaiter; + } + var result = patchAwaiterIfRequired(__awaiter); + Promise = SynchronousPromise; + return result; +}; + +SynchronousPromise.uninstallGlobally = function() { + if (Promise === SynchronousPromise) { + Promise = RealPromise; + } +}; + +function patchAwaiterIfRequired(__awaiter) { + if (typeof(__awaiter) === "undefined" || __awaiter.__patched) { + return __awaiter; + } + var originalAwaiter = __awaiter; + __awaiter = function() { + originalAwaiter.apply(this, makeArrayFrom(arguments)); + }; + __awaiter.__patched = true; + return __awaiter; +} +/* jshint ignore:end */ + +var synchronousPromise = { + SynchronousPromise: SynchronousPromise +};++var strReg = /\$\{\s*(\w+)\s*\}/g;++var replace = function replace(str) {+ return function (params) {+ return str.replace(strReg, function (_, key) {+ return printValue(params[key]);+ });+ };+};++function ValidationError(errors, value, field, type) {+ var _this = this;++ this.name = 'ValidationError';+ this.value = value;+ this.path = field;+ this.type = type;+ this.errors = [];+ this.inner = [];+ if (errors) [].concat(errors).forEach(function (err) {+ _this.errors = _this.errors.concat(err.errors || err);+ if (err.inner) _this.inner = _this.inner.concat(err.inner.length ? err.inner : err);+ });+ this.message = this.errors.length > 1 ? this.errors.length + " errors occurred" : this.errors[0];+ if (Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);+}+ValidationError.prototype = Object.create(Error.prototype);+ValidationError.prototype.constructor = ValidationError;++ValidationError.isError = function (err) {+ return err && err.name === 'ValidationError';+};++ValidationError.formatError = function (message, params) {+ if (typeof message === 'string') message = replace(message);++ var fn = function fn(params) {+ params.path = params.label || params.path || 'this';+ return typeof message === 'function' ? message(params) : message;+ };++ return arguments.length === 1 ? fn : fn(params);+};++var promise = function promise(sync) {+ return sync ? synchronousPromise.SynchronousPromise : Promise;+};++var unwrapError = function unwrapError(errors) {+ if (errors === void 0) {+ errors = [];+ }++ return errors.inner && errors.inner.length ? errors.inner : [].concat(errors);+};++function scopeToValue(promises, value, sync) {+ //console.log('scopeToValue', promises, value)+ var p = promise(sync).all(promises); //console.log('scopeToValue B', p)++ var b = p.catch(function (err) {+ if (err.name === 'ValidationError') err.value = value;+ throw err;+ }); //console.log('scopeToValue c', b)++ var c = b.then(function () {+ return value;+ }); //console.log('scopeToValue d', c)++ return c;+}+/**+ * If not failing on the first error, catch the errors+ * and collect them in an array+ */+++function propagateErrors(endEarly, errors) {+ return endEarly ? null : function (err) {+ errors.push(err);+ return err.value;+ };+}+function settled(promises, sync) {+ var Promise = promise(sync);+ return Promise.all(promises.map(function (p) {+ return Promise.resolve(p).then(function (value) {+ return {+ fulfilled: true,+ value: value+ };+ }, function (value) {+ return {+ fulfilled: false,+ value: value+ };+ });+ }));+}+function collectErrors(_ref) {+ var validations = _ref.validations,+ value = _ref.value,+ path = _ref.path,+ sync = _ref.sync,+ errors = _ref.errors,+ sort = _ref.sort;+ errors = unwrapError(errors);+ return settled(validations, sync).then(function (results) {+ var nestedErrors = results.filter(function (r) {+ return !r.fulfilled;+ }).reduce(function (arr, _ref2) {+ var error = _ref2.value;++ // we are only collecting validation errors+ if (!ValidationError.isError(error)) {+ throw error;+ }++ return arr.concat(error);+ }, []);+ if (sort) nestedErrors.sort(sort); //show parent errors after the nested ones: name.first, name++ errors = nestedErrors.concat(errors);+ if (errors.length) throw new ValidationError(errors, value, path);+ return value;+ });+}+function runValidations(_ref3) {+ var endEarly = _ref3.endEarly,+ options = _objectWithoutPropertiesLoose(_ref3, ["endEarly"]);++ if (endEarly) return scopeToValue(options.validations, options.value, options.sync);+ return collectErrors(options);+}++var isObject$5 = function isObject(obj) {+ return Object.prototype.toString.call(obj) === '[object Object]';+};++function prependDeep(target, source) {+ for (var key in source) {+ if (has(source, key)) {+ var sourceVal = source[key],+ targetVal = target[key];++ if (targetVal === undefined) {+ target[key] = sourceVal;+ } else if (targetVal === sourceVal) {+ continue;+ } else if (isSchema$1(targetVal)) {+ if (isSchema$1(sourceVal)) target[key] = sourceVal.concat(targetVal);+ } else if (isObject$5(targetVal)) {+ if (isObject$5(sourceVal)) target[key] = prependDeep(targetVal, sourceVal);+ } else if (Array.isArray(targetVal)) {+ if (Array.isArray(sourceVal)) target[key] = sourceVal.concat(targetVal);+ }+ }+ }++ return target;+}++/**+ * Creates a base function for methods like `_.forIn` and `_.forOwn`.+ *+ * @private+ * @param {boolean} [fromRight] Specify iterating from right to left.+ * @returns {Function} Returns the new base function.+ */+function createBaseFor(fromRight) {+ return function(object, iteratee, keysFunc) {+ var index = -1,+ iterable = Object(object),+ props = keysFunc(object),+ length = props.length;++ while (length--) {+ var key = props[fromRight ? length : ++index];+ if (iteratee(iterable[key], key, iterable) === false) {+ break;+ }+ }+ return object;+ };+}++/**+ * The base implementation of `baseForOwn` which iterates over `object`+ * properties returned by `keysFunc` and invokes `iteratee` for each property.+ * Iteratee functions may exit iteration early by explicitly returning `false`.+ *+ * @private+ * @param {Object} object The object to iterate over.+ * @param {Function} iteratee The function invoked per iteration.+ * @param {Function} keysFunc The function to get the keys of `object`.+ * @returns {Object} Returns `object`.+ */+var baseFor = createBaseFor();++/**+ * The base implementation of `_.forOwn` without support for iteratee shorthands.+ *+ * @private+ * @param {Object} object The object to iterate over.+ * @param {Function} iteratee The function invoked per iteration.+ * @returns {Object} Returns `object`.+ */+function baseForOwn(object, iteratee) {+ return object && baseFor(object, iteratee, keys);+}++/** Used to stand-in for `undefined` hash values. */+var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';++/**+ * Adds `value` to the array cache.+ *+ * @private+ * @name add+ * @memberOf SetCache+ * @alias push+ * @param {*} value The value to cache.+ * @returns {Object} Returns the cache instance.+ */+function setCacheAdd(value) {+ this.__data__.set(value, HASH_UNDEFINED$2);+ return this;+}++/**+ * Checks if `value` is in the array cache.+ *+ * @private+ * @name has+ * @memberOf SetCache+ * @param {*} value The value to search for.+ * @returns {number} Returns `true` if `value` is found, else `false`.+ */+function setCacheHas(value) {+ return this.__data__.has(value);+}++/**+ *+ * Creates an array cache object to store unique values.+ *+ * @private+ * @constructor+ * @param {Array} [values] The values to cache.+ */+function SetCache(values) {+ var index = -1,+ length = values == null ? 0 : values.length;++ this.__data__ = new MapCache;+ while (++index < length) {+ this.add(values[index]);+ }+}++// Add methods to `SetCache`.+SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;+SetCache.prototype.has = setCacheHas;++/**+ * A specialized version of `_.some` for arrays without support for iteratee+ * shorthands.+ *+ * @private+ * @param {Array} [array] The array to iterate over.+ * @param {Function} predicate The function invoked per iteration.+ * @returns {boolean} Returns `true` if any element passes the predicate check,+ * else `false`.+ */+function arraySome(array, predicate) {+ var index = -1,+ length = array == null ? 0 : array.length;++ while (++index < length) {+ if (predicate(array[index], index, array)) {+ return true;+ }+ }+ return false;+}++/**+ * Checks if a `cache` value for `key` exists.+ *+ * @private+ * @param {Object} cache The cache to query.+ * @param {string} key The key of the entry to check.+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.+ */+function cacheHas(cache, key) {+ return cache.has(key);+}++/** Used to compose bitmasks for value comparisons. */+var COMPARE_PARTIAL_FLAG = 1,+ COMPARE_UNORDERED_FLAG = 2;++/**+ * A specialized version of `baseIsEqualDeep` for arrays with support for+ * partial deep comparisons.+ *+ * @private+ * @param {Array} array The array to compare.+ * @param {Array} other The other array to compare.+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.+ * @param {Function} customizer The function to customize comparisons.+ * @param {Function} equalFunc The function to determine equivalents of values.+ * @param {Object} stack Tracks traversed `array` and `other` objects.+ * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.+ */+function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG,+ arrLength = array.length,+ othLength = other.length;++ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {+ return false;+ }+ // Assume cyclic values are equal.+ var stacked = stack.get(array);+ if (stacked && stack.get(other)) {+ return stacked == other;+ }+ var index = -1,+ result = true,+ seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;++ stack.set(array, other);+ stack.set(other, array);++ // Ignore non-index properties.+ while (++index < arrLength) {+ var arrValue = array[index],+ othValue = other[index];++ if (customizer) {+ var compared = isPartial+ ? customizer(othValue, arrValue, index, other, array, stack)+ : customizer(arrValue, othValue, index, array, other, stack);+ }+ if (compared !== undefined) {+ if (compared) {+ continue;+ }+ result = false;+ break;+ }+ // Recursively compare arrays (susceptible to call stack limits).+ if (seen) {+ if (!arraySome(other, function(othValue, othIndex) {+ if (!cacheHas(seen, othIndex) &&+ (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {+ return seen.push(othIndex);+ }+ })) {+ result = false;+ break;+ }+ } else if (!(+ arrValue === othValue ||+ equalFunc(arrValue, othValue, bitmask, customizer, stack)+ )) {+ result = false;+ break;+ }+ }+ stack['delete'](array);+ stack['delete'](other);+ return result;+}++/** Used to compose bitmasks for value comparisons. */+var COMPARE_PARTIAL_FLAG$1 = 1,+ COMPARE_UNORDERED_FLAG$1 = 2;++/** `Object#toString` result references. */+var boolTag$3 = '[object Boolean]',+ dateTag$3 = '[object Date]',+ errorTag$2 = '[object Error]',+ mapTag$6 = '[object Map]',+ numberTag$3 = '[object Number]',+ regexpTag$3 = '[object RegExp]',+ setTag$6 = '[object Set]',+ stringTag$4 = '[object String]',+ symbolTag$3 = '[object Symbol]';++var arrayBufferTag$3 = '[object ArrayBuffer]',+ dataViewTag$4 = '[object DataView]';++/** Used to convert symbols to primitives and strings. */+var symbolProto$2 = Symbol$1 ? Symbol$1.prototype : undefined,+ symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;++/**+ * A specialized version of `baseIsEqualDeep` for comparing objects of+ * the same `toStringTag`.+ *+ * **Note:** This function only supports comparing values with tags of+ * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.+ *+ * @private+ * @param {Object} object The object to compare.+ * @param {Object} other The other object to compare.+ * @param {string} tag The `toStringTag` of the objects to compare.+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.+ * @param {Function} customizer The function to customize comparisons.+ * @param {Function} equalFunc The function to determine equivalents of values.+ * @param {Object} stack Tracks traversed `object` and `other` objects.+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.+ */+function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {+ switch (tag) {+ case dataViewTag$4:+ if ((object.byteLength != other.byteLength) ||+ (object.byteOffset != other.byteOffset)) {+ return false;+ }+ object = object.buffer;+ other = other.buffer;++ case arrayBufferTag$3:+ if ((object.byteLength != other.byteLength) ||+ !equalFunc(new Uint8Array(object), new Uint8Array(other))) {+ return false;+ }+ return true;++ case boolTag$3:+ case dateTag$3:+ case numberTag$3:+ // Coerce booleans to `1` or `0` and dates to milliseconds.+ // Invalid dates are coerced to `NaN`.+ return eq(+object, +other);++ case errorTag$2:+ return object.name == other.name && object.message == other.message;++ case regexpTag$3:+ case stringTag$4:+ // Coerce regexes to strings and treat strings, primitives and objects,+ // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring+ // for more details.+ return object == (other + '');++ case mapTag$6:+ var convert = mapToArray;++ case setTag$6:+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;+ convert || (convert = setToArray);++ if (object.size != other.size && !isPartial) {+ return false;+ }+ // Assume cyclic values are equal.+ var stacked = stack.get(object);+ if (stacked) {+ return stacked == other;+ }+ bitmask |= COMPARE_UNORDERED_FLAG$1;++ // Recursively compare objects (susceptible to call stack limits).+ stack.set(object, other);+ var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);+ stack['delete'](object);+ return result;++ case symbolTag$3:+ if (symbolValueOf$1) {+ return symbolValueOf$1.call(object) == symbolValueOf$1.call(other);+ }+ }+ return false;+}++/** Used to compose bitmasks for value comparisons. */+var COMPARE_PARTIAL_FLAG$2 = 1;++/** Used for built-in method references. */+var objectProto$e = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$c = objectProto$e.hasOwnProperty;++/**+ * A specialized version of `baseIsEqualDeep` for objects with support for+ * partial deep comparisons.+ *+ * @private+ * @param {Object} object The object to compare.+ * @param {Object} other The other object to compare.+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.+ * @param {Function} customizer The function to customize comparisons.+ * @param {Function} equalFunc The function to determine equivalents of values.+ * @param {Object} stack Tracks traversed `object` and `other` objects.+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.+ */+function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,+ objProps = getAllKeys(object),+ objLength = objProps.length,+ othProps = getAllKeys(other),+ othLength = othProps.length;++ if (objLength != othLength && !isPartial) {+ return false;+ }+ var index = objLength;+ while (index--) {+ var key = objProps[index];+ if (!(isPartial ? key in other : hasOwnProperty$c.call(other, key))) {+ return false;+ }+ }+ // Assume cyclic values are equal.+ var stacked = stack.get(object);+ if (stacked && stack.get(other)) {+ return stacked == other;+ }+ var result = true;+ stack.set(object, other);+ stack.set(other, object);++ var skipCtor = isPartial;+ while (++index < objLength) {+ key = objProps[index];+ var objValue = object[key],+ othValue = other[key];++ if (customizer) {+ var compared = isPartial+ ? customizer(othValue, objValue, key, other, object, stack)+ : customizer(objValue, othValue, key, object, other, stack);+ }+ // Recursively compare objects (susceptible to call stack limits).+ if (!(compared === undefined+ ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))+ : compared+ )) {+ result = false;+ break;+ }+ skipCtor || (skipCtor = key == 'constructor');+ }+ if (result && !skipCtor) {+ var objCtor = object.constructor,+ othCtor = other.constructor;++ // Non `Object` object instances with different constructors are not equal.+ if (objCtor != othCtor &&+ ('constructor' in object && 'constructor' in other) &&+ !(typeof objCtor == 'function' && objCtor instanceof objCtor &&+ typeof othCtor == 'function' && othCtor instanceof othCtor)) {+ result = false;+ }+ }+ stack['delete'](object);+ stack['delete'](other);+ return result;+}++/** Used to compose bitmasks for value comparisons. */+var COMPARE_PARTIAL_FLAG$3 = 1;++/** `Object#toString` result references. */+var argsTag$3 = '[object Arguments]',+ arrayTag$2 = '[object Array]',+ objectTag$3 = '[object Object]';++/** Used for built-in method references. */+var objectProto$f = Object.prototype;++/** Used to check objects for own properties. */+var hasOwnProperty$d = objectProto$f.hasOwnProperty;++/**+ * A specialized version of `baseIsEqual` for arrays and objects which performs+ * deep comparisons and tracks traversed objects enabling objects with circular+ * references to be compared.+ *+ * @private+ * @param {Object} object The object to compare.+ * @param {Object} other The other object to compare.+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.+ * @param {Function} customizer The function to customize comparisons.+ * @param {Function} equalFunc The function to determine equivalents of values.+ * @param {Object} [stack] Tracks traversed `object` and `other` objects.+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.+ */+function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {+ var objIsArr = isArray(object),+ othIsArr = isArray(other),+ objTag = objIsArr ? arrayTag$2 : getTag$1(object),+ othTag = othIsArr ? arrayTag$2 : getTag$1(other);++ objTag = objTag == argsTag$3 ? objectTag$3 : objTag;+ othTag = othTag == argsTag$3 ? objectTag$3 : othTag;++ var objIsObj = objTag == objectTag$3,+ othIsObj = othTag == objectTag$3,+ isSameTag = objTag == othTag;++ if (isSameTag && isBuffer(object)) {+ if (!isBuffer(other)) {+ return false;+ }+ objIsArr = true;+ objIsObj = false;+ }+ if (isSameTag && !objIsObj) {+ stack || (stack = new Stack);+ return (objIsArr || isTypedArray(object))+ ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)+ : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);+ }+ if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {+ var objIsWrapped = objIsObj && hasOwnProperty$d.call(object, '__wrapped__'),+ othIsWrapped = othIsObj && hasOwnProperty$d.call(other, '__wrapped__');++ if (objIsWrapped || othIsWrapped) {+ var objUnwrapped = objIsWrapped ? object.value() : object,+ othUnwrapped = othIsWrapped ? other.value() : other;++ stack || (stack = new Stack);+ return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);+ }+ }+ if (!isSameTag) {+ return false;+ }+ stack || (stack = new Stack);+ return equalObjects(object, other, bitmask, customizer, equalFunc, stack);+}++/**+ * The base implementation of `_.isEqual` which supports partial comparisons+ * and tracks traversed objects.+ *+ * @private+ * @param {*} value The value to compare.+ * @param {*} other The other value to compare.+ * @param {boolean} bitmask The bitmask flags.+ * 1 - Unordered comparison+ * 2 - Partial comparison+ * @param {Function} [customizer] The function to customize comparisons.+ * @param {Object} [stack] Tracks traversed `value` and `other` objects.+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.+ */+function baseIsEqual(value, other, bitmask, customizer, stack) {+ if (value === other) {+ return true;+ }+ if (value == null || other == null || (!isObjectLike$1(value) && !isObjectLike$1(other))) {+ return value !== value && other !== other;+ }+ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);+}++/** Used to compose bitmasks for value comparisons. */+var COMPARE_PARTIAL_FLAG$4 = 1,+ COMPARE_UNORDERED_FLAG$2 = 2;++/**+ * The base implementation of `_.isMatch` without support for iteratee shorthands.+ *+ * @private+ * @param {Object} object The object to inspect.+ * @param {Object} source The object of property values to match.+ * @param {Array} matchData The property names, values, and compare flags to match.+ * @param {Function} [customizer] The function to customize comparisons.+ * @returns {boolean} Returns `true` if `object` is a match, else `false`.+ */+function baseIsMatch(object, source, matchData, customizer) {+ var index = matchData.length,+ length = index,+ noCustomizer = !customizer;++ if (object == null) {+ return !length;+ }+ object = Object(object);+ while (index--) {+ var data = matchData[index];+ if ((noCustomizer && data[2])+ ? data[1] !== object[data[0]]+ : !(data[0] in object)+ ) {+ return false;+ }+ }+ while (++index < length) {+ data = matchData[index];+ var key = data[0],+ objValue = object[key],+ srcValue = data[1];++ if (noCustomizer && data[2]) {+ if (objValue === undefined && !(key in object)) {+ return false;+ }+ } else {+ var stack = new Stack;+ if (customizer) {+ var result = customizer(objValue, srcValue, key, object, source, stack);+ }+ if (!(result === undefined+ ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack)+ : result+ )) {+ return false;+ }+ }+ }+ return true;+}++/**+ * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.+ *+ * @private+ * @param {*} value The value to check.+ * @returns {boolean} Returns `true` if `value` if suitable for strict+ * equality comparisons, else `false`.+ */+function isStrictComparable(value) {+ return value === value && !isObject$4(value);+}++/**+ * Gets the property names, values, and compare flags of `object`.+ *+ * @private+ * @param {Object} object The object to query.+ * @returns {Array} Returns the match data of `object`.+ */+function getMatchData(object) {+ var result = keys(object),+ length = result.length;++ while (length--) {+ var key = result[length],+ value = object[key];++ result[length] = [key, value, isStrictComparable(value)];+ }+ return result;+}++/**+ * A specialized version of `matchesProperty` for source values suitable+ * for strict equality comparisons, i.e. `===`.+ *+ * @private+ * @param {string} key The key of the property to get.+ * @param {*} srcValue The value to match.+ * @returns {Function} Returns the new spec function.+ */+function matchesStrictComparable(key, srcValue) {+ return function(object) {+ if (object == null) {+ return false;+ }+ return object[key] === srcValue &&+ (srcValue !== undefined || (key in Object(object)));+ };+}++/**+ * The base implementation of `_.matches` which doesn't clone `source`.+ *+ * @private+ * @param {Object} source The object of property values to match.+ * @returns {Function} Returns the new spec function.+ */+function baseMatches(source) {+ var matchData = getMatchData(source);+ if (matchData.length == 1 && matchData[0][2]) {+ return matchesStrictComparable(matchData[0][0], matchData[0][1]);+ }+ return function(object) {+ return object === source || baseIsMatch(object, source, matchData);+ };+}++/**+ * The base implementation of `_.get` without support for default values.+ *+ * @private+ * @param {Object} object The object to query.+ * @param {Array|string} path The path of the property to get.+ * @returns {*} Returns the resolved value.+ */+function baseGet(object, path) {+ path = castPath(path, object);++ var index = 0,+ length = path.length;++ while (object != null && index < length) {+ object = object[toKey(path[index++])];+ }+ return (index && index == length) ? object : undefined;+}++/**+ * Gets the value at `path` of `object`. If the resolved value is+ * `undefined`, the `defaultValue` is returned in its place.+ *+ * @static+ * @memberOf _+ * @since 3.7.0+ * @category Object+ * @param {Object} object The object to query.+ * @param {Array|string} path The path of the property to get.+ * @param {*} [defaultValue] The value returned for `undefined` resolved values.+ * @returns {*} Returns the resolved value.+ * @example+ *+ * var object = { 'a': [{ 'b': { 'c': 3 } }] };+ *+ * _.get(object, 'a[0].b.c');+ * // => 3+ *+ * _.get(object, ['a', '0', 'b', 'c']);+ * // => 3+ *+ * _.get(object, 'a.b.c', 'default');+ * // => 'default'+ */+function get(object, path, defaultValue) {+ var result = object == null ? undefined : baseGet(object, path);+ return result === undefined ? defaultValue : result;+}++/**+ * The base implementation of `_.hasIn` without support for deep paths.+ *+ * @private+ * @param {Object} [object] The object to query.+ * @param {Array|string} key The key to check.+ * @returns {boolean} Returns `true` if `key` exists, else `false`.+ */+function baseHasIn(object, key) {+ return object != null && key in Object(object);+}++/**+ * Checks if `path` is a direct or inherited property of `object`.+ *+ * @static+ * @memberOf _+ * @since 4.0.0+ * @category Object+ * @param {Object} object The object to query.+ * @param {Array|string} path The path to check.+ * @returns {boolean} Returns `true` if `path` exists, else `false`.+ * @example+ *+ * var object = _.create({ 'a': _.create({ 'b': 2 }) });+ *+ * _.hasIn(object, 'a');+ * // => true+ *+ * _.hasIn(object, 'a.b');+ * // => true+ *+ * _.hasIn(object, ['a', 'b']);+ * // => true+ *+ * _.hasIn(object, 'b');+ * // => false+ */+function hasIn(object, path) {+ return object != null && hasPath(object, path, baseHasIn);+}++/** Used to compose bitmasks for value comparisons. */+var COMPARE_PARTIAL_FLAG$5 = 1,+ COMPARE_UNORDERED_FLAG$3 = 2;++/**+ * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.+ *+ * @private+ * @param {string} path The path of the property to get.+ * @param {*} srcValue The value to match.+ * @returns {Function} Returns the new spec function.+ */+function baseMatchesProperty(path, srcValue) {+ if (isKey(path) && isStrictComparable(srcValue)) {+ return matchesStrictComparable(toKey(path), srcValue);+ }+ return function(object) {+ var objValue = get(object, path);+ return (objValue === undefined && objValue === srcValue)+ ? hasIn(object, path)+ : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);+ };+}++/**+ * This method returns the first argument it receives.+ *+ * @static+ * @since 0.1.0+ * @memberOf _+ * @category Util+ * @param {*} value Any value.+ * @returns {*} Returns `value`.+ * @example+ *+ * var object = { 'a': 1 };+ *+ * console.log(_.identity(object) === object);+ * // => true+ */+function identity(value) {+ return value;+}++/**+ * The base implementation of `_.property` without support for deep paths.+ *+ * @private+ * @param {string} key The key of the property to get.+ * @returns {Function} Returns the new accessor function.+ */+function baseProperty(key) {+ return function(object) {+ return object == null ? undefined : object[key];+ };+}++/**+ * A specialized version of `baseProperty` which supports deep paths.+ *+ * @private+ * @param {Array|string} path The path of the property to get.+ * @returns {Function} Returns the new accessor function.+ */+function basePropertyDeep(path) {+ return function(object) {+ return baseGet(object, path);+ };+}++/**+ * Creates a function that returns the value at `path` of a given object.+ *+ * @static+ * @memberOf _+ * @since 2.4.0+ * @category Util+ * @param {Array|string} path The path of the property to get.+ * @returns {Function} Returns the new accessor function.+ * @example+ *+ * var objects = [+ * { 'a': { 'b': 2 } },+ * { 'a': { 'b': 1 } }+ * ];+ *+ * _.map(objects, _.property('a.b'));+ * // => [2, 1]+ *+ * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');+ * // => [1, 2]+ */+function property(path) {+ return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);+}++/**+ * The base implementation of `_.iteratee`.+ *+ * @private+ * @param {*} [value=_.identity] The value to convert to an iteratee.+ * @returns {Function} Returns the iteratee.+ */+function baseIteratee(value) {+ // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.+ // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.+ if (typeof value == 'function') {+ return value;+ }+ if (value == null) {+ return identity;+ }+ if (typeof value == 'object') {+ return isArray(value)+ ? baseMatchesProperty(value[0], value[1])+ : baseMatches(value);+ }+ return property(value);+}++/**+ * Creates an object with the same keys as `object` and values generated+ * by running each own enumerable string keyed property of `object` thru+ * `iteratee`. The iteratee is invoked with three arguments:+ * (value, key, object).+ *+ * @static+ * @memberOf _+ * @since 2.4.0+ * @category Object+ * @param {Object} object The object to iterate over.+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.+ * @returns {Object} Returns the new mapped object.+ * @see _.mapKeys+ * @example+ *+ * var users = {+ * 'fred': { 'user': 'fred', 'age': 40 },+ * 'pebbles': { 'user': 'pebbles', 'age': 1 }+ * };+ *+ * _.mapValues(users, function(o) { return o.age; });+ * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)+ *+ * // The `_.property` iteratee shorthand.+ * _.mapValues(users, 'age');+ * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)+ */+function mapValues(object, iteratee) {+ var result = {};+ iteratee = baseIteratee(iteratee);++ baseForOwn(object, function(value, key, object) {+ baseAssignValue(result, key, iteratee(value, key, object));+ });+ return result;+}++/**+ * Based on Kendo UI Core expression code <https://github.com/telerik/kendo-ui-core#license-information>+ */++function Cache(maxSize) {+ this._maxSize = maxSize;+ this.clear();+}+Cache.prototype.clear = function () {+ this._size = 0;+ this._values = Object.create(null);+};+Cache.prototype.get = function (key) {+ return this._values[key]+};+Cache.prototype.set = function (key, value) {+ this._size >= this._maxSize && this.clear();+ if (!(key in this._values)) this._size++;++ return (this._values[key] = value)+};++var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g,+ DIGIT_REGEX = /^\d+$/,+ LEAD_DIGIT_REGEX = /^\d/,+ SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,+ CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/,+ MAX_CACHE_SIZE = 512;++var pathCache = new Cache(MAX_CACHE_SIZE),+ setCache = new Cache(MAX_CACHE_SIZE),+ getCache = new Cache(MAX_CACHE_SIZE);++var propertyExpr = {+ Cache: Cache,++ split: split,++ normalizePath: normalizePath$1,++ setter: function (path) {+ var parts = normalizePath$1(path);++ return (+ setCache.get(path) ||+ setCache.set(path, function setter(obj, value) {+ var index = 0;+ var len = parts.length;+ var data = obj;++ while (index < len - 1) {+ var part = parts[index];+ if (+ part === '__proto__' ||+ part === 'constructor' ||+ part === 'prototype'+ ) {+ return obj+ }++ data = data[parts[index++]];+ }+ data[parts[index]] = value;+ })+ )+ },++ getter: function (path, safe) {+ var parts = normalizePath$1(path);+ return (+ getCache.get(path) ||+ getCache.set(path, function getter(data) {+ var index = 0,+ len = parts.length;+ while (index < len) {+ if (data != null || !safe) data = data[parts[index++]];+ else return+ }+ return data+ })+ )+ },++ join: function (segments) {+ return segments.reduce(function (path, part) {+ return (+ path ++ (isQuoted(part) || DIGIT_REGEX.test(part)+ ? '[' + part + ']'+ : (path ? '.' : '') + part)+ )+ }, '')+ },++ forEach: function (path, cb, thisArg) {+ forEach$1(Array.isArray(path) ? path : split(path), cb, thisArg);+ },+};++function normalizePath$1(path) {+ return (+ pathCache.get(path) ||+ pathCache.set(+ path,+ split(path).map(function (part) {+ return part.replace(CLEAN_QUOTES_REGEX, '$2')+ })+ )+ )+}++function split(path) {+ return path.match(SPLIT_REGEX)+}++function forEach$1(parts, iter, thisArg) {+ var len = parts.length,+ part,+ idx,+ isArray,+ isBracket;++ for (idx = 0; idx < len; idx++) {+ part = parts[idx];++ if (part) {+ if (shouldBeQuoted(part)) {+ part = '"' + part + '"';+ }++ isBracket = isQuoted(part);+ isArray = !isBracket && /^\d+$/.test(part);++ iter.call(thisArg, part, isBracket, isArray, idx, parts);+ }+ }+}++function isQuoted(str) {+ return (+ typeof str === 'string' && str && ["'", '"'].indexOf(str.charAt(0)) !== -1+ )+}++function hasLeadingNumber(part) {+ return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)+}++function hasSpecialChars(part) {+ return SPEC_CHAR_REGEX.test(part)+}++function shouldBeQuoted(part) {+ return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))+}++var prefixes = {+ context: '$',+ value: '.'+};++var Reference = /*#__PURE__*/function () {+ function Reference(key, options) {+ if (options === void 0) {+ options = {};+ }++ if (typeof key !== 'string') throw new TypeError('ref must be a string, got: ' + key);+ this.key = key.trim();+ if (key === '') throw new TypeError('ref must be a non-empty string');+ this.isContext = this.key[0] === prefixes.context;+ this.isValue = this.key[0] === prefixes.value;+ this.isSibling = !this.isContext && !this.isValue;+ var prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : '';+ this.path = this.key.slice(prefix.length);+ this.getter = this.path && propertyExpr.getter(this.path, true);+ this.map = options.map;+ }++ var _proto = Reference.prototype;++ _proto.getValue = function getValue(options) {+ var result = this.isContext ? options.context : this.isValue ? options.value : options.parent;+ if (this.getter) result = this.getter(result || {});+ if (this.map) result = this.map(result);+ return result;+ };++ _proto.cast = function cast(value, options) {+ return this.getValue(_extends({}, options, {+ value: value+ }));+ };++ _proto.resolve = function resolve() {+ return this;+ };++ _proto.describe = function describe() {+ return {+ type: 'ref',+ key: this.key+ };+ };++ _proto.toString = function toString() {+ return "Ref(" + this.key + ")";+ };++ Reference.isRef = function isRef(value) {+ return value && value.__isYupRef;+ };++ return Reference;+}();+Reference.prototype.__isYupRef = true;++var formatError$1 = ValidationError.formatError;++var thenable = function thenable(p) {+ return p && typeof p.then === 'function' && typeof p.catch === 'function';+};++function runTest(testFn, ctx, value, sync) {+ var result = testFn.call(ctx, value);+ if (!sync) return Promise.resolve(result);++ if (thenable(result)) {+ throw new Error("Validation test of type: \"" + ctx.type + "\" returned a Promise during a synchronous validate. " + "This test will finish after the validate call has returned");+ }++ return synchronousPromise.SynchronousPromise.resolve(result);+}++function resolveParams(oldParams, newParams, resolve) {+ return mapValues(_extends({}, oldParams, newParams), resolve);+}++function createErrorFactory(_ref) {+ var value = _ref.value,+ label = _ref.label,+ resolve = _ref.resolve,+ originalValue = _ref.originalValue,+ opts = _objectWithoutPropertiesLoose(_ref, ["value", "label", "resolve", "originalValue"]);++ return function createError(_temp) {+ var _ref2 = _temp === void 0 ? {} : _temp,+ _ref2$path = _ref2.path,+ path = _ref2$path === void 0 ? opts.path : _ref2$path,+ _ref2$message = _ref2.message,+ message = _ref2$message === void 0 ? opts.message : _ref2$message,+ _ref2$type = _ref2.type,+ type = _ref2$type === void 0 ? opts.name : _ref2$type,+ params = _ref2.params;++ params = _extends({+ path: path,+ value: value,+ originalValue: originalValue,+ label: label+ }, resolveParams(opts.params, params, resolve));+ return _extends(new ValidationError(formatError$1(message, params), value, path, type), {+ params: params+ });+ };+}+function createValidation(options) {+ var name = options.name,+ message = options.message,+ test = options.test,+ params = options.params;++ function validate(_ref3) {+ var value = _ref3.value,+ path = _ref3.path,+ label = _ref3.label,+ options = _ref3.options,+ originalValue = _ref3.originalValue,+ sync = _ref3.sync,+ rest = _objectWithoutPropertiesLoose(_ref3, ["value", "path", "label", "options", "originalValue", "sync"]);++ var parent = options.parent;++ var resolve = function resolve(item) {+ return Reference.isRef(item) ? item.getValue({+ value: value,+ parent: parent,+ context: options.context+ }) : item;+ };++ var createError = createErrorFactory({+ message: message,+ path: path,+ value: value,+ originalValue: originalValue,+ params: params,+ label: label,+ resolve: resolve,+ name: name+ });++ var ctx = _extends({+ path: path,+ parent: parent,+ type: name,+ createError: createError,+ resolve: resolve,+ options: options+ }, rest);++ return runTest(test, ctx, value, sync).then(function (validOrError) {+ if (ValidationError.isError(validOrError)) throw validOrError;else if (!validOrError) throw createError();+ });+ }++ validate.OPTIONS = options;+ return validate;+}++var trim = function trim(part) {+ return part.substr(0, part.length - 1).substr(1);+};++function getIn(schema, path, value, context) {+ if (context === void 0) {+ context = value;+ }++ var parent, lastPart, lastPartDebug; // root path: ''++ if (!path) return {+ parent: parent,+ parentPath: path,+ schema: schema+ };+ propertyExpr.forEach(path, function (_part, isBracket, isArray) {+ var part = isBracket ? trim(_part) : _part;+ schema = schema.resolve({+ context: context,+ parent: parent,+ value: value+ });++ if (schema.innerType) {+ var idx = isArray ? parseInt(part, 10) : 0;++ if (value && idx >= value.length) {+ throw new Error("Yup.reach cannot resolve an array item at index: " + _part + ", in the path: " + path + ". " + "because there is no value at that index. ");+ }++ parent = value;+ value = value && value[idx];+ schema = schema.innerType;+ } // sometimes the array index part of a path doesn't exist: "nested.arr.child"+ // in these cases the current part is the next schema and should be processed+ // in this iteration. For cases where the index signature is included this+ // check will fail and we'll handle the `child` part on the next iteration like normal+++ if (!isArray) {+ if (!schema.fields || !schema.fields[part]) throw new Error("The schema does not contain the path: " + path + ". " + ("(failed at: " + lastPartDebug + " which is a type: \"" + schema._type + "\")"));+ parent = value;+ value = value && value[part];+ schema = schema.fields[part];+ }++ lastPart = part;+ lastPartDebug = isBracket ? '[' + _part + ']' : '.' + _part;+ });+ return {+ schema: schema,+ parent: parent,+ parentPath: lastPart+ };+}++function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }++function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }++function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }++var RefSet = /*#__PURE__*/function () {+ function RefSet() {+ this.list = new Set();+ this.refs = new Map();+ }++ var _proto = RefSet.prototype;++ _proto.describe = function describe() {+ var description = [];++ for (var _iterator = _createForOfIteratorHelperLoose(this.list), _step; !(_step = _iterator()).done;) {+ var item = _step.value;+ description.push(item);+ }++ for (var _iterator2 = _createForOfIteratorHelperLoose(this.refs), _step2; !(_step2 = _iterator2()).done;) {+ var _step2$value = _step2.value,+ ref = _step2$value[1];+ description.push(ref.describe());+ }++ return description;+ };++ _proto.toArray = function toArray() {+ return toArray$1(this.list).concat(toArray$1(this.refs.values()));+ };++ _proto.add = function add(value) {+ Reference.isRef(value) ? this.refs.set(value.key, value) : this.list.add(value);+ };++ _proto.delete = function _delete(value) {+ Reference.isRef(value) ? this.refs.delete(value.key) : this.list.delete(value);+ };++ _proto.has = function has(value, resolve) {+ if (this.list.has(value)) return true;+ var item,+ values = this.refs.values();++ while (item = values.next(), !item.done) {+ if (resolve(item.value) === value) return true;+ }++ return false;+ };++ _proto.clone = function clone() {+ var next = new RefSet();+ next.list = new Set(this.list);+ next.refs = new Map(this.refs);+ return next;+ };++ _proto.merge = function merge(newItems, removeItems) {+ var next = this.clone();+ newItems.list.forEach(function (value) {+ return next.add(value);+ });+ newItems.refs.forEach(function (value) {+ return next.add(value);+ });+ removeItems.list.forEach(function (value) {+ return next.delete(value);+ });+ removeItems.refs.forEach(function (value) {+ return next.delete(value);+ });+ return next;+ };++ _createClass$5(RefSet, [{+ key: "size",+ get: function get() {+ return this.list.size + this.refs.size;+ }+ }]);++ return RefSet;+}();++function SchemaType(options) {+ var _this = this;++ if (options === void 0) {+ options = {};+ }++ if (!(this instanceof SchemaType)) return new SchemaType();+ this._deps = [];+ this._conditions = [];+ this._options = {+ abortEarly: true,+ recursive: true+ };+ this._exclusive = Object.create(null);+ this._whitelist = new RefSet();+ this._blacklist = new RefSet();+ this.tests = [];+ this.transforms = [];+ this.withMutation(function () {+ _this.typeError(mixed.notType);+ });+ if (has(options, 'default')) this._defaultDefault = options.default;+ this.type = options.type || 'mixed'; // TODO: remove++ this._type = options.type || 'mixed';+}+var proto = SchemaType.prototype = {+ __isYupSchema__: true,+ constructor: SchemaType,+ clone: function clone() {+ var _this2 = this;++ if (this._mutate) return this; // if the nested value is a schema we can skip cloning, since+ // they are already immutable++ return cloneDeepWith(this, function (value) {+ if (isSchema$1(value) && value !== _this2) return value;+ });+ },+ label: function label(_label) {+ var next = this.clone();+ next._label = _label;+ return next;+ },+ meta: function meta(obj) {+ if (arguments.length === 0) return this._meta;+ var next = this.clone();+ next._meta = _extends(next._meta || {}, obj);+ return next;+ },+ withMutation: function withMutation(fn) {+ var before = this._mutate;+ this._mutate = true;+ var result = fn(this);+ this._mutate = before;+ return result;+ },+ concat: function concat(schema) {+ if (!schema || schema === this) return this;+ if (schema._type !== this._type && this._type !== 'mixed') throw new TypeError("You cannot `concat()` schema's of different types: " + this._type + " and " + schema._type);+ var next = prependDeep(schema.clone(), this); // new undefined default is overridden by old non-undefined one, revert++ if (has(schema, '_default')) next._default = schema._default;+ next.tests = this.tests;+ next._exclusive = this._exclusive; // manually merge the blacklist/whitelist (the other `schema` takes+ // precedence in case of conflicts)++ next._whitelist = this._whitelist.merge(schema._whitelist, schema._blacklist);+ next._blacklist = this._blacklist.merge(schema._blacklist, schema._whitelist); // manually add the new tests to ensure+ // the deduping logic is consistent++ next.withMutation(function (next) {+ schema.tests.forEach(function (fn) {+ next.test(fn.OPTIONS);+ });+ });+ return next;+ },+ isType: function isType(v) {+ if (this._nullable && v === null) return true;+ return !this._typeCheck || this._typeCheck(v);+ },+ resolve: function resolve(options) {+ var schema = this;++ if (schema._conditions.length) {+ var conditions = schema._conditions;+ schema = schema.clone();+ schema._conditions = [];+ schema = conditions.reduce(function (schema, condition) {+ return condition.resolve(schema, options);+ }, schema);+ schema = schema.resolve(options);+ }++ return schema;+ },+ cast: function cast(value, options) {+ if (options === void 0) {+ options = {};+ }++ var resolvedSchema = this.resolve(_extends({}, options, {+ value: value+ }));++ var result = resolvedSchema._cast(value, options);++ if (value !== undefined && options.assert !== false && resolvedSchema.isType(result) !== true) {+ var formattedValue = printValue(value);+ var formattedResult = printValue(result);+ throw new TypeError("The value of " + (options.path || 'field') + " could not be cast to a value " + ("that satisfies the schema type: \"" + resolvedSchema._type + "\". \n\n") + ("attempted value: " + formattedValue + " \n") + (formattedResult !== formattedValue ? "result of cast: " + formattedResult : ''));+ }++ return result;+ },+ _cast: function _cast(rawValue) {+ var _this3 = this;++ var value = rawValue === undefined ? rawValue : this.transforms.reduce(function (value, fn) {+ return fn.call(_this3, value, rawValue);+ }, rawValue);++ if (value === undefined && has(this, '_default')) {+ value = this.default();+ }++ return value;+ },+ _validate: function _validate(_value, options) {+ var _this4 = this;++ if (options === void 0) {+ options = {};+ }++ var value = _value;+ var originalValue = options.originalValue != null ? options.originalValue : _value;++ var isStrict = this._option('strict', options);++ var endEarly = this._option('abortEarly', options);++ var sync = options.sync;+ var path = options.path;+ var label = this._label;++ if (!isStrict) {+ value = this._cast(value, _extends({+ assert: false+ }, options));+ } // value is cast, we can check if it meets type requirements+++ var validationParams = {+ value: value,+ path: path,+ schema: this,+ options: options,+ label: label,+ originalValue: originalValue,+ sync: sync+ };++ if (options.from) {+ validationParams.from = options.from;+ }++ var initialTests = [];+ if (this._typeError) initialTests.push(this._typeError(validationParams));+ if (this._whitelistError) initialTests.push(this._whitelistError(validationParams));+ if (this._blacklistError) initialTests.push(this._blacklistError(validationParams));+ return runValidations({+ validations: initialTests,+ endEarly: endEarly,+ value: value,+ path: path,+ sync: sync+ }).then(function (value) {+ return runValidations({+ path: path,+ sync: sync,+ value: value,+ endEarly: endEarly,+ validations: _this4.tests.map(function (fn) {+ return fn(validationParams);+ })+ });+ });+ },+ validate: function validate(value, options) {+ if (options === void 0) {+ options = {};+ }++ var schema = this.resolve(_extends({}, options, {+ value: value+ }));+ return schema._validate(value, options);+ },+ validateSync: function validateSync(value, options) {+ if (options === void 0) {+ options = {};+ }++ var schema = this.resolve(_extends({}, options, {+ value: value+ }));+ var result, err;++ schema._validate(value, _extends({}, options, {+ sync: true+ })).then(function (r) {+ return result = r;+ }).catch(function (e) {+ return err = e;+ });++ if (err) throw err;+ return result;+ },+ isValid: function isValid(value, options) {+ return this.validate(value, options).then(function () {+ return true;+ }).catch(function (err) {+ if (err.name === 'ValidationError') return false;+ throw err;+ });+ },+ isValidSync: function isValidSync(value, options) {+ try {+ this.validateSync(value, options);+ return true;+ } catch (err) {+ if (err.name === 'ValidationError') return false;+ throw err;+ }+ },+ getDefault: function getDefault(options) {+ if (options === void 0) {+ options = {};+ }++ var schema = this.resolve(options);+ return schema.default();+ },+ default: function _default(def) {+ if (arguments.length === 0) {+ var defaultValue = has(this, '_default') ? this._default : this._defaultDefault;+ return typeof defaultValue === 'function' ? defaultValue.call(this) : cloneDeepWith(defaultValue);+ }++ var next = this.clone();+ next._default = def;+ return next;+ },+ strict: function strict(isStrict) {+ if (isStrict === void 0) {+ isStrict = true;+ }++ var next = this.clone();+ next._options.strict = isStrict;+ return next;+ },+ _isPresent: function _isPresent(value) {+ return value != null;+ },+ required: function required(message) {+ if (message === void 0) {+ message = mixed.required;+ }++ return this.test({+ message: message,+ name: 'required',+ exclusive: true,+ test: function test(value) {+ return this.schema._isPresent(value);+ }+ });+ },+ notRequired: function notRequired() {+ var next = this.clone();+ next.tests = next.tests.filter(function (test) {+ return test.OPTIONS.name !== 'required';+ });+ return next;+ },+ nullable: function nullable(isNullable) {+ if (isNullable === void 0) {+ isNullable = true;+ }++ var next = this.clone();+ next._nullable = isNullable;+ return next;+ },+ transform: function transform(fn) {+ var next = this.clone();+ next.transforms.push(fn);+ return next;+ },++ /**+ * Adds a test function to the schema's queue of tests.+ * tests can be exclusive or non-exclusive.+ *+ * - exclusive tests, will replace any existing tests of the same name.+ * - non-exclusive: can be stacked+ *+ * If a non-exclusive test is added to a schema with an exclusive test of the same name+ * the exclusive test is removed and further tests of the same name will be stacked.+ *+ * If an exclusive test is added to a schema with non-exclusive tests of the same name+ * the previous tests are removed and further tests of the same name will replace each other.+ */+ test: function test() {+ var opts;++ if (arguments.length === 1) {+ if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'function') {+ opts = {+ test: arguments.length <= 0 ? undefined : arguments[0]+ };+ } else {+ opts = arguments.length <= 0 ? undefined : arguments[0];+ }+ } else if (arguments.length === 2) {+ opts = {+ name: arguments.length <= 0 ? undefined : arguments[0],+ test: arguments.length <= 1 ? undefined : arguments[1]+ };+ } else {+ opts = {+ name: arguments.length <= 0 ? undefined : arguments[0],+ message: arguments.length <= 1 ? undefined : arguments[1],+ test: arguments.length <= 2 ? undefined : arguments[2]+ };+ }++ if (opts.message === undefined) opts.message = mixed.default;+ if (typeof opts.test !== 'function') throw new TypeError('`test` is a required parameters');+ var next = this.clone();+ var validate = createValidation(opts);+ var isExclusive = opts.exclusive || opts.name && next._exclusive[opts.name] === true;++ if (opts.exclusive && !opts.name) {+ throw new TypeError('Exclusive tests must provide a unique `name` identifying the test');+ }++ next._exclusive[opts.name] = !!opts.exclusive;+ next.tests = next.tests.filter(function (fn) {+ if (fn.OPTIONS.name === opts.name) {+ if (isExclusive) return false;+ if (fn.OPTIONS.test === validate.OPTIONS.test) return false;+ }++ return true;+ });+ next.tests.push(validate);+ return next;+ },+ when: function when(keys, options) {+ if (arguments.length === 1) {+ options = keys;+ keys = '.';+ }++ var next = this.clone(),+ deps = [].concat(keys).map(function (key) {+ return new Reference(key);+ });+ deps.forEach(function (dep) {+ if (dep.isSibling) next._deps.push(dep.key);+ });++ next._conditions.push(new Condition(deps, options));++ return next;+ },+ typeError: function typeError(message) {+ var next = this.clone();+ next._typeError = createValidation({+ message: message,+ name: 'typeError',+ test: function test(value) {+ if (value !== undefined && !this.schema.isType(value)) return this.createError({+ params: {+ type: this.schema._type+ }+ });+ return true;+ }+ });+ return next;+ },+ oneOf: function oneOf(enums, message) {+ if (message === void 0) {+ message = mixed.oneOf;+ }++ var next = this.clone();+ enums.forEach(function (val) {+ next._whitelist.add(val);++ next._blacklist.delete(val);+ });+ next._whitelistError = createValidation({+ message: message,+ name: 'oneOf',+ test: function test(value) {+ if (value === undefined) return true;+ var valids = this.schema._whitelist;+ return valids.has(value, this.resolve) ? true : this.createError({+ params: {+ values: valids.toArray().join(', ')+ }+ });+ }+ });+ return next;+ },+ notOneOf: function notOneOf(enums, message) {+ if (message === void 0) {+ message = mixed.notOneOf;+ }++ var next = this.clone();+ enums.forEach(function (val) {+ next._blacklist.add(val);++ next._whitelist.delete(val);+ });+ next._blacklistError = createValidation({+ message: message,+ name: 'notOneOf',+ test: function test(value) {+ var invalids = this.schema._blacklist;+ if (invalids.has(value, this.resolve)) return this.createError({+ params: {+ values: invalids.toArray().join(', ')+ }+ });+ return true;+ }+ });+ return next;+ },+ strip: function strip(_strip) {+ if (_strip === void 0) {+ _strip = true;+ }++ var next = this.clone();+ next._strip = _strip;+ return next;+ },+ _option: function _option(key, overrides) {+ return has(overrides, key) ? overrides[key] : this._options[key];+ },+ describe: function describe() {+ var next = this.clone();+ var description = {+ type: next._type,+ meta: next._meta,+ label: next._label,+ tests: next.tests.map(function (fn) {+ return {+ name: fn.OPTIONS.name,+ params: fn.OPTIONS.params+ };+ }).filter(function (n, idx, list) {+ return list.findIndex(function (c) {+ return c.name === n.name;+ }) === idx;+ })+ };+ if (next._whitelist.size) description.oneOf = next._whitelist.describe();+ if (next._blacklist.size) description.notOneOf = next._blacklist.describe();+ return description;+ },+ defined: function defined(message) {+ if (message === void 0) {+ message = mixed.defined;+ }++ return this.nullable().test({+ message: message,+ name: 'defined',+ exclusive: true,+ test: function test(value) {+ return value !== undefined;+ }+ });+ }+};++var _loop = function _loop() {+ var method = _arr[_i];++ proto[method + "At"] = function (path, value, options) {+ if (options === void 0) {+ options = {};+ }++ var _getIn = getIn(this, path, value, options.context),+ parent = _getIn.parent,+ parentPath = _getIn.parentPath,+ schema = _getIn.schema;++ return schema[method](parent && parent[parentPath], _extends({}, options, {+ parent: parent,+ path: path+ }));+ };+};++for (var _i = 0, _arr = ['validate', 'validateSync']; _i < _arr.length; _i++) {+ _loop();+}++for (var _i2 = 0, _arr2 = ['equals', 'is']; _i2 < _arr2.length; _i2++) {+ var alias = _arr2[_i2];+ proto[alias] = proto.oneOf;+}++for (var _i3 = 0, _arr3 = ['not', 'nope']; _i3 < _arr3.length; _i3++) {+ var _alias = _arr3[_i3];+ proto[_alias] = proto.notOneOf;+}++proto.optional = proto.notRequired;++function inherits(ctor, superCtor, spec) {+ ctor.prototype = Object.create(superCtor.prototype, {+ constructor: {+ value: ctor,+ enumerable: false,+ writable: true,+ configurable: true+ }+ });++ _extends(ctor.prototype, spec);+}++function BooleanSchema() {+ var _this = this;++ if (!(this instanceof BooleanSchema)) return new BooleanSchema();+ SchemaType.call(this, {+ type: 'boolean'+ });+ this.withMutation(function () {+ _this.transform(function (value) {+ if (!this.isType(value)) {+ if (/^(true|1)$/i.test(value)) return true;+ if (/^(false|0)$/i.test(value)) return false;+ }++ return value;+ });+ });+}++inherits(BooleanSchema, SchemaType, {+ _typeCheck: function _typeCheck(v) {+ if (v instanceof Boolean) v = v.valueOf();+ return typeof v === 'boolean';+ }+});++var isAbsent = (function (value) {+ return value == null;+});++var rEmail = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; // eslint-disable-next-line++var rUrl = /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i; // eslint-disable-next-line++var rUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i;++var isTrimmed = function isTrimmed(value) {+ return isAbsent(value) || value === value.trim();+};++function StringSchema() {+ var _this = this;++ if (!(this instanceof StringSchema)) return new StringSchema();+ SchemaType.call(this, {+ type: 'string'+ });+ this.withMutation(function () {+ _this.transform(function (value) {+ if (this.isType(value)) return value;+ return value != null && value.toString ? value.toString() : value;+ });+ });+}+inherits(StringSchema, SchemaType, {+ _typeCheck: function _typeCheck(value) {+ if (value instanceof String) value = value.valueOf();+ return typeof value === 'string';+ },+ _isPresent: function _isPresent(value) {+ return SchemaType.prototype._isPresent.call(this, value) && value.length > 0;+ },+ length: function length(_length, message) {+ if (message === void 0) {+ message = string$1.length;+ }++ return this.test({+ message: message,+ name: 'length',+ exclusive: true,+ params: {+ length: _length+ },+ test: function test(value) {+ return isAbsent(value) || value.length === this.resolve(_length);+ }+ });+ },+ min: function min(_min, message) {+ if (message === void 0) {+ message = string$1.min;+ }++ return this.test({+ message: message,+ name: 'min',+ exclusive: true,+ params: {+ min: _min+ },+ test: function test(value) {+ return isAbsent(value) || value.length >= this.resolve(_min);+ }+ });+ },+ max: function max(_max, message) {+ if (message === void 0) {+ message = string$1.max;+ }++ return this.test({+ name: 'max',+ exclusive: true,+ message: message,+ params: {+ max: _max+ },+ test: function test(value) {+ return isAbsent(value) || value.length <= this.resolve(_max);+ }+ });+ },+ matches: function matches(regex, options) {+ var excludeEmptyString = false;+ var message;+ var name;++ if (options) {+ if (typeof options === 'object') {+ excludeEmptyString = options.excludeEmptyString;+ message = options.message;+ name = options.name;+ } else {+ message = options;+ }+ }++ return this.test({+ name: name || 'matches',+ message: message || string$1.matches,+ params: {+ regex: regex+ },+ test: function test(value) {+ return isAbsent(value) || value === '' && excludeEmptyString || value.search(regex) !== -1;+ }+ });+ },+ email: function email(message) {+ if (message === void 0) {+ message = string$1.email;+ }++ return this.matches(rEmail, {+ name: 'email',+ message: message,+ excludeEmptyString: true+ });+ },+ url: function url(message) {+ if (message === void 0) {+ message = string$1.url;+ }++ return this.matches(rUrl, {+ name: 'url',+ message: message,+ excludeEmptyString: true+ });+ },+ uuid: function uuid(message) {+ if (message === void 0) {+ message = string$1.uuid;+ }++ return this.matches(rUUID, {+ name: 'uuid',+ message: message,+ excludeEmptyString: false+ });+ },+ //-- transforms --+ ensure: function ensure() {+ return this.default('').transform(function (val) {+ return val === null ? '' : val;+ });+ },+ trim: function trim(message) {+ if (message === void 0) {+ message = string$1.trim;+ }++ return this.transform(function (val) {+ return val != null ? val.trim() : val;+ }).test({+ message: message,+ name: 'trim',+ test: isTrimmed+ });+ },+ lowercase: function lowercase(message) {+ if (message === void 0) {+ message = string$1.lowercase;+ }++ return this.transform(function (value) {+ return !isAbsent(value) ? value.toLowerCase() : value;+ }).test({+ message: message,+ name: 'string_case',+ exclusive: true,+ test: function test(value) {+ return isAbsent(value) || value === value.toLowerCase();+ }+ });+ },+ uppercase: function uppercase(message) {+ if (message === void 0) {+ message = string$1.uppercase; } return this.transform(function (value) {
src/Data/GraphQL/Query.hs view
@@ -10,6 +10,7 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeInType #-} module Data.GraphQL.Query ( GraphQLQuery(..)@@ -17,7 +18,7 @@ ) where import Data.Aeson (Value)-import Data.Aeson.Schema (IsSchemaObject, SchemaType)+import Data.Aeson.Schema (IsSchema, Schema) import Data.Text (Text) import qualified Data.Text as Text import Language.Haskell.TH.Quote (QuasiQuoter(..))@@ -28,8 +29,8 @@ -- Should be generated via the `graphql-codegen` command. Any manual instances needs -- to be certain that `getArgs query` satisfies the arguments defined in -- `getQueryText query`, and that the result adheres to `ResultSchema query`.-class IsSchemaObject (ResultSchema query) => GraphQLQuery query where- type ResultSchema query :: SchemaType+class IsSchema (ResultSchema query) => GraphQLQuery query where+ type ResultSchema query :: Schema getQueryName :: query -> Text getQueryText :: query -> Text getArgs :: query -> Value
src/Data/GraphQL/TestUtils.hs view
@@ -10,16 +10,19 @@ {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneDeriving #-} module Data.GraphQL.TestUtils ( ResultMock(..) , mocked , MockQueryT , runMockQueryT+ , AnyResultMock ) where import Control.Monad.IO.Class (MonadIO) import Control.Monad.State.Strict (MonadState, StateT, evalStateT, state)+import Control.Monad.Trans.Class (MonadTrans) import Data.Aeson (FromJSON, Value, object, (.=)) import qualified Data.Aeson.Types as Aeson import qualified Data.Text as Text@@ -33,13 +36,15 @@ , result :: Value } deriving (Show) -mocked :: GraphQLQuery query => ResultMock query -> AnyResultMock+mocked :: (Show query, GraphQLQuery query) => ResultMock query -> AnyResultMock mocked = AnyResultMock {- AnyResultMock -} -data AnyResultMock = forall query. GraphQLQuery query => AnyResultMock (ResultMock query)+data AnyResultMock = forall query. (Show query, GraphQLQuery query) => AnyResultMock (ResultMock query) +deriving instance Show AnyResultMock+ isMatch :: GraphQLQuery query => query -> AnyResultMock -> Bool isMatch testQuery (AnyResultMock mock) = getArgs (query mock) == getArgs testQuery @@ -49,7 +54,7 @@ {- MockQueryT -} newtype MockQueryT m a = MockQueryT { unMockQueryT :: StateT [AnyResultMock] m a }- deriving (Functor, Applicative, Monad, MonadIO, MonadState [AnyResultMock])+ deriving (Functor, Applicative, Monad, MonadIO, MonadState [AnyResultMock], MonadTrans) instance Monad m => MonadGraphQLQuery (MockQueryT m) where runQuerySafe testQuery = toGraphQLResult <$> lookupMock
test/Data/GraphQL/Test/Monad/Class.hs view
@@ -3,9 +3,6 @@ {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-}--- TypeApplications is needed in the [get| ... |] quasiquoter-{- HLint ignore "Unused LANGUAGE pragma" -}-{-# LANGUAGE TypeApplications #-} module Data.GraphQL.Test.Monad.Class where
test/Data/GraphQL/Test/TestQuery.hs view
@@ -9,6 +9,7 @@ import Data.GraphQL data TestQuery = TestQuery+ deriving (Show) type TestSchema = [schema| {