UNPKG

183 kBSource Map (JSON)View Raw
1{"version":3,"file":"index.cjs.js","sources":["../../../packages/utils/dist/index.esm.js","../../../dist/batch-delegate/src/getLoader.js","../../../dist/batch-delegate/src/batchDelegateToSchema.js","../../../dist/batch-delegate/src/createBatchDelegateFn.js"],"sourcesContent":["import { parse, isNonNullType, GraphQLError, Kind, valueFromAST, print, isObjectType, isListType, isSpecifiedScalarType, isIntrospectionType, astFromValue, isInterfaceType, isUnionType, isInputObjectType, isEnumType, isScalarType, isSpecifiedDirective, GraphQLDeprecatedDirective, specifiedRules, validate, buildSchema, Source, TokenKind, visit, isTypeSystemDefinitionNode, buildClientSchema, getNamedType, GraphQLString, GraphQLNonNull, GraphQLList, GraphQLID, GraphQLBoolean, GraphQLFloat, GraphQLInt, GraphQLObjectType, GraphQLInterfaceType, GraphQLInputObjectType, GraphQLDirective, GraphQLUnionType, GraphQLEnumType, GraphQLScalarType, isNamedType, getNullableType, isLeafType, GraphQLSchema, isSchema, isInputType, valueFromASTUntyped, isDirective, getDirectiveValues, GraphQLSkipDirective, GraphQLIncludeDirective, typeFromAST, isAbstractType, isCompositeType, doTypesOverlap, getOperationAST, getOperationRootType } from 'graphql';\nimport AggregateError from '@ardatan/aggregate-error';\nimport { camelCase } from 'camel-case';\n\nconst asArray = (fns) => (Array.isArray(fns) ? fns : fns ? [fns] : []);\nfunction isEqual(a, b) {\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return false;\n }\n for (let index = 0; index < a.length; index++) {\n if (a[index] !== b[index]) {\n return false;\n }\n }\n return true;\n }\n return a === b || (!a && !b);\n}\nfunction isNotEqual(a, b) {\n return !isEqual(a, b);\n}\nfunction isDocumentString(str) {\n // XXX: is-valid-path or is-glob treat SDL as a valid path\n // (`scalar Date` for example)\n // this why checking the extension is fast enough\n // and prevent from parsing the string in order to find out\n // if the string is a SDL\n if (/\\.[a-z0-9]+$/i.test(str)) {\n return false;\n }\n try {\n parse(str);\n return true;\n }\n catch (e) { }\n return false;\n}\nconst invalidPathRegex = /[‘“!%&^<=>`]/;\nfunction isValidPath(str) {\n return typeof str === 'string' && !invalidPathRegex.test(str);\n}\nfunction compareStrings(a, b) {\n if (a.toString() < b.toString()) {\n return -1;\n }\n if (a.toString() > b.toString()) {\n return 1;\n }\n return 0;\n}\nfunction nodeToString(a) {\n if ('alias' in a) {\n return a.alias.value;\n }\n if ('name' in a) {\n return a.name.value;\n }\n return a.kind;\n}\nfunction compareNodes(a, b, customFn) {\n const aStr = nodeToString(a);\n const bStr = nodeToString(b);\n if (typeof customFn === 'function') {\n return customFn(aStr, bStr);\n }\n return compareStrings(aStr, bStr);\n}\n\nfunction debugLog(...args) {\n if (process && process.env && process.env.DEBUG && !process.env.GQL_tools_NODEBUG) {\n // tslint:disable-next-line: no-console\n console.log(...args);\n }\n}\n\nconst fixWindowsPath = (path) => path.replace(/\\\\/g, '/');\n\nconst flattenArray = (arr) => arr.reduce((acc, next) => acc.concat(Array.isArray(next) ? flattenArray(next) : next), []);\n\nconst MAX_ARRAY_LENGTH = 10;\nconst MAX_RECURSIVE_DEPTH = 2;\n/**\n * Used to print values in error messages.\n */\nfunction inspect(value) {\n return formatValue(value, []);\n}\nfunction formatValue(value, seenValues) {\n switch (typeof value) {\n case 'string':\n return JSON.stringify(value);\n case 'function':\n return value.name ? `[function ${value.name}]` : '[function]';\n case 'object':\n if (value === null) {\n return 'null';\n }\n return formatObjectValue(value, seenValues);\n default:\n return String(value);\n }\n}\nfunction formatObjectValue(value, previouslySeenValues) {\n if (previouslySeenValues.indexOf(value) !== -1) {\n return '[Circular]';\n }\n const seenValues = [...previouslySeenValues, value];\n const customInspectFn = getCustomFn(value);\n if (customInspectFn !== undefined) {\n const customValue = customInspectFn.call(value);\n // check for infinite recursion\n if (customValue !== value) {\n return typeof customValue === 'string' ? customValue : formatValue(customValue, seenValues);\n }\n }\n else if (Array.isArray(value)) {\n return formatArray(value, seenValues);\n }\n return formatObject(value, seenValues);\n}\nfunction formatObject(object, seenValues) {\n const keys = Object.keys(object);\n if (keys.length === 0) {\n return '{}';\n }\n if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n return '[' + getObjectTag(object) + ']';\n }\n const properties = keys.map(key => {\n const value = formatValue(object[key], seenValues);\n return key + ': ' + value;\n });\n return '{ ' + properties.join(', ') + ' }';\n}\nfunction formatArray(array, seenValues) {\n if (array.length === 0) {\n return '[]';\n }\n if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n return '[Array]';\n }\n const len = Math.min(MAX_ARRAY_LENGTH, array.length);\n const remaining = array.length - len;\n const items = [];\n for (let i = 0; i < len; ++i) {\n items.push(formatValue(array[i], seenValues));\n }\n if (remaining === 1) {\n items.push('... 1 more item');\n }\n else if (remaining > 1) {\n items.push(`... ${remaining.toString(10)} more items`);\n }\n return '[' + items.join(', ') + ']';\n}\nfunction getCustomFn(obj) {\n if (typeof obj.inspect === 'function') {\n return obj.inspect;\n }\n}\nfunction getObjectTag(obj) {\n const tag = Object.prototype.toString\n .call(obj)\n .replace(/^\\[object /, '')\n .replace(/]$/, '');\n if (tag === 'Object' && typeof obj.constructor === 'function') {\n const name = obj.constructor.name;\n if (typeof name === 'string' && name !== '') {\n return name;\n }\n }\n return tag;\n}\n\n/**\n * Prepares an object map of argument values given a list of argument\n * definitions and list of argument AST nodes.\n *\n * Note: The returned value is a plain Object with a prototype, since it is\n * exposed to user code. Care should be taken to not pull values from the\n * Object prototype.\n */\nfunction getArgumentValues(def, node, variableValues = {}) {\n var _a;\n const variableMap = Object.entries(variableValues).reduce((prev, [key, value]) => ({\n ...prev,\n [key]: value,\n }), {});\n const coercedValues = {};\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const argumentNodes = (_a = node.arguments) !== null && _a !== void 0 ? _a : [];\n const argNodeMap = argumentNodes.reduce((prev, arg) => ({\n ...prev,\n [arg.name.value]: arg,\n }), {});\n for (const argDef of def.args) {\n const name = argDef.name;\n const argType = argDef.type;\n const argumentNode = argNodeMap[name];\n if (!argumentNode) {\n if (argDef.defaultValue !== undefined) {\n coercedValues[name] = argDef.defaultValue;\n }\n else if (isNonNullType(argType)) {\n throw new GraphQLError(`Argument \"${name}\" of required type \"${inspect(argType)}\" ` + 'was not provided.', node);\n }\n continue;\n }\n const valueNode = argumentNode.value;\n let isNull = valueNode.kind === Kind.NULL;\n if (valueNode.kind === Kind.VARIABLE) {\n const variableName = valueNode.name.value;\n if (variableValues == null || !(variableName in variableMap)) {\n if (argDef.defaultValue !== undefined) {\n coercedValues[name] = argDef.defaultValue;\n }\n else if (isNonNullType(argType)) {\n throw new GraphQLError(`Argument \"${name}\" of required type \"${inspect(argType)}\" ` +\n `was provided the variable \"$${variableName}\" which was not provided a runtime value.`, valueNode);\n }\n continue;\n }\n isNull = variableValues[variableName] == null;\n }\n if (isNull && isNonNullType(argType)) {\n throw new GraphQLError(`Argument \"${name}\" of non-null type \"${inspect(argType)}\" ` + 'must not be null.', valueNode);\n }\n const coercedValue = valueFromAST(valueNode, argType, variableValues);\n if (coercedValue === undefined) {\n // Note: ValuesOfCorrectTypeRule validation should catch this before\n // execution. This is a runtime check to ensure execution does not\n // continue with an invalid argument value.\n throw new GraphQLError(`Argument \"${name}\" has invalid value ${print(valueNode)}.`, valueNode);\n }\n coercedValues[name] = coercedValue;\n }\n return coercedValues;\n}\n\nfunction getDirectivesInExtensions(node, pathToDirectivesInExtensions = ['directives']) {\n const directivesInExtensions = pathToDirectivesInExtensions.reduce((acc, pathSegment) => (acc == null ? acc : acc[pathSegment]), node === null || node === void 0 ? void 0 : node.extensions);\n return directivesInExtensions;\n}\nfunction getDirectives(schema, node, pathToDirectivesInExtensions = ['directives']) {\n const directivesInExtensions = getDirectivesInExtensions(node, pathToDirectivesInExtensions);\n if (directivesInExtensions != null) {\n return directivesInExtensions;\n }\n const schemaDirectives = schema && schema.getDirectives ? schema.getDirectives() : [];\n const schemaDirectiveMap = schemaDirectives.reduce((schemaDirectiveMap, schemaDirective) => {\n schemaDirectiveMap[schemaDirective.name] = schemaDirective;\n return schemaDirectiveMap;\n }, {});\n let astNodes = [];\n if (node.astNode) {\n astNodes.push(node.astNode);\n }\n if ('extensionASTNodes' in node && node.extensionASTNodes) {\n astNodes = [...astNodes, ...node.extensionASTNodes];\n }\n const result = {};\n astNodes.forEach(astNode => {\n if (astNode.directives) {\n astNode.directives.forEach(directiveNode => {\n var _a;\n const schemaDirective = schemaDirectiveMap[directiveNode.name.value];\n if (schemaDirective) {\n if (schemaDirective.isRepeatable) {\n result[schemaDirective.name] = (_a = result[schemaDirective.name]) !== null && _a !== void 0 ? _a : [];\n result[schemaDirective.name].push(getArgumentValues(schemaDirective, directiveNode));\n }\n else {\n result[schemaDirective.name] = getArgumentValues(schemaDirective, directiveNode);\n }\n }\n });\n }\n });\n return result;\n}\n\nfunction parseDirectiveValue(value) {\n switch (value.kind) {\n case Kind.INT:\n return parseInt(value.value);\n case Kind.FLOAT:\n return parseFloat(value.value);\n case Kind.BOOLEAN:\n return Boolean(value.value);\n case Kind.STRING:\n case Kind.ENUM:\n return value.value;\n case Kind.LIST:\n return value.values.map(v => parseDirectiveValue(v));\n case Kind.OBJECT:\n return value.fields.reduce((prev, v) => ({ ...prev, [v.name.value]: parseDirectiveValue(v.value) }), {});\n case Kind.NULL:\n return null;\n default:\n return null;\n }\n}\nfunction getFieldsWithDirectives(documentNode, options = {}) {\n const result = {};\n let selected = ['ObjectTypeDefinition', 'ObjectTypeExtension'];\n if (options.includeInputTypes) {\n selected = [...selected, 'InputObjectTypeDefinition', 'InputObjectTypeExtension'];\n }\n const allTypes = documentNode.definitions.filter(obj => selected.includes(obj.kind));\n for (const type of allTypes) {\n const typeName = type.name.value;\n for (const field of type.fields) {\n if (field.directives && field.directives.length > 0) {\n const fieldName = field.name.value;\n const key = `${typeName}.${fieldName}`;\n const directives = field.directives.map(d => ({\n name: d.name.value,\n args: (d.arguments || []).reduce((prev, arg) => ({ ...prev, [arg.name.value]: parseDirectiveValue(arg.value) }), {}),\n }));\n result[key] = directives;\n }\n }\n }\n return result;\n}\n\nfunction getImplementingTypes(interfaceName, schema) {\n const allTypesMap = schema.getTypeMap();\n const result = [];\n for (const graphqlTypeName in allTypesMap) {\n const graphqlType = allTypesMap[graphqlTypeName];\n if (isObjectType(graphqlType)) {\n const allInterfaces = graphqlType.getInterfaces();\n if (allInterfaces.find(int => int.name === interfaceName)) {\n result.push(graphqlType.name);\n }\n }\n }\n return result;\n}\n\nfunction astFromType(type) {\n if (isNonNullType(type)) {\n const innerType = astFromType(type.ofType);\n if (innerType.kind === Kind.NON_NULL_TYPE) {\n throw new Error(`Invalid type node ${JSON.stringify(type)}. Inner type of non-null type cannot be a non-null type.`);\n }\n return {\n kind: Kind.NON_NULL_TYPE,\n type: innerType,\n };\n }\n else if (isListType(type)) {\n return {\n kind: Kind.LIST_TYPE,\n type: astFromType(type.ofType),\n };\n }\n return {\n kind: Kind.NAMED_TYPE,\n name: {\n kind: Kind.NAME,\n value: type.name,\n },\n };\n}\n\n/**\n * Produces a GraphQL Value AST given a JavaScript object.\n * Function will match JavaScript/JSON values to GraphQL AST schema format\n * by using the following mapping.\n *\n * | JSON Value | GraphQL Value |\n * | ------------- | -------------------- |\n * | Object | Input Object |\n * | Array | List |\n * | Boolean | Boolean |\n * | String | String |\n * | Number | Int / Float |\n * | null | NullValue |\n *\n */\nfunction astFromValueUntyped(value) {\n // only explicit null, not undefined, NaN\n if (value === null) {\n return { kind: Kind.NULL };\n }\n // undefined\n if (value === undefined) {\n return null;\n }\n // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but\n // the value is not an array, convert the value using the list's item type.\n if (Array.isArray(value)) {\n const valuesNodes = [];\n value.forEach(item => {\n const itemNode = astFromValueUntyped(item);\n if (itemNode != null) {\n valuesNodes.push(itemNode);\n }\n });\n return { kind: Kind.LIST, values: valuesNodes };\n }\n if (typeof value === 'object') {\n const fieldNodes = [];\n Object.entries(value).forEach(([fieldName, fieldValue]) => {\n const ast = astFromValueUntyped(fieldValue);\n if (ast) {\n fieldNodes.push({\n kind: Kind.OBJECT_FIELD,\n name: { kind: Kind.NAME, value: fieldName },\n value: ast,\n });\n }\n });\n return { kind: Kind.OBJECT, fields: fieldNodes };\n }\n // Others serialize based on their corresponding JavaScript scalar types.\n if (typeof value === 'boolean') {\n return { kind: Kind.BOOLEAN, value };\n }\n // JavaScript numbers can be Int or Float values.\n if (typeof value === 'number' && isFinite(value)) {\n const stringNum = String(value);\n return integerStringRegExp.test(stringNum)\n ? { kind: Kind.INT, value: stringNum }\n : { kind: Kind.FLOAT, value: stringNum };\n }\n if (typeof value === 'string') {\n return { kind: Kind.STRING, value };\n }\n throw new TypeError(`Cannot convert value to AST: ${value}.`);\n}\n/**\n * IntValue:\n * - NegativeSign? 0\n * - NegativeSign? NonZeroDigit ( Digit+ )?\n */\nconst integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;\n\nfunction getDocumentNodeFromSchema(schema, options = {}) {\n const pathToDirectivesInExtensions = options.pathToDirectivesInExtensions;\n const typesMap = schema.getTypeMap();\n const schemaNode = astFromSchema(schema, pathToDirectivesInExtensions);\n const definitions = schemaNode != null ? [schemaNode] : [];\n for (const typeName in typesMap) {\n const type = typesMap[typeName];\n const isPredefinedScalar = isSpecifiedScalarType(type);\n const isIntrospection = isIntrospectionType(type);\n if (isPredefinedScalar || isIntrospection) {\n continue;\n }\n if (isObjectType(type)) {\n definitions.push(astFromObjectType(type, schema, pathToDirectivesInExtensions));\n }\n else if (isInterfaceType(type)) {\n definitions.push(astFromInterfaceType(type, schema, pathToDirectivesInExtensions));\n }\n else if (isUnionType(type)) {\n definitions.push(astFromUnionType(type, schema, pathToDirectivesInExtensions));\n }\n else if (isInputObjectType(type)) {\n definitions.push(astFromInputObjectType(type, schema, pathToDirectivesInExtensions));\n }\n else if (isEnumType(type)) {\n definitions.push(astFromEnumType(type, schema, pathToDirectivesInExtensions));\n }\n else if (isScalarType(type)) {\n definitions.push(astFromScalarType(type, schema, pathToDirectivesInExtensions));\n }\n else {\n throw new Error(`Unknown type ${type}.`);\n }\n }\n const directives = schema.getDirectives();\n for (const directive of directives) {\n if (isSpecifiedDirective(directive)) {\n continue;\n }\n definitions.push(astFromDirective(directive, schema, pathToDirectivesInExtensions));\n }\n return {\n kind: Kind.DOCUMENT,\n definitions,\n };\n}\n// this approach uses the default schema printer rather than a custom solution, so may be more backwards compatible\n// currently does not allow customization of printSchema options having to do with comments.\nfunction printSchemaWithDirectives(schema, options = {}) {\n const documentNode = getDocumentNodeFromSchema(schema, options);\n return print(documentNode);\n}\nfunction astFromSchema(schema, pathToDirectivesInExtensions) {\n var _a, _b;\n const operationTypeMap = {\n query: undefined,\n mutation: undefined,\n subscription: undefined,\n };\n let nodes = [];\n if (schema.astNode != null) {\n nodes.push(schema.astNode);\n }\n if (schema.extensionASTNodes != null) {\n nodes = nodes.concat(schema.extensionASTNodes);\n }\n nodes.forEach(node => {\n if (node.operationTypes) {\n node.operationTypes.forEach(operationTypeDefinitionNode => {\n operationTypeMap[operationTypeDefinitionNode.operation] = operationTypeDefinitionNode;\n });\n }\n });\n const rootTypeMap = {\n query: schema.getQueryType(),\n mutation: schema.getMutationType(),\n subscription: schema.getSubscriptionType(),\n };\n Object.keys(operationTypeMap).forEach(operationTypeNode => {\n if (rootTypeMap[operationTypeNode] != null) {\n if (operationTypeMap[operationTypeNode] != null) {\n operationTypeMap[operationTypeNode].type = astFromType(rootTypeMap[operationTypeNode]);\n }\n else {\n operationTypeMap[operationTypeNode] = {\n kind: Kind.OPERATION_TYPE_DEFINITION,\n operation: operationTypeNode,\n type: astFromType(rootTypeMap[operationTypeNode]),\n };\n }\n }\n });\n const operationTypes = Object.values(operationTypeMap).filter(operationTypeDefinitionNode => operationTypeDefinitionNode != null);\n const directives = getDirectiveNodes(schema, schema, pathToDirectivesInExtensions);\n if (!operationTypes.length && !directives.length) {\n return null;\n }\n const schemaNode = {\n kind: operationTypes != null ? Kind.SCHEMA_DEFINITION : Kind.SCHEMA_EXTENSION,\n operationTypes,\n directives,\n };\n schemaNode.description =\n ((_b = (_a = schema.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : schema.description != null)\n ? {\n kind: Kind.STRING,\n value: schema.description,\n block: true,\n }\n : undefined;\n return schemaNode;\n}\nfunction astFromDirective(directive, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.DIRECTIVE_DEFINITION,\n description: (_b = (_a = directive.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : (directive.description\n ? {\n kind: Kind.STRING,\n value: directive.description,\n }\n : undefined),\n name: {\n kind: Kind.NAME,\n value: directive.name,\n },\n arguments: (directive === null || directive === void 0 ? void 0 : directive.args)\n ? directive.args.map(arg => astFromArg(arg, schema, pathToDirectivesInExtensions))\n : undefined,\n repeatable: directive.isRepeatable,\n locations: (directive === null || directive === void 0 ? void 0 : directive.locations)\n ? directive.locations.map(location => ({\n kind: Kind.NAME,\n value: location,\n }))\n : undefined,\n };\n}\nfunction getDirectiveNodes(entity, schema, pathToDirectivesInExtensions) {\n const directivesInExtensions = getDirectivesInExtensions(entity, pathToDirectivesInExtensions);\n let nodes = [];\n if (entity.astNode != null) {\n nodes.push(entity.astNode);\n }\n if ('extensionASTNodes' in entity && entity.extensionASTNodes != null) {\n nodes = nodes.concat(entity.extensionASTNodes);\n }\n let directives;\n if (directivesInExtensions != null) {\n directives = makeDirectiveNodes(schema, directivesInExtensions);\n }\n else {\n directives = [].concat(...nodes.filter(node => node.directives != null).map(node => node.directives));\n }\n return directives;\n}\nfunction getDeprecatableDirectiveNodes(entity, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n let directiveNodesBesidesDeprecated = [];\n let deprecatedDirectiveNode;\n const directivesInExtensions = getDirectivesInExtensions(entity, pathToDirectivesInExtensions);\n let directives;\n if (directivesInExtensions != null) {\n directives = makeDirectiveNodes(schema, directivesInExtensions);\n }\n else {\n directives = (_a = entity.astNode) === null || _a === void 0 ? void 0 : _a.directives;\n }\n if (directives != null) {\n directiveNodesBesidesDeprecated = directives.filter(directive => directive.name.value !== 'deprecated');\n if (entity.deprecationReason != null) {\n deprecatedDirectiveNode = (_b = directives.filter(directive => directive.name.value === 'deprecated')) === null || _b === void 0 ? void 0 : _b[0];\n }\n }\n if (entity.deprecationReason != null &&\n deprecatedDirectiveNode == null) {\n deprecatedDirectiveNode = makeDeprecatedDirective(entity.deprecationReason);\n }\n return deprecatedDirectiveNode == null\n ? directiveNodesBesidesDeprecated\n : [deprecatedDirectiveNode].concat(directiveNodesBesidesDeprecated);\n}\nfunction astFromArg(arg, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.INPUT_VALUE_DEFINITION,\n description: ((_b = (_a = arg.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : arg.description)\n ? {\n kind: Kind.STRING,\n value: arg.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: arg.name,\n },\n type: astFromType(arg.type),\n defaultValue: arg.defaultValue !== undefined ? astFromValue(arg.defaultValue, arg.type) : undefined,\n directives: getDeprecatableDirectiveNodes(arg, schema, pathToDirectivesInExtensions),\n };\n}\nfunction astFromObjectType(type, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.OBJECT_TYPE_DEFINITION,\n description: ((_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type.description)\n ? {\n kind: Kind.STRING,\n value: type.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: type.name,\n },\n fields: Object.values(type.getFields()).map(field => astFromField(field, schema, pathToDirectivesInExtensions)),\n interfaces: Object.values(type.getInterfaces()).map(iFace => astFromType(iFace)),\n directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),\n };\n}\nfunction astFromInterfaceType(type, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n const node = {\n kind: Kind.INTERFACE_TYPE_DEFINITION,\n description: ((_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type.description)\n ? {\n kind: Kind.STRING,\n value: type.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: type.name,\n },\n fields: Object.values(type.getFields()).map(field => astFromField(field, schema, pathToDirectivesInExtensions)),\n directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),\n };\n if ('getInterfaces' in type) {\n node.interfaces = Object.values(type.getInterfaces()).map(iFace => astFromType(iFace));\n }\n return node;\n}\nfunction astFromUnionType(type, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.UNION_TYPE_DEFINITION,\n description: ((_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type.description)\n ? {\n kind: Kind.STRING,\n value: type.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: type.name,\n },\n directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),\n types: type.getTypes().map(type => astFromType(type)),\n };\n}\nfunction astFromInputObjectType(type, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,\n description: ((_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type.description)\n ? {\n kind: Kind.STRING,\n value: type.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: type.name,\n },\n fields: Object.values(type.getFields()).map(field => astFromInputField(field, schema, pathToDirectivesInExtensions)),\n directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),\n };\n}\nfunction astFromEnumType(type, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.ENUM_TYPE_DEFINITION,\n description: ((_b = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type.description)\n ? {\n kind: Kind.STRING,\n value: type.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: type.name,\n },\n values: Object.values(type.getValues()).map(value => astFromEnumValue(value, schema, pathToDirectivesInExtensions)),\n directives: getDirectiveNodes(type, schema, pathToDirectivesInExtensions),\n };\n}\nfunction astFromScalarType(type, schema, pathToDirectivesInExtensions) {\n var _a, _b, _c, _d;\n let directiveNodesBesidesSpecifiedBy = [];\n let specifiedByDirectiveNode;\n const directivesInExtensions = getDirectivesInExtensions(type, pathToDirectivesInExtensions);\n let allDirectives;\n if (directivesInExtensions != null) {\n allDirectives = makeDirectiveNodes(schema, directivesInExtensions);\n }\n else {\n allDirectives = (_a = type.astNode) === null || _a === void 0 ? void 0 : _a.directives;\n }\n if (allDirectives != null) {\n directiveNodesBesidesSpecifiedBy = allDirectives.filter(directive => directive.name.value !== 'specifiedBy');\n if (type.specifiedByUrl != null) {\n specifiedByDirectiveNode = (_b = allDirectives.filter(directive => directive.name.value === 'specifiedBy')) === null || _b === void 0 ? void 0 : _b[0];\n }\n }\n if (type.specifiedByUrl != null && specifiedByDirectiveNode == null) {\n specifiedByDirectiveNode = makeDirectiveNode('specifiedBy', {\n url: type.specifiedByUrl,\n });\n }\n const directives = specifiedByDirectiveNode == null\n ? directiveNodesBesidesSpecifiedBy\n : [specifiedByDirectiveNode].concat(directiveNodesBesidesSpecifiedBy);\n return {\n kind: Kind.SCALAR_TYPE_DEFINITION,\n description: ((_d = (_c = type.astNode) === null || _c === void 0 ? void 0 : _c.description) !== null && _d !== void 0 ? _d : type.description)\n ? {\n kind: Kind.STRING,\n value: type.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: type.name,\n },\n directives,\n };\n}\nfunction astFromField(field, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.FIELD_DEFINITION,\n description: ((_b = (_a = field.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : field.description)\n ? {\n kind: Kind.STRING,\n value: field.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: field.name,\n },\n arguments: field.args.map(arg => astFromArg(arg, schema, pathToDirectivesInExtensions)),\n type: astFromType(field.type),\n directives: getDeprecatableDirectiveNodes(field, schema, pathToDirectivesInExtensions),\n };\n}\nfunction astFromInputField(field, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.INPUT_VALUE_DEFINITION,\n description: ((_b = (_a = field.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : field.description)\n ? {\n kind: Kind.STRING,\n value: field.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: field.name,\n },\n type: astFromType(field.type),\n directives: getDeprecatableDirectiveNodes(field, schema, pathToDirectivesInExtensions),\n defaultValue: astFromValue(field.defaultValue, field.type),\n };\n}\nfunction astFromEnumValue(value, schema, pathToDirectivesInExtensions) {\n var _a, _b;\n return {\n kind: Kind.ENUM_VALUE_DEFINITION,\n description: ((_b = (_a = value.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : value.description)\n ? {\n kind: Kind.STRING,\n value: value.description,\n block: true,\n }\n : undefined,\n name: {\n kind: Kind.NAME,\n value: value.name,\n },\n directives: getDirectiveNodes(value, schema, pathToDirectivesInExtensions),\n };\n}\nfunction makeDeprecatedDirective(deprecationReason) {\n return makeDirectiveNode('deprecated', { reason: deprecationReason }, GraphQLDeprecatedDirective);\n}\nfunction makeDirectiveNode(name, args, directive) {\n const directiveArguments = [];\n if (directive != null) {\n directive.args.forEach(arg => {\n const argName = arg.name;\n const argValue = args[argName];\n if (argValue !== undefined) {\n directiveArguments.push({\n kind: Kind.ARGUMENT,\n name: {\n kind: Kind.NAME,\n value: argName,\n },\n value: astFromValue(argValue, arg.type),\n });\n }\n });\n }\n else {\n Object.entries(args).forEach(([argName, argValue]) => {\n directiveArguments.push({\n kind: Kind.ARGUMENT,\n name: {\n kind: Kind.NAME,\n value: argName,\n },\n value: astFromValueUntyped(argValue),\n });\n });\n }\n return {\n kind: Kind.DIRECTIVE,\n name: {\n kind: Kind.NAME,\n value: name,\n },\n arguments: directiveArguments,\n };\n}\nfunction makeDirectiveNodes(schema, directiveValues) {\n const directiveNodes = [];\n Object.entries(directiveValues).forEach(([directiveName, arrayOrSingleValue]) => {\n const directive = schema.getDirective(directiveName);\n if (Array.isArray(arrayOrSingleValue)) {\n arrayOrSingleValue.forEach(value => {\n directiveNodes.push(makeDirectiveNode(directiveName, value, directive));\n });\n }\n else {\n directiveNodes.push(makeDirectiveNode(directiveName, arrayOrSingleValue, directive));\n }\n });\n return directiveNodes;\n}\n\nasync function validateGraphQlDocuments(schema, documentFiles, effectiveRules) {\n effectiveRules = effectiveRules || createDefaultRules();\n const allFragments = [];\n documentFiles.forEach(documentFile => {\n if (documentFile.document) {\n for (const definitionNode of documentFile.document.definitions) {\n if (definitionNode.kind === Kind.FRAGMENT_DEFINITION) {\n allFragments.push(definitionNode);\n }\n }\n }\n });\n const allErrors = [];\n await Promise.all(documentFiles.map(async (documentFile) => {\n const documentToValidate = {\n kind: Kind.DOCUMENT,\n definitions: [...allFragments, ...documentFile.document.definitions].filter((definition, index, list) => {\n if (definition.kind === Kind.FRAGMENT_DEFINITION) {\n const firstIndex = list.findIndex(def => def.kind === Kind.FRAGMENT_DEFINITION && def.name.value === definition.name.value);\n const isDuplicated = firstIndex !== index;\n if (isDuplicated) {\n return false;\n }\n }\n return true;\n }),\n };\n const errors = validate(schema, documentToValidate, effectiveRules);\n if (errors.length > 0) {\n allErrors.push({\n filePath: documentFile.location,\n errors,\n });\n }\n }));\n return allErrors;\n}\nfunction checkValidationErrors(loadDocumentErrors) {\n if (loadDocumentErrors.length > 0) {\n const errors = [];\n for (const loadDocumentError of loadDocumentErrors) {\n for (const graphQLError of loadDocumentError.errors) {\n const error = new Error();\n error.name = 'GraphQLDocumentError';\n error.message = `${error.name}: ${graphQLError.message}`;\n error.stack = error.message;\n graphQLError.locations.forEach(location => (error.stack += `\\n at ${loadDocumentError.filePath}:${location.line}:${location.column}`));\n errors.push(error);\n }\n }\n throw new AggregateError(errors);\n }\n}\nfunction createDefaultRules() {\n const ignored = ['NoUnusedFragmentsRule', 'NoUnusedVariablesRule', 'KnownDirectivesRule'];\n // GraphQL v14 has no Rule suffix in function names\n // Adding `*Rule` makes validation backwards compatible\n ignored.forEach(rule => {\n ignored.push(rule.replace(/Rule$/, ''));\n });\n return specifiedRules.filter((f) => !ignored.includes(f.name));\n}\n\nfunction buildFixedSchema(schema, options) {\n return buildSchema(printSchemaWithDirectives(schema), {\n noLocation: true,\n ...(options || {}),\n });\n}\nfunction fixSchemaAst(schema, options) {\n let schemaWithValidAst;\n if (!schema.astNode || !schema.extensionASTNodes) {\n schemaWithValidAst = buildFixedSchema(schema, options);\n }\n if (!schema.astNode) {\n schema.astNode = schemaWithValidAst.astNode;\n }\n if (!schema.extensionASTNodes) {\n schema.extensionASTNodes = schemaWithValidAst.extensionASTNodes;\n }\n return schema;\n}\n\n/**\n * Produces the value of a block string from its parsed raw value, similar to\n * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.\n *\n * This implements the GraphQL spec's BlockStringValue() static algorithm.\n *\n * @internal\n */\nfunction dedentBlockStringValue(rawString) {\n // Expand a block string's raw value into independent lines.\n var lines = rawString.split(/\\r\\n|[\\n\\r]/g); // Remove common indentation from all lines but first.\n\n var commonIndent = getBlockStringIndentation(rawString);\n\n if (commonIndent !== 0) {\n for (var i = 1; i < lines.length; i++) {\n lines[i] = lines[i].slice(commonIndent);\n }\n } // Remove leading and trailing blank lines.\n\n\n var startLine = 0;\n\n while (startLine < lines.length && isBlank(lines[startLine])) {\n ++startLine;\n }\n\n var endLine = lines.length;\n\n while (endLine > startLine && isBlank(lines[endLine - 1])) {\n --endLine;\n } // Return a string of the lines joined with U+000A.\n\n\n return lines.slice(startLine, endLine).join('\\n');\n}\n\nfunction isBlank(str) {\n for (var i = 0; i < str.length; ++i) {\n if (str[i] !== ' ' && str[i] !== '\\t') {\n return false;\n }\n }\n\n return true;\n}\n/**\n * @internal\n */\n\n\nfunction getBlockStringIndentation(value) {\n var _commonIndent;\n\n var isFirstLine = true;\n var isEmptyLine = true;\n var indent = 0;\n var commonIndent = null;\n\n for (var i = 0; i < value.length; ++i) {\n switch (value.charCodeAt(i)) {\n case 13:\n // \\r\n if (value.charCodeAt(i + 1) === 10) {\n ++i; // skip \\r\\n as one symbol\n }\n\n // falls through\n\n case 10:\n // \\n\n isFirstLine = false;\n isEmptyLine = true;\n indent = 0;\n break;\n\n case 9: // \\t\n\n case 32:\n // <space>\n ++indent;\n break;\n\n default:\n if (isEmptyLine && !isFirstLine && (commonIndent === null || indent < commonIndent)) {\n commonIndent = indent;\n }\n\n isEmptyLine = false;\n }\n }\n\n return (_commonIndent = commonIndent) !== null && _commonIndent !== void 0 ? _commonIndent : 0;\n}\n\nfunction parseGraphQLSDL(location, rawSDL, options = {}) {\n let document;\n const sdl = rawSDL;\n let sdlModified = false;\n try {\n if (options.commentDescriptions && sdl.includes('#')) {\n sdlModified = true;\n document = transformCommentsToDescriptions(rawSDL, options);\n // If noLocation=true, we need to make sure to print and parse it again, to remove locations,\n // since `transformCommentsToDescriptions` must have locations set in order to transform the comments\n // into descriptions.\n if (options.noLocation) {\n document = parse(print(document), options);\n }\n }\n else {\n document = parse(new Source(sdl, location), options);\n }\n }\n catch (e) {\n if (e.message.includes('EOF') && sdl.replace(/(\\#[^*]*)/g, '').trim() === '') {\n document = {\n kind: Kind.DOCUMENT,\n definitions: [],\n };\n }\n else {\n throw e;\n }\n }\n return {\n location,\n document,\n rawSDL: sdlModified ? print(document) : sdl,\n };\n}\nfunction getLeadingCommentBlock(node) {\n const loc = node.loc;\n if (!loc) {\n return;\n }\n const comments = [];\n let token = loc.startToken.prev;\n while (token != null &&\n token.kind === TokenKind.COMMENT &&\n token.next &&\n token.prev &&\n token.line + 1 === token.next.line &&\n token.line !== token.prev.line) {\n const value = String(token.value);\n comments.push(value);\n token = token.prev;\n }\n return comments.length > 0 ? comments.reverse().join('\\n') : undefined;\n}\nfunction transformCommentsToDescriptions(sourceSdl, options = {}) {\n const parsedDoc = parse(sourceSdl, {\n ...options,\n noLocation: false,\n });\n const modifiedDoc = visit(parsedDoc, {\n leave: (node) => {\n if (isDescribable(node)) {\n const rawValue = getLeadingCommentBlock(node);\n if (rawValue !== undefined) {\n const commentsBlock = dedentBlockStringValue('\\n' + rawValue);\n const isBlock = commentsBlock.includes('\\n');\n if (!node.description) {\n return {\n ...node,\n description: {\n kind: Kind.STRING,\n value: commentsBlock,\n block: isBlock,\n },\n };\n }\n else {\n return {\n ...node,\n description: {\n ...node.description,\n value: node.description.value + '\\n' + commentsBlock,\n block: true,\n },\n };\n }\n }\n }\n },\n });\n return modifiedDoc;\n}\nfunction isDescribable(node) {\n return (isTypeSystemDefinitionNode(node) ||\n node.kind === Kind.FIELD_DEFINITION ||\n node.kind === Kind.INPUT_VALUE_DEFINITION ||\n node.kind === Kind.ENUM_VALUE_DEFINITION);\n}\n\nfunction stripBOM(content) {\n content = content.toString();\n // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n // because the buffer-to-string conversion in `fs.readFileSync()`\n // translates it to FEFF, the UTF-16 BOM.\n if (content.charCodeAt(0) === 0xfeff) {\n content = content.slice(1);\n }\n return content;\n}\nfunction parseBOM(content) {\n return JSON.parse(stripBOM(content));\n}\nfunction parseGraphQLJSON(location, jsonContent, options) {\n let parsedJson = parseBOM(jsonContent);\n if (parsedJson.data) {\n parsedJson = parsedJson.data;\n }\n if (parsedJson.kind === 'Document') {\n const document = parsedJson;\n return {\n location,\n document,\n };\n }\n else if (parsedJson.__schema) {\n const schema = buildClientSchema(parsedJson, options);\n const rawSDL = printSchemaWithDirectives(schema, options);\n return {\n location,\n document: parseGraphQLSDL(location, rawSDL, options).document,\n rawSDL,\n schema,\n };\n }\n throw new Error(`Not valid JSON content`);\n}\n\n/**\n * Get all GraphQL types from schema without:\n *\n * - Query, Mutation, Subscription objects\n * - Internal scalars added by parser\n *\n * @param schema\n */\nfunction getUserTypesFromSchema(schema) {\n const allTypesMap = schema.getTypeMap();\n // tslint:disable-next-line: no-unnecessary-local-variable\n const modelTypes = Object.values(allTypesMap).filter((graphqlType) => {\n if (isObjectType(graphqlType)) {\n // Filter out private types\n if (graphqlType.name.startsWith('__')) {\n return false;\n }\n if (schema.getMutationType() && graphqlType.name === schema.getMutationType().name) {\n return false;\n }\n if (schema.getQueryType() && graphqlType.name === schema.getQueryType().name) {\n return false;\n }\n if (schema.getSubscriptionType() && graphqlType.name === schema.getSubscriptionType().name) {\n return false;\n }\n return true;\n }\n return false;\n });\n return modelTypes;\n}\n\nfunction createSchemaDefinition(def, config) {\n const schemaRoot = {};\n if (def.query) {\n schemaRoot.query = def.query.toString();\n }\n if (def.mutation) {\n schemaRoot.mutation = def.mutation.toString();\n }\n if (def.subscription) {\n schemaRoot.subscription = def.subscription.toString();\n }\n const fields = Object.keys(schemaRoot)\n .map(rootType => (schemaRoot[rootType] ? `${rootType}: ${schemaRoot[rootType]}` : null))\n .filter(a => a);\n if (fields.length) {\n return `schema { ${fields.join('\\n')} }`;\n }\n if (config && config.force) {\n return ` schema { query: Query } `;\n }\n return undefined;\n}\n\nlet operationVariables = [];\nlet fieldTypeMap = new Map();\nfunction addOperationVariable(variable) {\n operationVariables.push(variable);\n}\nfunction resetOperationVariables() {\n operationVariables = [];\n}\nfunction resetFieldMap() {\n fieldTypeMap = new Map();\n}\nfunction buildOperationName(name) {\n return camelCase(name);\n}\nfunction buildOperationNodeForField({ schema, kind, field, models, ignore, depthLimit, circularReferenceDepth, argNames, selectedFields = true, }) {\n resetOperationVariables();\n resetFieldMap();\n const operationNode = buildOperationAndCollectVariables({\n schema,\n fieldName: field,\n kind,\n models: models || [],\n ignore: ignore || [],\n depthLimit: depthLimit || Infinity,\n circularReferenceDepth: circularReferenceDepth || 1,\n argNames,\n selectedFields,\n });\n // attach variables\n operationNode.variableDefinitions = [...operationVariables];\n resetOperationVariables();\n resetFieldMap();\n return operationNode;\n}\nfunction buildOperationAndCollectVariables({ schema, fieldName, kind, models, ignore, depthLimit, circularReferenceDepth, argNames, selectedFields, }) {\n const typeMap = {\n query: schema.getQueryType(),\n mutation: schema.getMutationType(),\n subscription: schema.getSubscriptionType(),\n };\n const type = typeMap[kind];\n const field = type.getFields()[fieldName];\n const operationName = buildOperationName(`${fieldName}_${kind}`);\n if (field.args) {\n field.args.forEach(arg => {\n const argName = arg.name;\n if (!argNames || argNames.includes(argName)) {\n addOperationVariable(resolveVariable(arg, argName));\n }\n });\n }\n return {\n kind: Kind.OPERATION_DEFINITION,\n operation: kind,\n name: {\n kind: 'Name',\n value: operationName,\n },\n variableDefinitions: [],\n selectionSet: {\n kind: Kind.SELECTION_SET,\n selections: [\n resolveField({\n type,\n field,\n models,\n firstCall: true,\n path: [],\n ancestors: [],\n ignore,\n depthLimit,\n circularReferenceDepth,\n schema,\n depth: 0,\n argNames,\n selectedFields,\n }),\n ],\n },\n };\n}\nfunction resolveSelectionSet({ parent, type, models, firstCall, path, ancestors, ignore, depthLimit, circularReferenceDepth, schema, depth, argNames, selectedFields, }) {\n if (typeof selectedFields === 'boolean' && depth > depthLimit) {\n return;\n }\n if (isUnionType(type)) {\n const types = type.getTypes();\n return {\n kind: Kind.SELECTION_SET,\n selections: types\n .filter(t => !hasCircularRef([...ancestors, t], {\n depth: circularReferenceDepth,\n }))\n .map(t => {\n return {\n kind: Kind.INLINE_FRAGMENT,\n typeCondition: {\n kind: Kind.NAMED_TYPE,\n name: {\n kind: Kind.NAME,\n value: t.name,\n },\n },\n selectionSet: resolveSelectionSet({\n parent: type,\n type: t,\n models,\n path,\n ancestors,\n ignore,\n depthLimit,\n circularReferenceDepth,\n schema,\n depth,\n argNames,\n selectedFields,\n }),\n };\n })\n .filter(fragmentNode => { var _a, _b; return ((_b = (_a = fragmentNode === null || fragmentNode === void 0 ? void 0 : fragmentNode.selectionSet) === null || _a === void 0 ? void 0 : _a.selections) === null || _b === void 0 ? void 0 : _b.length) > 0; }),\n };\n }\n if (isInterfaceType(type)) {\n const types = Object.values(schema.getTypeMap()).filter((t) => isObjectType(t) && t.getInterfaces().includes(type));\n return {\n kind: Kind.SELECTION_SET,\n selections: types\n .filter(t => !hasCircularRef([...ancestors, t], {\n depth: circularReferenceDepth,\n }))\n .map(t => {\n return {\n kind: Kind.INLINE_FRAGMENT,\n typeCondition: {\n kind: Kind.NAMED_TYPE,\n name: {\n kind: Kind.NAME,\n value: t.name,\n },\n },\n selectionSet: resolveSelectionSet({\n parent: type,\n type: t,\n models,\n path,\n ancestors,\n ignore,\n depthLimit,\n circularReferenceDepth,\n schema,\n depth,\n argNames,\n selectedFields,\n }),\n };\n })\n .filter(fragmentNode => { var _a, _b; return ((_b = (_a = fragmentNode === null || fragmentNode === void 0 ? void 0 : fragmentNode.selectionSet) === null || _a === void 0 ? void 0 : _a.selections) === null || _b === void 0 ? void 0 : _b.length) > 0; }),\n };\n }\n if (isObjectType(type)) {\n const isIgnored = ignore.includes(type.name) || ignore.includes(`${parent.name}.${path[path.length - 1]}`);\n const isModel = models.includes(type.name);\n if (!firstCall && isModel && !isIgnored) {\n return {\n kind: Kind.SELECTION_SET,\n selections: [\n {\n kind: Kind.FIELD,\n name: {\n kind: Kind.NAME,\n value: 'id',\n },\n },\n ],\n };\n }\n const fields = type.getFields();\n return {\n kind: Kind.SELECTION_SET,\n selections: Object.keys(fields)\n .filter(fieldName => {\n return !hasCircularRef([...ancestors, getNamedType(fields[fieldName].type)], {\n depth: circularReferenceDepth,\n });\n })\n .map(fieldName => {\n const selectedSubFields = typeof selectedFields === 'object' ? selectedFields[fieldName] : true;\n if (selectedSubFields) {\n return resolveField({\n type: type,\n field: fields[fieldName],\n models,\n path: [...path, fieldName],\n ancestors,\n ignore,\n depthLimit,\n circularReferenceDepth,\n schema,\n depth,\n argNames,\n selectedFields: selectedSubFields,\n });\n }\n return null;\n })\n .filter(f => {\n var _a, _b;\n if (f) {\n if ('selectionSet' in f) {\n return (_b = (_a = f.selectionSet) === null || _a === void 0 ? void 0 : _a.selections) === null || _b === void 0 ? void 0 : _b.length;\n }\n else {\n return true;\n }\n }\n return false;\n }),\n };\n }\n}\nfunction resolveVariable(arg, name) {\n function resolveVariableType(type) {\n if (isListType(type)) {\n return {\n kind: Kind.LIST_TYPE,\n type: resolveVariableType(type.ofType),\n };\n }\n if (isNonNullType(type)) {\n return {\n kind: Kind.NON_NULL_TYPE,\n type: resolveVariableType(type.ofType),\n };\n }\n return {\n kind: Kind.NAMED_TYPE,\n name: {\n kind: Kind.NAME,\n value: type.name,\n },\n };\n }\n return {\n kind: Kind.VARIABLE_DEFINITION,\n variable: {\n kind: Kind.VARIABLE,\n name: {\n kind: Kind.NAME,\n value: name || arg.name,\n },\n },\n type: resolveVariableType(arg.type),\n };\n}\nfunction getArgumentName(name, path) {\n return camelCase([...path, name].join('_'));\n}\nfunction resolveField({ type, field, models, firstCall, path, ancestors, ignore, depthLimit, circularReferenceDepth, schema, depth, argNames, selectedFields, }) {\n const namedType = getNamedType(field.type);\n let args = [];\n let removeField = false;\n if (field.args && field.args.length) {\n args = field.args\n .map(arg => {\n const argumentName = getArgumentName(arg.name, path);\n if (argNames && !argNames.includes(argumentName)) {\n if (isNonNullType(arg.type)) {\n removeField = true;\n }\n return null;\n }\n if (!firstCall) {\n addOperationVariable(resolveVariable(arg, argumentName));\n }\n return {\n kind: Kind.ARGUMENT,\n name: {\n kind: Kind.NAME,\n value: arg.name,\n },\n value: {\n kind: Kind.VARIABLE,\n name: {\n kind: Kind.NAME,\n value: getArgumentName(arg.name, path),\n },\n },\n };\n })\n .filter(Boolean);\n }\n if (removeField) {\n return null;\n }\n const fieldPath = [...path, field.name];\n const fieldPathStr = fieldPath.join('.');\n let fieldName = field.name;\n if (fieldTypeMap.has(fieldPathStr) && fieldTypeMap.get(fieldPathStr) !== field.type.toString()) {\n fieldName += field.type.toString().replace('!', 'NonNull');\n }\n fieldTypeMap.set(fieldPathStr, field.type.toString());\n if (!isScalarType(namedType) && !isEnumType(namedType)) {\n return {\n kind: Kind.FIELD,\n name: {\n kind: Kind.NAME,\n value: field.name,\n },\n ...(fieldName !== field.name && { alias: { kind: Kind.NAME, value: fieldName } }),\n selectionSet: resolveSelectionSet({\n parent: type,\n type: namedType,\n models,\n firstCall,\n path: fieldPath,\n ancestors: [...ancestors, type],\n ignore,\n depthLimit,\n circularReferenceDepth,\n schema,\n depth: depth + 1,\n argNames,\n selectedFields,\n }) || undefined,\n arguments: args,\n };\n }\n return {\n kind: Kind.FIELD,\n name: {\n kind: Kind.NAME,\n value: field.name,\n },\n ...(fieldName !== field.name && { alias: { kind: Kind.NAME, value: fieldName } }),\n arguments: args,\n };\n}\nfunction hasCircularRef(types, config = {\n depth: 1,\n}) {\n const type = types[types.length - 1];\n if (isScalarType(type)) {\n return false;\n }\n const size = types.filter(t => t.name === type.name).length;\n return size > config.depth;\n}\n\nvar VisitSchemaKind;\n(function (VisitSchemaKind) {\n VisitSchemaKind[\"TYPE\"] = \"VisitSchemaKind.TYPE\";\n VisitSchemaKind[\"SCALAR_TYPE\"] = \"VisitSchemaKind.SCALAR_TYPE\";\n VisitSchemaKind[\"ENUM_TYPE\"] = \"VisitSchemaKind.ENUM_TYPE\";\n VisitSchemaKind[\"COMPOSITE_TYPE\"] = \"VisitSchemaKind.COMPOSITE_TYPE\";\n VisitSchemaKind[\"OBJECT_TYPE\"] = \"VisitSchemaKind.OBJECT_TYPE\";\n VisitSchemaKind[\"INPUT_OBJECT_TYPE\"] = \"VisitSchemaKind.INPUT_OBJECT_TYPE\";\n VisitSchemaKind[\"ABSTRACT_TYPE\"] = \"VisitSchemaKind.ABSTRACT_TYPE\";\n VisitSchemaKind[\"UNION_TYPE\"] = \"VisitSchemaKind.UNION_TYPE\";\n VisitSchemaKind[\"INTERFACE_TYPE\"] = \"VisitSchemaKind.INTERFACE_TYPE\";\n VisitSchemaKind[\"ROOT_OBJECT\"] = \"VisitSchemaKind.ROOT_OBJECT\";\n VisitSchemaKind[\"QUERY\"] = \"VisitSchemaKind.QUERY\";\n VisitSchemaKind[\"MUTATION\"] = \"VisitSchemaKind.MUTATION\";\n VisitSchemaKind[\"SUBSCRIPTION\"] = \"VisitSchemaKind.SUBSCRIPTION\";\n})(VisitSchemaKind || (VisitSchemaKind = {}));\nvar MapperKind;\n(function (MapperKind) {\n MapperKind[\"TYPE\"] = \"MapperKind.TYPE\";\n MapperKind[\"SCALAR_TYPE\"] = \"MapperKind.SCALAR_TYPE\";\n MapperKind[\"ENUM_TYPE\"] = \"MapperKind.ENUM_TYPE\";\n MapperKind[\"COMPOSITE_TYPE\"] = \"MapperKind.COMPOSITE_TYPE\";\n MapperKind[\"OBJECT_TYPE\"] = \"MapperKind.OBJECT_TYPE\";\n MapperKind[\"INPUT_OBJECT_TYPE\"] = \"MapperKind.INPUT_OBJECT_TYPE\";\n MapperKind[\"ABSTRACT_TYPE\"] = \"MapperKind.ABSTRACT_TYPE\";\n MapperKind[\"UNION_TYPE\"] = \"MapperKind.UNION_TYPE\";\n MapperKind[\"INTERFACE_TYPE\"] = \"MapperKind.INTERFACE_TYPE\";\n MapperKind[\"ROOT_OBJECT\"] = \"MapperKind.ROOT_OBJECT\";\n MapperKind[\"QUERY\"] = \"MapperKind.QUERY\";\n MapperKind[\"MUTATION\"] = \"MapperKind.MUTATION\";\n MapperKind[\"SUBSCRIPTION\"] = \"MapperKind.SUBSCRIPTION\";\n MapperKind[\"DIRECTIVE\"] = \"MapperKind.DIRECTIVE\";\n MapperKind[\"FIELD\"] = \"MapperKind.FIELD\";\n MapperKind[\"COMPOSITE_FIELD\"] = \"MapperKind.COMPOSITE_FIELD\";\n MapperKind[\"OBJECT_FIELD\"] = \"MapperKind.OBJECT_FIELD\";\n MapperKind[\"ROOT_FIELD\"] = \"MapperKind.ROOT_FIELD\";\n MapperKind[\"QUERY_ROOT_FIELD\"] = \"MapperKind.QUERY_ROOT_FIELD\";\n MapperKind[\"MUTATION_ROOT_FIELD\"] = \"MapperKind.MUTATION_ROOT_FIELD\";\n MapperKind[\"SUBSCRIPTION_ROOT_FIELD\"] = \"MapperKind.SUBSCRIPTION_ROOT_FIELD\";\n MapperKind[\"INTERFACE_FIELD\"] = \"MapperKind.INTERFACE_FIELD\";\n MapperKind[\"INPUT_OBJECT_FIELD\"] = \"MapperKind.INPUT_OBJECT_FIELD\";\n MapperKind[\"ARGUMENT\"] = \"MapperKind.ARGUMENT\";\n MapperKind[\"ENUM_VALUE\"] = \"MapperKind.ENUM_VALUE\";\n})(MapperKind || (MapperKind = {}));\n\nfunction createNamedStub(name, type) {\n let constructor;\n if (type === 'object') {\n constructor = GraphQLObjectType;\n }\n else if (type === 'interface') {\n constructor = GraphQLInterfaceType;\n }\n else {\n constructor = GraphQLInputObjectType;\n }\n return new constructor({\n name,\n fields: {\n __fake: {\n type: GraphQLString,\n },\n },\n });\n}\nfunction createStub(node, type) {\n switch (node.kind) {\n case Kind.LIST_TYPE:\n return new GraphQLList(createStub(node.type, type));\n case Kind.NON_NULL_TYPE:\n return new GraphQLNonNull(createStub(node.type, type));\n default:\n if (type === 'output') {\n return createNamedStub(node.name.value, 'object');\n }\n return createNamedStub(node.name.value, 'input');\n }\n}\nfunction isNamedStub(type) {\n if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {\n const fields = type.getFields();\n const fieldNames = Object.keys(fields);\n return fieldNames.length === 1 && fields[fieldNames[0]].name === '__fake';\n }\n return false;\n}\nfunction getBuiltInForStub(type) {\n switch (type.name) {\n case GraphQLInt.name:\n return GraphQLInt;\n case GraphQLFloat.name:\n return GraphQLFloat;\n case GraphQLString.name:\n return GraphQLString;\n case GraphQLBoolean.name:\n return GraphQLBoolean;\n case GraphQLID.name:\n return GraphQLID;\n default:\n return type;\n }\n}\n\nfunction rewireTypes(originalTypeMap, directives) {\n const referenceTypeMap = Object.create(null);\n Object.keys(originalTypeMap).forEach(typeName => {\n referenceTypeMap[typeName] = originalTypeMap[typeName];\n });\n const newTypeMap = Object.create(null);\n Object.keys(referenceTypeMap).forEach(typeName => {\n const namedType = referenceTypeMap[typeName];\n if (namedType == null || typeName.startsWith('__')) {\n return;\n }\n const newName = namedType.name;\n if (newName.startsWith('__')) {\n return;\n }\n if (newTypeMap[newName] != null) {\n throw new Error(`Duplicate schema type name ${newName}`);\n }\n newTypeMap[newName] = namedType;\n });\n Object.keys(newTypeMap).forEach(typeName => {\n newTypeMap[typeName] = rewireNamedType(newTypeMap[typeName]);\n });\n const newDirectives = directives.map(directive => rewireDirective(directive));\n return {\n typeMap: newTypeMap,\n directives: newDirectives,\n };\n function rewireDirective(directive) {\n if (isSpecifiedDirective(directive)) {\n return directive;\n }\n const directiveConfig = directive.toConfig();\n directiveConfig.args = rewireArgs(directiveConfig.args);\n return new GraphQLDirective(directiveConfig);\n }\n function rewireArgs(args) {\n const rewiredArgs = {};\n Object.keys(args).forEach(argName => {\n const arg = args[argName];\n const rewiredArgType = rewireType(arg.type);\n if (rewiredArgType != null) {\n arg.type = rewiredArgType;\n rewiredArgs[argName] = arg;\n }\n });\n return rewiredArgs;\n }\n function rewireNamedType(type) {\n if (isObjectType(type)) {\n const config = type.toConfig();\n const newConfig = {\n ...config,\n fields: () => rewireFields(config.fields),\n interfaces: () => rewireNamedTypes(config.interfaces),\n };\n return new GraphQLObjectType(newConfig);\n }\n else if (isInterfaceType(type)) {\n const config = type.toConfig();\n const newConfig = {\n ...config,\n fields: () => rewireFields(config.fields),\n };\n if ('interfaces' in newConfig) {\n newConfig.interfaces = () => rewireNamedTypes(config.interfaces);\n }\n return new GraphQLInterfaceType(newConfig);\n }\n else if (isUnionType(type)) {\n const config = type.toConfig();\n const newConfig = {\n ...config,\n types: () => rewireNamedTypes(config.types),\n };\n return new GraphQLUnionType(newConfig);\n }\n else if (isInputObjectType(type)) {\n const config = type.toConfig();\n const newConfig = {\n ...config,\n fields: () => rewireInputFields(config.fields),\n };\n return new GraphQLInputObjectType(newConfig);\n }\n else if (isEnumType(type)) {\n const enumConfig = type.toConfig();\n return new GraphQLEnumType(enumConfig);\n }\n else if (isScalarType(type)) {\n if (isSpecifiedScalarType(type)) {\n return type;\n }\n const scalarConfig = type.toConfig();\n return new GraphQLScalarType(scalarConfig);\n }\n throw new Error(`Unexpected schema type: ${type}`);\n }\n function rewireFields(fields) {\n const rewiredFields = {};\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n const rewiredFieldType = rewireType(field.type);\n if (rewiredFieldType != null) {\n field.type = rewiredFieldType;\n field.args = rewireArgs(field.args);\n rewiredFields[fieldName] = field;\n }\n });\n return rewiredFields;\n }\n function rewireInputFields(fields) {\n const rewiredFields = {};\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n const rewiredFieldType = rewireType(field.type);\n if (rewiredFieldType != null) {\n field.type = rewiredFieldType;\n rewiredFields[fieldName] = field;\n }\n });\n return rewiredFields;\n }\n function rewireNamedTypes(namedTypes) {\n const rewiredTypes = [];\n namedTypes.forEach(namedType => {\n const rewiredType = rewireType(namedType);\n if (rewiredType != null) {\n rewiredTypes.push(rewiredType);\n }\n });\n return rewiredTypes;\n }\n function rewireType(type) {\n if (isListType(type)) {\n const rewiredType = rewireType(type.ofType);\n return rewiredType != null ? new GraphQLList(rewiredType) : null;\n }\n else if (isNonNullType(type)) {\n const rewiredType = rewireType(type.ofType);\n return rewiredType != null ? new GraphQLNonNull(rewiredType) : null;\n }\n else if (isNamedType(type)) {\n let rewiredType = referenceTypeMap[type.name];\n if (rewiredType === undefined) {\n rewiredType = isNamedStub(type) ? getBuiltInForStub(type) : rewireNamedType(type);\n newTypeMap[rewiredType.name] = referenceTypeMap[type.name] = rewiredType;\n }\n return rewiredType != null ? newTypeMap[rewiredType.name] : null;\n }\n return null;\n }\n}\n\nfunction transformInputValue(type, value, inputLeafValueTransformer = null, inputObjectValueTransformer = null) {\n if (value == null) {\n return value;\n }\n const nullableType = getNullableType(type);\n if (isLeafType(nullableType)) {\n return inputLeafValueTransformer != null ? inputLeafValueTransformer(nullableType, value) : value;\n }\n else if (isListType(nullableType)) {\n return value.map((listMember) => transformInputValue(nullableType.ofType, listMember, inputLeafValueTransformer, inputObjectValueTransformer));\n }\n else if (isInputObjectType(nullableType)) {\n const fields = nullableType.getFields();\n const newValue = {};\n Object.keys(value).forEach(key => {\n const field = fields[key];\n if (field != null) {\n newValue[key] = transformInputValue(field.type, value[key], inputLeafValueTransformer, inputObjectValueTransformer);\n }\n });\n return inputObjectValueTransformer != null ? inputObjectValueTransformer(nullableType, newValue) : newValue;\n }\n // unreachable, no other possible return value\n}\nfunction serializeInputValue(type, value) {\n return transformInputValue(type, value, (t, v) => t.serialize(v));\n}\nfunction parseInputValue(type, value) {\n return transformInputValue(type, value, (t, v) => t.parseValue(v));\n}\nfunction parseInputValueLiteral(type, value) {\n return transformInputValue(type, value, (t, v) => t.parseLiteral(v, {}));\n}\n\nfunction mapSchema(schema, schemaMapper = {}) {\n const originalTypeMap = schema.getTypeMap();\n let newTypeMap = mapDefaultValues(originalTypeMap, schema, serializeInputValue);\n newTypeMap = mapTypes(newTypeMap, schema, schemaMapper, type => isLeafType(type));\n newTypeMap = mapEnumValues(newTypeMap, schema, schemaMapper);\n newTypeMap = mapDefaultValues(newTypeMap, schema, parseInputValue);\n newTypeMap = mapTypes(newTypeMap, schema, schemaMapper, type => !isLeafType(type));\n newTypeMap = mapFields(newTypeMap, schema, schemaMapper);\n newTypeMap = mapArguments(newTypeMap, schema, schemaMapper);\n const originalDirectives = schema.getDirectives();\n const newDirectives = mapDirectives(originalDirectives, schema, schemaMapper);\n const queryType = schema.getQueryType();\n const mutationType = schema.getMutationType();\n const subscriptionType = schema.getSubscriptionType();\n const newQueryTypeName = queryType != null ? (newTypeMap[queryType.name] != null ? newTypeMap[queryType.name].name : undefined) : undefined;\n const newMutationTypeName = mutationType != null\n ? newTypeMap[mutationType.name] != null\n ? newTypeMap[mutationType.name].name\n : undefined\n : undefined;\n const newSubscriptionTypeName = subscriptionType != null\n ? newTypeMap[subscriptionType.name] != null\n ? newTypeMap[subscriptionType.name].name\n : undefined\n : undefined;\n const { typeMap, directives } = rewireTypes(newTypeMap, newDirectives);\n return new GraphQLSchema({\n ...schema.toConfig(),\n query: newQueryTypeName ? typeMap[newQueryTypeName] : undefined,\n mutation: newMutationTypeName ? typeMap[newMutationTypeName] : undefined,\n subscription: newSubscriptionTypeName != null ? typeMap[newSubscriptionTypeName] : undefined,\n types: Object.keys(typeMap).map(typeName => typeMap[typeName]),\n directives,\n });\n}\nfunction mapTypes(originalTypeMap, schema, schemaMapper, testFn = () => true) {\n const newTypeMap = {};\n Object.keys(originalTypeMap).forEach(typeName => {\n if (!typeName.startsWith('__')) {\n const originalType = originalTypeMap[typeName];\n if (originalType == null || !testFn(originalType)) {\n newTypeMap[typeName] = originalType;\n return;\n }\n const typeMapper = getTypeMapper(schema, schemaMapper, typeName);\n if (typeMapper == null) {\n newTypeMap[typeName] = originalType;\n return;\n }\n const maybeNewType = typeMapper(originalType, schema);\n if (maybeNewType === undefined) {\n newTypeMap[typeName] = originalType;\n return;\n }\n newTypeMap[typeName] = maybeNewType;\n }\n });\n return newTypeMap;\n}\nfunction mapEnumValues(originalTypeMap, schema, schemaMapper) {\n const enumValueMapper = getEnumValueMapper(schemaMapper);\n if (!enumValueMapper) {\n return originalTypeMap;\n }\n return mapTypes(originalTypeMap, schema, {\n [MapperKind.ENUM_TYPE]: type => {\n const config = type.toConfig();\n const originalEnumValueConfigMap = config.values;\n const newEnumValueConfigMap = {};\n Object.keys(originalEnumValueConfigMap).forEach(externalValue => {\n const originalEnumValueConfig = originalEnumValueConfigMap[externalValue];\n const mappedEnumValue = enumValueMapper(originalEnumValueConfig, type.name, schema, externalValue);\n if (mappedEnumValue === undefined) {\n newEnumValueConfigMap[externalValue] = originalEnumValueConfig;\n }\n else if (Array.isArray(mappedEnumValue)) {\n const [newExternalValue, newEnumValueConfig] = mappedEnumValue;\n newEnumValueConfigMap[newExternalValue] =\n newEnumValueConfig === undefined ? originalEnumValueConfig : newEnumValueConfig;\n }\n else if (mappedEnumValue !== null) {\n newEnumValueConfigMap[externalValue] = mappedEnumValue;\n }\n });\n return correctASTNodes(new GraphQLEnumType({\n ...config,\n values: newEnumValueConfigMap,\n }));\n },\n }, type => isEnumType(type));\n}\nfunction mapDefaultValues(originalTypeMap, schema, fn) {\n const newTypeMap = mapArguments(originalTypeMap, schema, {\n [MapperKind.ARGUMENT]: argumentConfig => {\n if (argumentConfig.defaultValue === undefined) {\n return argumentConfig;\n }\n const maybeNewType = getNewType(originalTypeMap, argumentConfig.type);\n if (maybeNewType != null) {\n return {\n ...argumentConfig,\n defaultValue: fn(maybeNewType, argumentConfig.defaultValue),\n };\n }\n },\n });\n return mapFields(newTypeMap, schema, {\n [MapperKind.INPUT_OBJECT_FIELD]: inputFieldConfig => {\n if (inputFieldConfig.defaultValue === undefined) {\n return inputFieldConfig;\n }\n const maybeNewType = getNewType(newTypeMap, inputFieldConfig.type);\n if (maybeNewType != null) {\n return {\n ...inputFieldConfig,\n defaultValue: fn(maybeNewType, inputFieldConfig.defaultValue),\n };\n }\n },\n });\n}\nfunction getNewType(newTypeMap, type) {\n if (isListType(type)) {\n const newType = getNewType(newTypeMap, type.ofType);\n return newType != null ? new GraphQLList(newType) : null;\n }\n else if (isNonNullType(type)) {\n const newType = getNewType(newTypeMap, type.ofType);\n return newType != null ? new GraphQLNonNull(newType) : null;\n }\n else if (isNamedType(type)) {\n const newType = newTypeMap[type.name];\n return newType != null ? newType : null;\n }\n return null;\n}\nfunction mapFields(originalTypeMap, schema, schemaMapper) {\n const newTypeMap = {};\n Object.keys(originalTypeMap).forEach(typeName => {\n if (!typeName.startsWith('__')) {\n const originalType = originalTypeMap[typeName];\n if (!isObjectType(originalType) && !isInterfaceType(originalType) && !isInputObjectType(originalType)) {\n newTypeMap[typeName] = originalType;\n return;\n }\n const fieldMapper = getFieldMapper(schema, schemaMapper, typeName);\n if (fieldMapper == null) {\n newTypeMap[typeName] = originalType;\n return;\n }\n const config = originalType.toConfig();\n const originalFieldConfigMap = config.fields;\n const newFieldConfigMap = {};\n Object.keys(originalFieldConfigMap).forEach(fieldName => {\n const originalFieldConfig = originalFieldConfigMap[fieldName];\n const mappedField = fieldMapper(originalFieldConfig, fieldName, typeName, schema);\n if (mappedField === undefined) {\n newFieldConfigMap[fieldName] = originalFieldConfig;\n }\n else if (Array.isArray(mappedField)) {\n const [newFieldName, newFieldConfig] = mappedField;\n if (newFieldConfig.astNode != null) {\n newFieldConfig.astNode = {\n ...newFieldConfig.astNode,\n name: {\n ...newFieldConfig.astNode.name,\n value: newFieldName,\n },\n };\n }\n newFieldConfigMap[newFieldName] = newFieldConfig === undefined ? originalFieldConfig : newFieldConfig;\n }\n else if (mappedField !== null) {\n newFieldConfigMap[fieldName] = mappedField;\n }\n });\n if (isObjectType(originalType)) {\n newTypeMap[typeName] = correctASTNodes(new GraphQLObjectType({\n ...config,\n fields: newFieldConfigMap,\n }));\n }\n else if (isInterfaceType(originalType)) {\n newTypeMap[typeName] = correctASTNodes(new GraphQLInterfaceType({\n ...config,\n fields: newFieldConfigMap,\n }));\n }\n else {\n newTypeMap[typeName] = correctASTNodes(new GraphQLInputObjectType({\n ...config,\n fields: newFieldConfigMap,\n }));\n }\n }\n });\n return newTypeMap;\n}\nfunction mapArguments(originalTypeMap, schema, schemaMapper) {\n const newTypeMap = {};\n Object.keys(originalTypeMap).forEach(typeName => {\n if (!typeName.startsWith('__')) {\n const originalType = originalTypeMap[typeName];\n if (!isObjectType(originalType) && !isInterfaceType(originalType)) {\n newTypeMap[typeName] = originalType;\n return;\n }\n const argumentMapper = getArgumentMapper(schemaMapper);\n if (argumentMapper == null) {\n newTypeMap[typeName] = originalType;\n return;\n }\n const config = originalType.toConfig();\n const originalFieldConfigMap = config.fields;\n const newFieldConfigMap = {};\n Object.keys(originalFieldConfigMap).forEach(fieldName => {\n const originalFieldConfig = originalFieldConfigMap[fieldName];\n const originalArgumentConfigMap = originalFieldConfig.args;\n if (originalArgumentConfigMap == null) {\n newFieldConfigMap[fieldName] = originalFieldConfig;\n return;\n }\n const argumentNames = Object.keys(originalArgumentConfigMap);\n if (!argumentNames.length) {\n newFieldConfigMap[fieldName] = originalFieldConfig;\n return;\n }\n const newArgumentConfigMap = {};\n argumentNames.forEach(argumentName => {\n const originalArgumentConfig = originalArgumentConfigMap[argumentName];\n const mappedArgument = argumentMapper(originalArgumentConfig, fieldName, typeName, schema);\n if (mappedArgument === undefined) {\n newArgumentConfigMap[argumentName] = originalArgumentConfig;\n }\n else if (Array.isArray(mappedArgument)) {\n const [newArgumentName, newArgumentConfig] = mappedArgument;\n newArgumentConfigMap[newArgumentName] = newArgumentConfig;\n }\n else if (mappedArgument !== null) {\n newArgumentConfigMap[argumentName] = mappedArgument;\n }\n });\n newFieldConfigMap[fieldName] = {\n ...originalFieldConfig,\n args: newArgumentConfigMap,\n };\n });\n if (isObjectType(originalType)) {\n newTypeMap[typeName] = new GraphQLObjectType({\n ...config,\n fields: newFieldConfigMap,\n });\n }\n else if (isInterfaceType(originalType)) {\n newTypeMap[typeName] = new GraphQLInterfaceType({\n ...config,\n fields: newFieldConfigMap,\n });\n }\n else {\n newTypeMap[typeName] = new GraphQLInputObjectType({\n ...config,\n fields: newFieldConfigMap,\n });\n }\n }\n });\n return newTypeMap;\n}\nfunction mapDirectives(originalDirectives, schema, schemaMapper) {\n const directiveMapper = getDirectiveMapper(schemaMapper);\n if (directiveMapper == null) {\n return originalDirectives.slice();\n }\n const newDirectives = [];\n originalDirectives.forEach(directive => {\n const mappedDirective = directiveMapper(directive, schema);\n if (mappedDirective === undefined) {\n newDirectives.push(directive);\n }\n else if (mappedDirective !== null) {\n newDirectives.push(mappedDirective);\n }\n });\n return newDirectives;\n}\nfunction getTypeSpecifiers(schema, typeName) {\n const type = schema.getType(typeName);\n const specifiers = [MapperKind.TYPE];\n if (isObjectType(type)) {\n specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.OBJECT_TYPE);\n const query = schema.getQueryType();\n const mutation = schema.getMutationType();\n const subscription = schema.getSubscriptionType();\n if (query != null && typeName === query.name) {\n specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.QUERY);\n }\n else if (mutation != null && typeName === mutation.name) {\n specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.MUTATION);\n }\n else if (subscription != null && typeName === subscription.name) {\n specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.SUBSCRIPTION);\n }\n }\n else if (isInputObjectType(type)) {\n specifiers.push(MapperKind.INPUT_OBJECT_TYPE);\n }\n else if (isInterfaceType(type)) {\n specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.ABSTRACT_TYPE, MapperKind.INTERFACE_TYPE);\n }\n else if (isUnionType(type)) {\n specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.ABSTRACT_TYPE, MapperKind.UNION_TYPE);\n }\n else if (isEnumType(type)) {\n specifiers.push(MapperKind.ENUM_TYPE);\n }\n else if (isScalarType(type)) {\n specifiers.push(MapperKind.SCALAR_TYPE);\n }\n return specifiers;\n}\nfunction getTypeMapper(schema, schemaMapper, typeName) {\n const specifiers = getTypeSpecifiers(schema, typeName);\n let typeMapper;\n const stack = [...specifiers];\n while (!typeMapper && stack.length > 0) {\n const next = stack.pop();\n typeMapper = schemaMapper[next];\n }\n return typeMapper != null ? typeMapper : null;\n}\nfunction getFieldSpecifiers(schema, typeName) {\n const type = schema.getType(typeName);\n const specifiers = [MapperKind.FIELD];\n if (isObjectType(type)) {\n specifiers.push(MapperKind.COMPOSITE_FIELD, MapperKind.OBJECT_FIELD);\n const query = schema.getQueryType();\n const mutation = schema.getMutationType();\n const subscription = schema.getSubscriptionType();\n if (query != null && typeName === query.name) {\n specifiers.push(MapperKind.ROOT_FIELD, MapperKind.QUERY_ROOT_FIELD);\n }\n else if (mutation != null && typeName === mutation.name) {\n specifiers.push(MapperKind.ROOT_FIELD, MapperKind.MUTATION_ROOT_FIELD);\n }\n else if (subscription != null && typeName === subscription.name) {\n specifiers.push(MapperKind.ROOT_FIELD, MapperKind.SUBSCRIPTION_ROOT_FIELD);\n }\n }\n else if (isInterfaceType(type)) {\n specifiers.push(MapperKind.COMPOSITE_FIELD, MapperKind.INTERFACE_FIELD);\n }\n else if (isInputObjectType(type)) {\n specifiers.push(MapperKind.INPUT_OBJECT_FIELD);\n }\n return specifiers;\n}\nfunction getFieldMapper(schema, schemaMapper, typeName) {\n const specifiers = getFieldSpecifiers(schema, typeName);\n let fieldMapper;\n const stack = [...specifiers];\n while (!fieldMapper && stack.length > 0) {\n const next = stack.pop();\n fieldMapper = schemaMapper[next];\n }\n return fieldMapper != null ? fieldMapper : null;\n}\nfunction getArgumentMapper(schemaMapper) {\n const argumentMapper = schemaMapper[MapperKind.ARGUMENT];\n return argumentMapper != null ? argumentMapper : null;\n}\nfunction getDirectiveMapper(schemaMapper) {\n const directiveMapper = schemaMapper[MapperKind.DIRECTIVE];\n return directiveMapper != null ? directiveMapper : null;\n}\nfunction getEnumValueMapper(schemaMapper) {\n const enumValueMapper = schemaMapper[MapperKind.ENUM_VALUE];\n return enumValueMapper != null ? enumValueMapper : null;\n}\nfunction correctASTNodes(type) {\n if (isObjectType(type)) {\n const config = type.toConfig();\n if (config.astNode != null) {\n const fields = [];\n Object.values(config.fields).forEach(fieldConfig => {\n if (fieldConfig.astNode != null) {\n fields.push(fieldConfig.astNode);\n }\n });\n config.astNode = {\n ...config.astNode,\n kind: Kind.OBJECT_TYPE_DEFINITION,\n fields,\n };\n }\n if (config.extensionASTNodes != null) {\n config.extensionASTNodes = config.extensionASTNodes.map(node => ({\n ...node,\n kind: Kind.OBJECT_TYPE_EXTENSION,\n fields: undefined,\n }));\n }\n return new GraphQLObjectType(config);\n }\n else if (isInterfaceType(type)) {\n const config = type.toConfig();\n if (config.astNode != null) {\n const fields = [];\n Object.values(config.fields).forEach(fieldConfig => {\n if (fieldConfig.astNode != null) {\n fields.push(fieldConfig.astNode);\n }\n });\n config.astNode = {\n ...config.astNode,\n kind: Kind.INTERFACE_TYPE_DEFINITION,\n fields,\n };\n }\n if (config.extensionASTNodes != null) {\n config.extensionASTNodes = config.extensionASTNodes.map(node => ({\n ...node,\n kind: Kind.INTERFACE_TYPE_EXTENSION,\n fields: undefined,\n }));\n }\n return new GraphQLInterfaceType(config);\n }\n else if (isInputObjectType(type)) {\n const config = type.toConfig();\n if (config.astNode != null) {\n const fields = [];\n Object.values(config.fields).forEach(fieldConfig => {\n if (fieldConfig.astNode != null) {\n fields.push(fieldConfig.astNode);\n }\n });\n config.astNode = {\n ...config.astNode,\n kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,\n fields,\n };\n }\n if (config.extensionASTNodes != null) {\n config.extensionASTNodes = config.extensionASTNodes.map(node => ({\n ...node,\n kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n fields: undefined,\n }));\n }\n return new GraphQLInputObjectType(config);\n }\n else if (isEnumType(type)) {\n const config = type.toConfig();\n if (config.astNode != null) {\n const values = [];\n Object.values(config.values).forEach(enumValueConfig => {\n if (enumValueConfig.astNode != null) {\n values.push(enumValueConfig.astNode);\n }\n });\n config.astNode = {\n ...config.astNode,\n values,\n };\n }\n if (config.extensionASTNodes != null) {\n config.extensionASTNodes = config.extensionASTNodes.map(node => ({\n ...node,\n values: undefined,\n }));\n }\n return new GraphQLEnumType(config);\n }\n else {\n return type;\n }\n}\n\nfunction filterSchema({ schema, typeFilter = () => true, fieldFilter = undefined, rootFieldFilter = undefined, objectFieldFilter = undefined, interfaceFieldFilter = undefined, inputObjectFieldFilter = undefined, argumentFilter = undefined, }) {\n const filteredSchema = mapSchema(schema, {\n [MapperKind.QUERY]: (type) => filterRootFields(type, 'Query', rootFieldFilter, argumentFilter),\n [MapperKind.MUTATION]: (type) => filterRootFields(type, 'Mutation', rootFieldFilter, argumentFilter),\n [MapperKind.SUBSCRIPTION]: (type) => filterRootFields(type, 'Subscription', rootFieldFilter, argumentFilter),\n [MapperKind.OBJECT_TYPE]: (type) => typeFilter(type.name, type)\n ? filterElementFields(GraphQLObjectType, type, objectFieldFilter || fieldFilter, argumentFilter)\n : null,\n [MapperKind.INTERFACE_TYPE]: (type) => typeFilter(type.name, type)\n ? filterElementFields(GraphQLInterfaceType, type, interfaceFieldFilter || fieldFilter, argumentFilter)\n : null,\n [MapperKind.INPUT_OBJECT_TYPE]: (type) => typeFilter(type.name, type)\n ? filterElementFields(GraphQLInputObjectType, type, inputObjectFieldFilter || fieldFilter)\n : null,\n [MapperKind.UNION_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),\n [MapperKind.ENUM_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),\n [MapperKind.SCALAR_TYPE]: (type) => (typeFilter(type.name, type) ? undefined : null),\n });\n return filteredSchema;\n}\nfunction filterRootFields(type, operation, rootFieldFilter, argumentFilter) {\n if (rootFieldFilter || argumentFilter) {\n const config = type.toConfig();\n Object.entries(config.fields).forEach(([fieldName, field]) => {\n if (rootFieldFilter && !rootFieldFilter(operation, fieldName, config.fields[fieldName])) {\n delete config.fields[fieldName];\n }\n else if (argumentFilter) {\n for (const argName of Object.keys(field.args)) {\n if (!argumentFilter(operation, fieldName, argName, field.args[argName])) {\n delete field.args[argName];\n }\n }\n }\n });\n return new GraphQLObjectType(config);\n }\n return type;\n}\nfunction filterElementFields(ElementConstructor, type, fieldFilter, argumentFilter) {\n if (fieldFilter || argumentFilter) {\n const config = type.toConfig();\n Object.entries(config.fields).forEach(([fieldName, field]) => {\n if (fieldFilter && !fieldFilter(type.name, fieldName, config.fields[fieldName])) {\n delete config.fields[fieldName];\n }\n else if (argumentFilter && 'args' in field) {\n for (const argName of Object.keys(field.args)) {\n if (!argumentFilter(type.name, fieldName, argName, field.args[argName])) {\n delete field.args[argName];\n }\n }\n }\n });\n return new ElementConstructor(config);\n }\n}\n\nfunction cloneDirective(directive) {\n return isSpecifiedDirective(directive) ? directive : new GraphQLDirective(directive.toConfig());\n}\nfunction cloneType(type) {\n if (isObjectType(type)) {\n const config = type.toConfig();\n return new GraphQLObjectType({\n ...config,\n interfaces: typeof config.interfaces === 'function' ? config.interfaces : config.interfaces.slice(),\n });\n }\n else if (isInterfaceType(type)) {\n const config = type.toConfig();\n const newConfig = {\n ...config,\n interfaces: [...((typeof config.interfaces === 'function' ? config.interfaces() : config.interfaces) || [])],\n };\n return new GraphQLInterfaceType(newConfig);\n }\n else if (isUnionType(type)) {\n const config = type.toConfig();\n return new GraphQLUnionType({\n ...config,\n types: config.types.slice(),\n });\n }\n else if (isInputObjectType(type)) {\n return new GraphQLInputObjectType(type.toConfig());\n }\n else if (isEnumType(type)) {\n return new GraphQLEnumType(type.toConfig());\n }\n else if (isScalarType(type)) {\n return isSpecifiedScalarType(type) ? type : new GraphQLScalarType(type.toConfig());\n }\n throw new Error(`Invalid type ${type}`);\n}\nfunction cloneSchema(schema) {\n return mapSchema(schema);\n}\n\n// Update any references to named schema types that disagree with the named\n// types found in schema.getTypeMap().\n//\n// healSchema and its callers (visitSchema/visitSchemaDirectives) all modify the schema in place.\n// Therefore, private variables (such as the stored implementation map and the proper root types)\n// are not updated.\n//\n// If this causes issues, the schema could be more aggressively healed as follows:\n//\n// healSchema(schema);\n// const config = schema.toConfig()\n// const healedSchema = new GraphQLSchema({\n// ...config,\n// query: schema.getType('<desired new root query type name>'),\n// mutation: schema.getType('<desired new root mutation type name>'),\n// subscription: schema.getType('<desired new root subscription type name>'),\n// });\n//\n// One can then also -- if necessary -- assign the correct private variables to the initial schema\n// as follows:\n// Object.assign(schema, healedSchema);\n//\n// These steps are not taken automatically to preserve backwards compatibility with graphql-tools v4.\n// See https://github.com/ardatan/graphql-tools/issues/1462\n//\n// They were briefly taken in v5, but can now be phased out as they were only required when other\n// areas of the codebase were using healSchema and visitSchema more extensively.\n//\nfunction healSchema(schema) {\n healTypes(schema.getTypeMap(), schema.getDirectives());\n return schema;\n}\nfunction healTypes(originalTypeMap, directives) {\n const actualNamedTypeMap = Object.create(null);\n // If any of the .name properties of the GraphQLNamedType objects in\n // schema.getTypeMap() have changed, the keys of the type map need to\n // be updated accordingly.\n Object.entries(originalTypeMap).forEach(([typeName, namedType]) => {\n if (namedType == null || typeName.startsWith('__')) {\n return;\n }\n const actualName = namedType.name;\n if (actualName.startsWith('__')) {\n return;\n }\n if (actualName in actualNamedTypeMap) {\n throw new Error(`Duplicate schema type name ${actualName}`);\n }\n actualNamedTypeMap[actualName] = namedType;\n // Note: we are deliberately leaving namedType in the schema by its\n // original name (which might be different from actualName), so that\n // references by that name can be healed.\n });\n // Now add back every named type by its actual name.\n Object.entries(actualNamedTypeMap).forEach(([typeName, namedType]) => {\n originalTypeMap[typeName] = namedType;\n });\n // Directive declaration argument types can refer to named types.\n directives.forEach((decl) => {\n decl.args = decl.args.filter(arg => {\n arg.type = healType(arg.type);\n return arg.type !== null;\n });\n });\n Object.entries(originalTypeMap).forEach(([typeName, namedType]) => {\n // Heal all named types, except for dangling references, kept only to redirect.\n if (!typeName.startsWith('__') && typeName in actualNamedTypeMap) {\n if (namedType != null) {\n healNamedType(namedType);\n }\n }\n });\n for (const typeName of Object.keys(originalTypeMap)) {\n if (!typeName.startsWith('__') && !(typeName in actualNamedTypeMap)) {\n delete originalTypeMap[typeName];\n }\n }\n function healNamedType(type) {\n if (isObjectType(type)) {\n healFields(type);\n healInterfaces(type);\n return;\n }\n else if (isInterfaceType(type)) {\n healFields(type);\n if ('getInterfaces' in type) {\n healInterfaces(type);\n }\n return;\n }\n else if (isUnionType(type)) {\n healUnderlyingTypes(type);\n return;\n }\n else if (isInputObjectType(type)) {\n healInputFields(type);\n return;\n }\n else if (isLeafType(type)) {\n return;\n }\n throw new Error(`Unexpected schema type: ${type}`);\n }\n function healFields(type) {\n const fieldMap = type.getFields();\n for (const [key, field] of Object.entries(fieldMap)) {\n field.args\n .map(arg => {\n arg.type = healType(arg.type);\n return arg.type === null ? null : arg;\n })\n .filter(Boolean);\n field.type = healType(field.type);\n if (field.type === null) {\n delete fieldMap[key];\n }\n }\n }\n function healInterfaces(type) {\n if ('getInterfaces' in type) {\n const interfaces = type.getInterfaces();\n interfaces.push(...interfaces\n .splice(0)\n .map(iface => healType(iface))\n .filter(Boolean));\n }\n }\n function healInputFields(type) {\n const fieldMap = type.getFields();\n for (const [key, field] of Object.entries(fieldMap)) {\n field.type = healType(field.type);\n if (field.type === null) {\n delete fieldMap[key];\n }\n }\n }\n function healUnderlyingTypes(type) {\n const types = type.getTypes();\n types.push(...types\n .splice(0)\n .map(t => healType(t))\n .filter(Boolean));\n }\n function healType(type) {\n // Unwrap the two known wrapper types\n if (isListType(type)) {\n const healedType = healType(type.ofType);\n return healedType != null ? new GraphQLList(healedType) : null;\n }\n else if (isNonNullType(type)) {\n const healedType = healType(type.ofType);\n return healedType != null ? new GraphQLNonNull(healedType) : null;\n }\n else if (isNamedType(type)) {\n // If a type annotation on a field or an argument or a union member is\n // any `GraphQLNamedType` with a `name`, then it must end up identical\n // to `schema.getType(name)`, since `schema.getTypeMap()` is the source\n // of truth for all named schema types.\n // Note that new types can still be simply added by adding a field, as\n // the official type will be undefined, not null.\n const officialType = originalTypeMap[type.name];\n if (officialType && type !== officialType) {\n return officialType;\n }\n }\n return type;\n }\n}\n\n// Abstract base class of any visitor implementation, defining the available\n// visitor methods along with their parameter types, and providing a static\n// helper function for determining whether a subclass implements a given\n// visitor method, as opposed to inheriting one of the stubs defined here.\nclass SchemaVisitor {\n // Determine if this SchemaVisitor (sub)class implements a particular\n // visitor method.\n static implementsVisitorMethod(methodName) {\n if (!methodName.startsWith('visit')) {\n return false;\n }\n const method = this.prototype[methodName];\n if (typeof method !== 'function') {\n return false;\n }\n if (this.name === 'SchemaVisitor') {\n // The SchemaVisitor class implements every visitor method.\n return true;\n }\n const stub = SchemaVisitor.prototype[methodName];\n if (method === stub) {\n // If this.prototype[methodName] was just inherited from SchemaVisitor,\n // then this class does not really implement the method.\n return false;\n }\n return true;\n }\n // Concrete subclasses of SchemaVisitor should override one or more of these\n // visitor methods, in order to express their interest in handling certain\n // schema types/locations. Each method may return null to remove the given\n // type from the schema, a non-null value of the same type to update the\n // type in the schema, or nothing to leave the type as it was.\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n visitSchema(_schema) { }\n visitScalar(_scalar\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n ) { }\n visitObject(_object\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n ) { }\n visitFieldDefinition(_field, _details\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n ) { }\n visitArgumentDefinition(_argument, _details\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n ) { }\n visitInterface(_iface\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n ) { }\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n visitUnion(_union) { }\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n visitEnum(_type) { }\n visitEnumValue(_value, _details\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n ) { }\n visitInputObject(_object\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n ) { }\n visitInputFieldDefinition(_field, _details\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n ) { }\n}\n\nfunction isSchemaVisitor(obj) {\n if ('schema' in obj && isSchema(obj.schema)) {\n if ('visitSchema' in obj && typeof obj.visitSchema === 'function') {\n return true;\n }\n }\n return false;\n}\n// Generic function for visiting GraphQLSchema objects.\nfunction visitSchema(schema, \n// To accommodate as many different visitor patterns as possible, the\n// visitSchema function does not simply accept a single instance of the\n// SchemaVisitor class, but instead accepts a function that takes the\n// current VisitableSchemaType object and the name of a visitor method and\n// returns an array of SchemaVisitor instances that implement the visitor\n// method and have an interest in handling the given VisitableSchemaType\n// object. In the simplest case, this function can always return an array\n// containing a single visitor object, without even looking at the type or\n// methodName parameters. In other cases, this function might sometimes\n// return an empty array to indicate there are no visitors that should be\n// applied to the given VisitableSchemaType object. For an example of a\n// visitor pattern that benefits from this abstraction, see the\n// SchemaDirectiveVisitor class below.\nvisitorOrVisitorSelector) {\n const visitorSelector = typeof visitorOrVisitorSelector === 'function' ? visitorOrVisitorSelector : () => visitorOrVisitorSelector;\n // Helper function that calls visitorSelector and applies the resulting\n // visitors to the given type, with arguments [type, ...args].\n function callMethod(methodName, type, ...args) {\n let visitors = visitorSelector(type, methodName);\n visitors = Array.isArray(visitors) ? visitors : [visitors];\n let finalType = type;\n visitors.every(visitorOrVisitorDef => {\n let newType;\n if (isSchemaVisitor(visitorOrVisitorDef)) {\n newType = visitorOrVisitorDef[methodName](finalType, ...args);\n }\n else if (isNamedType(finalType) &&\n (methodName === 'visitScalar' ||\n methodName === 'visitEnum' ||\n methodName === 'visitObject' ||\n methodName === 'visitInputObject' ||\n methodName === 'visitUnion' ||\n methodName === 'visitInterface')) {\n const specifiers = getTypeSpecifiers$1(finalType, schema);\n const typeVisitor = getVisitor(visitorOrVisitorDef, specifiers);\n newType = typeVisitor != null ? typeVisitor(finalType, schema) : undefined;\n }\n if (typeof newType === 'undefined') {\n // Keep going without modifying type.\n return true;\n }\n if (methodName === 'visitSchema' || isSchema(finalType)) {\n throw new Error(`Method ${methodName} cannot replace schema with ${newType}`);\n }\n if (newType === null) {\n // Stop the loop and return null form callMethod, which will cause\n // the type to be removed from the schema.\n finalType = null;\n return false;\n }\n // Update type to the new type returned by the visitor method, so that\n // later directives will see the new type, and callMethod will return\n // the final type.\n finalType = newType;\n return true;\n });\n // If there were no directives for this type object, or if all visitor\n // methods returned nothing, type will be returned unmodified.\n return finalType;\n }\n // Recursive helper function that calls any appropriate visitor methods for\n // each object in the schema, then traverses the object's children (if any).\n function visit(type) {\n if (isSchema(type)) {\n // Unlike the other types, the root GraphQLSchema object cannot be\n // replaced by visitor methods, because that would make life very hard\n // for SchemaVisitor subclasses that rely on the original schema object.\n callMethod('visitSchema', type);\n const typeMap = type.getTypeMap();\n Object.entries(typeMap).forEach(([typeName, namedType]) => {\n if (!typeName.startsWith('__') && namedType != null) {\n // Call visit recursively to let it determine which concrete\n // subclass of GraphQLNamedType we found in the type map.\n // We do not use updateEachKey because we want to preserve\n // deleted types in the typeMap so that other types that reference\n // the deleted types can be healed.\n typeMap[typeName] = visit(namedType);\n }\n });\n return type;\n }\n if (isObjectType(type)) {\n // Note that callMethod('visitObject', type) may not actually call any\n // methods, if there are no @directive annotations associated with this\n // type, or if this SchemaDirectiveVisitor subclass does not override\n // the visitObject method.\n const newObject = callMethod('visitObject', type);\n if (newObject != null) {\n visitFields(newObject);\n }\n return newObject;\n }\n if (isInterfaceType(type)) {\n const newInterface = callMethod('visitInterface', type);\n if (newInterface != null) {\n visitFields(newInterface);\n }\n return newInterface;\n }\n if (isInputObjectType(type)) {\n const newInputObject = callMethod('visitInputObject', type);\n if (newInputObject != null) {\n const fieldMap = newInputObject.getFields();\n for (const key of Object.keys(fieldMap)) {\n fieldMap[key] = callMethod('visitInputFieldDefinition', fieldMap[key], {\n // Since we call a different method for input object fields, we\n // can't reuse the visitFields function here.\n objectType: newInputObject,\n });\n if (!fieldMap[key]) {\n delete fieldMap[key];\n }\n }\n }\n return newInputObject;\n }\n if (isScalarType(type)) {\n return callMethod('visitScalar', type);\n }\n if (isUnionType(type)) {\n return callMethod('visitUnion', type);\n }\n if (isEnumType(type)) {\n let newEnum = callMethod('visitEnum', type);\n if (newEnum != null) {\n const newValues = newEnum\n .getValues()\n .map(value => callMethod('visitEnumValue', value, {\n enumType: newEnum,\n }))\n .filter(Boolean);\n // Recreate the enum type if any of the values changed\n const valuesUpdated = newValues.some((value, index) => value !== newEnum.getValues()[index]);\n if (valuesUpdated) {\n newEnum = new GraphQLEnumType({\n ...newEnum.toConfig(),\n values: newValues.reduce((prev, value) => ({\n ...prev,\n [value.name]: {\n value: value.value,\n deprecationReason: value.deprecationReason,\n description: value.description,\n astNode: value.astNode,\n },\n }), {}),\n });\n }\n }\n return newEnum;\n }\n throw new Error(`Unexpected schema type: ${type}`);\n }\n function visitFields(type) {\n const fieldMap = type.getFields();\n for (const [key, field] of Object.entries(fieldMap)) {\n // It would be nice if we could call visit(field) recursively here, but\n // GraphQLField is merely a type, not a value that can be detected using\n // an instanceof check, so we have to visit the fields in this lexical\n // context, so that TypeScript can validate the call to\n // visitFieldDefinition.\n const newField = callMethod('visitFieldDefinition', field, {\n // While any field visitor needs a reference to the field object, some\n // field visitors may also need to know the enclosing (parent) type,\n // perhaps to determine if the parent is a GraphQLObjectType or a\n // GraphQLInterfaceType. To obtain a reference to the parent, a\n // visitor method can have a second parameter, which will be an object\n // with an .objectType property referring to the parent.\n objectType: type,\n });\n if ((newField === null || newField === void 0 ? void 0 : newField.args) != null) {\n newField.args = newField.args\n .map(arg => callMethod('visitArgumentDefinition', arg, {\n // Like visitFieldDefinition, visitArgumentDefinition takes a\n // second parameter that provides additional context, namely the\n // parent .field and grandparent .objectType. Remember that the\n // current GraphQLSchema is always available via this.schema.\n field: newField,\n objectType: type,\n }))\n .filter(Boolean);\n }\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (newField) {\n fieldMap[key] = newField;\n }\n else {\n delete fieldMap[key];\n }\n }\n }\n visit(schema);\n // Automatically update any references to named schema types replaced\n // during the traversal, so implementers don't have to worry about that.\n healSchema(schema);\n // Return schema for convenience, even though schema parameter has all updated types.\n return schema;\n}\nfunction getTypeSpecifiers$1(type, schema) {\n const specifiers = [VisitSchemaKind.TYPE];\n if (isObjectType(type)) {\n specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.OBJECT_TYPE);\n const query = schema.getQueryType();\n const mutation = schema.getMutationType();\n const subscription = schema.getSubscriptionType();\n if (type === query) {\n specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.QUERY);\n }\n else if (type === mutation) {\n specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.MUTATION);\n }\n else if (type === subscription) {\n specifiers.push(VisitSchemaKind.ROOT_OBJECT, VisitSchemaKind.SUBSCRIPTION);\n }\n }\n else if (isInputType(type)) {\n specifiers.push(VisitSchemaKind.INPUT_OBJECT_TYPE);\n }\n else if (isInterfaceType(type)) {\n specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.ABSTRACT_TYPE, VisitSchemaKind.INTERFACE_TYPE);\n }\n else if (isUnionType(type)) {\n specifiers.push(VisitSchemaKind.COMPOSITE_TYPE, VisitSchemaKind.ABSTRACT_TYPE, VisitSchemaKind.UNION_TYPE);\n }\n else if (isEnumType(type)) {\n specifiers.push(VisitSchemaKind.ENUM_TYPE);\n }\n else if (isScalarType(type)) {\n specifiers.push(VisitSchemaKind.SCALAR_TYPE);\n }\n return specifiers;\n}\nfunction getVisitor(visitorDef, specifiers) {\n let typeVisitor;\n const stack = [...specifiers];\n while (!typeVisitor && stack.length > 0) {\n const next = stack.pop();\n typeVisitor = visitorDef[next];\n }\n return typeVisitor != null ? typeVisitor : null;\n}\n\n// This class represents a reusable implementation of a @directive that may\n// appear in a GraphQL schema written in Schema Definition Language.\n//\n// By overriding one or more visit{Object,Union,...} methods, a subclass\n// registers interest in certain schema types, such as GraphQLObjectType,\n// GraphQLUnionType, etc. When SchemaDirectiveVisitor.visitSchemaDirectives is\n// called with a GraphQLSchema object and a map of visitor subclasses, the\n// overridden methods of those subclasses allow the visitors to obtain\n// references to any type objects that have @directives attached to them,\n// enabling visitors to inspect or modify the schema as appropriate.\n//\n// For example, if a directive called @rest(url: \"...\") appears after a field\n// definition, a SchemaDirectiveVisitor subclass could provide meaning to that\n// directive by overriding the visitFieldDefinition method (which receives a\n// GraphQLField parameter), and then the body of that visitor method could\n// manipulate the field's resolver function to fetch data from a REST endpoint\n// described by the url argument passed to the @rest directive:\n//\n// const typeDefs = `\n// type Query {\n// people: [Person] @rest(url: \"/api/v1/people\")\n// }`;\n//\n// const schema = makeExecutableSchema({ typeDefs });\n//\n// SchemaDirectiveVisitor.visitSchemaDirectives(schema, {\n// rest: class extends SchemaDirectiveVisitor {\n// public visitFieldDefinition(field: GraphQLField<any, any>) {\n// const { url } = this.args;\n// field.resolve = () => fetch(url);\n// }\n// }\n// });\n//\n// The subclass in this example is defined as an anonymous class expression,\n// for brevity. A truly reusable SchemaDirectiveVisitor would most likely be\n// defined in a library using a named class declaration, and then exported for\n// consumption by other modules and packages.\n//\n// See below for a complete list of overridable visitor methods, their\n// parameter types, and more details about the properties exposed by instances\n// of the SchemaDirectiveVisitor class.\nclass SchemaDirectiveVisitor extends SchemaVisitor {\n // Mark the constructor protected to enforce passing SchemaDirectiveVisitor\n // subclasses (not instances) to visitSchemaDirectives.\n constructor(config) {\n super();\n this.name = config.name;\n this.args = config.args;\n this.visitedType = config.visitedType;\n this.schema = config.schema;\n this.context = config.context;\n }\n // Override this method to return a custom GraphQLDirective (or modify one\n // already present in the schema) to enforce argument types, provide default\n // argument values, or specify schema locations where this @directive may\n // appear. By default, any declaration found in the schema will be returned.\n static getDirectiveDeclaration(directiveName, schema) {\n return schema.getDirective(directiveName);\n }\n // Call SchemaDirectiveVisitor.visitSchemaDirectives to visit every\n // @directive in the schema and create an appropriate SchemaDirectiveVisitor\n // instance to visit the object decorated by the @directive.\n static visitSchemaDirectives(schema, \n // The keys of this object correspond to directive names as they appear\n // in the schema, and the values should be subclasses (not instances!)\n // of the SchemaDirectiveVisitor class. This distinction is important\n // because a new SchemaDirectiveVisitor instance will be created each\n // time a matching directive is found in the schema AST, with arguments\n // and other metadata specific to that occurrence. To help prevent the\n // mistake of passing instances, the SchemaDirectiveVisitor constructor\n // method is marked as protected.\n directiveVisitors, \n // Optional context object that will be available to all visitor instances\n // via this.context. Defaults to an empty null-prototype object.\n context = Object.create(null), \n // The visitSchemaDirectives method returns a map from directive names to\n // lists of SchemaDirectiveVisitors created while visiting the schema.\n pathToDirectivesInExtensions = ['directives']) {\n // If the schema declares any directives for public consumption, record\n // them here so that we can properly coerce arguments when/if we encounter\n // an occurrence of the directive while walking the schema below.\n const declaredDirectives = this.getDeclaredDirectives(schema, directiveVisitors);\n // Map from directive names to lists of SchemaDirectiveVisitor instances\n // created while visiting the schema.\n const createdVisitors = Object.keys(directiveVisitors).reduce((prev, item) => ({\n ...prev,\n [item]: [],\n }), {});\n const directiveVisitorMap = Object.entries(directiveVisitors).reduce((prev, [key, value]) => ({\n ...prev,\n [key]: value,\n }), {});\n function visitorSelector(type, methodName) {\n var _a, _b;\n const directivesInExtensions = pathToDirectivesInExtensions.reduce((acc, pathSegment) => (acc == null ? acc : acc[pathSegment]), type === null || type === void 0 ? void 0 : type.extensions);\n const directives = Object.create(null);\n if (directivesInExtensions != null) {\n Object.entries(directivesInExtensions).forEach(([directiveName, directiveValue]) => {\n if (!directives[directiveName]) {\n directives[directiveName] = [directiveValue];\n }\n else {\n directives[directiveName].push([directiveValue]);\n }\n });\n }\n else {\n 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 : [];\n const extensionASTNodes = type.extensionASTNodes;\n if (extensionASTNodes != null) {\n extensionASTNodes.forEach(extensionASTNode => {\n if (extensionASTNode.directives != null) {\n directiveNodes = directiveNodes.concat(extensionASTNode.directives);\n }\n });\n }\n directiveNodes.forEach(directiveNode => {\n const directiveName = directiveNode.name.value;\n const decl = declaredDirectives[directiveName];\n let args;\n if (decl != null) {\n // If this directive was explicitly declared, use the declared\n // argument types (and any default values) to check, coerce, and/or\n // supply default values for the given arguments.\n args = getArgumentValues(decl, directiveNode);\n }\n else {\n // If this directive was not explicitly declared, just convert the\n // argument nodes to their corresponding JavaScript values.\n args = Object.create(null);\n if (directiveNode.arguments != null) {\n directiveNode.arguments.forEach(arg => {\n args[arg.name.value] = valueFromASTUntyped(arg.value);\n });\n }\n }\n if (!directives[directiveName]) {\n directives[directiveName] = [args];\n }\n else {\n directives[directiveName].push(args);\n }\n });\n }\n const visitors = [];\n Object.entries(directives).forEach(([directiveName, directiveValues]) => {\n if (!(directiveName in directiveVisitorMap)) {\n return;\n }\n const VisitorClass = directiveVisitorMap[directiveName];\n // Avoid creating visitor objects if visitorClass does not override\n // the visitor method named by methodName.\n if (!VisitorClass.implementsVisitorMethod(methodName)) {\n return;\n }\n directiveValues.forEach(directiveValue => {\n // As foretold in comments near the top of the visitSchemaDirectives\n // method, this is where instances of the SchemaDirectiveVisitor class\n // get created and assigned names. While subclasses could override the\n // constructor method, the constructor is marked as protected, so\n // these are the only arguments that will ever be passed.\n visitors.push(new VisitorClass({\n name: directiveName,\n args: directiveValue,\n visitedType: type,\n schema,\n context,\n }));\n });\n });\n if (visitors.length > 0) {\n visitors.forEach(visitor => {\n createdVisitors[visitor.name].push(visitor);\n });\n }\n return visitors;\n }\n visitSchema(schema, visitorSelector);\n return createdVisitors;\n }\n static getDeclaredDirectives(schema, directiveVisitors) {\n const declaredDirectives = schema.getDirectives().reduce((prev, curr) => ({\n ...prev,\n [curr.name]: curr,\n }), {});\n // If the visitor subclass overrides getDirectiveDeclaration, and it\n // returns a non-null GraphQLDirective, use that instead of any directive\n // declared in the schema itself. Reasoning: if a SchemaDirectiveVisitor\n // goes to the trouble of implementing getDirectiveDeclaration, it should\n // be able to rely on that implementation.\n Object.entries(directiveVisitors).forEach(([directiveName, visitorClass]) => {\n const decl = visitorClass.getDirectiveDeclaration(directiveName, schema);\n if (decl != null) {\n declaredDirectives[directiveName] = decl;\n }\n });\n Object.entries(declaredDirectives).forEach(([name, decl]) => {\n if (!(name in directiveVisitors)) {\n // SchemaDirectiveVisitors.visitSchemaDirectives might be called\n // multiple times with partial directiveVisitors maps, so it's not\n // necessarily an error for directiveVisitors to be missing an\n // implementation of a directive that was declared in the schema.\n return;\n }\n const visitorClass = directiveVisitors[name];\n decl.locations.forEach(loc => {\n const visitorMethodName = directiveLocationToVisitorMethodName(loc);\n if (SchemaVisitor.implementsVisitorMethod(visitorMethodName) &&\n !visitorClass.implementsVisitorMethod(visitorMethodName)) {\n // While visitor subclasses may implement extra visitor methods,\n // it's definitely a mistake if the GraphQLDirective declares itself\n // applicable to certain schema locations, and the visitor subclass\n // does not implement all the corresponding methods.\n throw new Error(`SchemaDirectiveVisitor for @${name} must implement ${visitorMethodName} method`);\n }\n });\n });\n return declaredDirectives;\n }\n}\n// Convert a string like \"FIELD_DEFINITION\" to \"visitFieldDefinition\".\nfunction directiveLocationToVisitorMethodName(loc) {\n return ('visit' +\n loc.replace(/([^_]*)_?/g, (_wholeMatch, part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()));\n}\n\nfunction getResolversFromSchema(schema) {\n const resolvers = Object.create({});\n const typeMap = schema.getTypeMap();\n Object.keys(typeMap).forEach(typeName => {\n const type = typeMap[typeName];\n if (isScalarType(type)) {\n if (!isSpecifiedScalarType(type)) {\n const config = type.toConfig();\n delete config.astNode; // avoid AST duplication elsewhere\n resolvers[typeName] = new GraphQLScalarType(config);\n }\n }\n else if (isEnumType(type)) {\n resolvers[typeName] = {};\n const values = type.getValues();\n values.forEach(value => {\n resolvers[typeName][value.name] = value.value;\n });\n }\n else if (isInterfaceType(type)) {\n if (type.resolveType != null) {\n resolvers[typeName] = {\n __resolveType: type.resolveType,\n };\n }\n }\n else if (isUnionType(type)) {\n if (type.resolveType != null) {\n resolvers[typeName] = {\n __resolveType: type.resolveType,\n };\n }\n }\n else if (isObjectType(type)) {\n resolvers[typeName] = {};\n if (type.isTypeOf != null) {\n resolvers[typeName].__isTypeOf = type.isTypeOf;\n }\n const fields = type.getFields();\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n resolvers[typeName][fieldName] = {\n resolve: field.resolve,\n subscribe: field.subscribe,\n };\n });\n }\n });\n return resolvers;\n}\n\nfunction forEachField(schema, fn) {\n const typeMap = schema.getTypeMap();\n Object.keys(typeMap).forEach(typeName => {\n const type = typeMap[typeName];\n // TODO: maybe have an option to include these?\n if (!getNamedType(type).name.startsWith('__') && isObjectType(type)) {\n const fields = type.getFields();\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n fn(field, typeName, fieldName);\n });\n }\n });\n}\n\nfunction forEachDefaultValue(schema, fn) {\n const typeMap = schema.getTypeMap();\n Object.keys(typeMap).forEach(typeName => {\n const type = typeMap[typeName];\n if (!getNamedType(type).name.startsWith('__')) {\n if (isObjectType(type)) {\n const fields = type.getFields();\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n field.args.forEach(arg => {\n arg.defaultValue = fn(arg.type, arg.defaultValue);\n });\n });\n }\n else if (isInputObjectType(type)) {\n const fields = type.getFields();\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n field.defaultValue = fn(field.type, field.defaultValue);\n });\n }\n }\n });\n}\n\n// addTypes uses toConfig to create a new schema with a new or replaced\nfunction addTypes(schema, newTypesOrDirectives) {\n const queryType = schema.getQueryType();\n const mutationType = schema.getMutationType();\n const subscriptionType = schema.getSubscriptionType();\n const queryTypeName = queryType != null ? queryType.name : undefined;\n const mutationTypeName = mutationType != null ? mutationType.name : undefined;\n const subscriptionTypeName = subscriptionType != null ? subscriptionType.name : undefined;\n const config = schema.toConfig();\n const originalTypeMap = {};\n config.types.forEach(type => {\n originalTypeMap[type.name] = type;\n });\n const originalDirectiveMap = {};\n config.directives.forEach(directive => {\n originalDirectiveMap[directive.name] = directive;\n });\n newTypesOrDirectives.forEach(newTypeOrDirective => {\n if (isNamedType(newTypeOrDirective)) {\n originalTypeMap[newTypeOrDirective.name] = newTypeOrDirective;\n }\n else if (isDirective(newTypeOrDirective)) {\n originalDirectiveMap[newTypeOrDirective.name] = newTypeOrDirective;\n }\n });\n const { typeMap, directives } = rewireTypes(originalTypeMap, Object.keys(originalDirectiveMap).map(directiveName => originalDirectiveMap[directiveName]));\n return new GraphQLSchema({\n ...config,\n query: queryTypeName ? typeMap[queryTypeName] : undefined,\n mutation: mutationTypeName ? typeMap[mutationTypeName] : undefined,\n subscription: subscriptionTypeName != null ? typeMap[subscriptionTypeName] : undefined,\n types: Object.keys(typeMap).map(typeName => typeMap[typeName]),\n directives,\n });\n}\n\n/**\n * Prunes the provided schema, removing unused and empty types\n * @param schema The schema to prune\n * @param options Additional options for removing unused types from the schema\n */\nfunction pruneSchema(schema, options = {}) {\n const pruningContext = {\n schema,\n unusedTypes: Object.create(null),\n implementations: Object.create(null),\n };\n Object.keys(schema.getTypeMap()).forEach(typeName => {\n const type = schema.getType(typeName);\n if ('getInterfaces' in type) {\n type.getInterfaces().forEach(iface => {\n if (pruningContext.implementations[iface.name] == null) {\n pruningContext.implementations[iface.name] = Object.create(null);\n }\n pruningContext.implementations[iface.name][type.name] = true;\n });\n }\n });\n visitTypes(pruningContext, schema);\n return mapSchema(schema, {\n [MapperKind.TYPE]: (type) => {\n if (isObjectType(type) || isInputObjectType(type)) {\n if ((!Object.keys(type.getFields()).length && !options.skipEmptyCompositeTypePruning) ||\n (pruningContext.unusedTypes[type.name] && !options.skipUnusedTypesPruning)) {\n return null;\n }\n }\n else if (isUnionType(type)) {\n if ((!type.getTypes().length && !options.skipEmptyUnionPruning) ||\n (pruningContext.unusedTypes[type.name] && !options.skipUnusedTypesPruning)) {\n return null;\n }\n }\n else if (isInterfaceType(type)) {\n if ((!Object.keys(type.getFields()).length && !options.skipEmptyCompositeTypePruning) ||\n (!Object.keys(pruningContext.implementations[type.name]).length &&\n !options.skipUnimplementedInterfacesPruning) ||\n (pruningContext.unusedTypes[type.name] && !options.skipUnusedTypesPruning)) {\n return null;\n }\n }\n else {\n if (pruningContext.unusedTypes[type.name] && !options.skipUnusedTypesPruning) {\n return null;\n }\n }\n },\n });\n}\nfunction visitOutputType(visitedTypes, pruningContext, type) {\n if (visitedTypes[type.name]) {\n return;\n }\n visitedTypes[type.name] = true;\n pruningContext.unusedTypes[type.name] = false;\n if (isObjectType(type) || isInterfaceType(type)) {\n const fields = type.getFields();\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n const namedType = getNamedType(field.type);\n visitOutputType(visitedTypes, pruningContext, namedType);\n const args = field.args;\n args.forEach(arg => {\n const type = getNamedType(arg.type);\n visitInputType(visitedTypes, pruningContext, type);\n });\n });\n if (isInterfaceType(type)) {\n Object.keys(pruningContext.implementations[type.name]).forEach(typeName => {\n visitOutputType(visitedTypes, pruningContext, pruningContext.schema.getType(typeName));\n });\n }\n if ('getInterfaces' in type) {\n type.getInterfaces().forEach(type => {\n visitOutputType(visitedTypes, pruningContext, type);\n });\n }\n }\n else if (isUnionType(type)) {\n const types = type.getTypes();\n types.forEach(type => visitOutputType(visitedTypes, pruningContext, type));\n }\n}\nfunction visitInputType(visitedTypes, pruningContext, type) {\n if (visitedTypes[type.name]) {\n return;\n }\n pruningContext.unusedTypes[type.name] = false;\n visitedTypes[type.name] = true;\n if (isInputObjectType(type)) {\n const fields = type.getFields();\n Object.keys(fields).forEach(fieldName => {\n const field = fields[fieldName];\n const namedType = getNamedType(field.type);\n visitInputType(visitedTypes, pruningContext, namedType);\n });\n }\n}\nfunction visitTypes(pruningContext, schema) {\n Object.keys(schema.getTypeMap()).forEach(typeName => {\n if (!typeName.startsWith('__')) {\n pruningContext.unusedTypes[typeName] = true;\n }\n });\n const visitedTypes = Object.create(null);\n const rootTypes = [schema.getQueryType(), schema.getMutationType(), schema.getSubscriptionType()].filter(type => type != null);\n rootTypes.forEach(rootType => visitOutputType(visitedTypes, pruningContext, rootType));\n schema.getDirectives().forEach(directive => {\n directive.args.forEach(arg => {\n const type = getNamedType(arg.type);\n visitInputType(visitedTypes, pruningContext, type);\n });\n });\n}\n\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\nfunction mergeDeep(target, ...sources) {\n if (isScalarType(target)) {\n return target;\n }\n const output = {\n ...target,\n };\n for (const source of sources) {\n if (isObject(target) && isObject(source)) {\n for (const key in source) {\n if (isObject(source[key])) {\n if (!(key in target)) {\n Object.assign(output, { [key]: source[key] });\n }\n else {\n output[key] = mergeDeep(target[key], source[key]);\n }\n }\n else {\n Object.assign(output, { [key]: source[key] });\n }\n }\n }\n }\n return output;\n}\nfunction isObject(item) {\n return item && typeof item === 'object' && !Array.isArray(item);\n}\n\nfunction parseSelectionSet(selectionSet, options) {\n const query = parse(selectionSet, options).definitions[0];\n return query.selectionSet;\n}\n\n/**\n * Get the key under which the result of this resolver will be placed in the response JSON. Basically, just\n * resolves aliases.\n * @param info The info argument to the resolver.\n */\nfunction getResponseKeyFromInfo(info) {\n return info.fieldNodes[0].alias != null ? info.fieldNodes[0].alias.value : info.fieldName;\n}\n\nfunction appendObjectFields(schema, typeName, additionalFields) {\n if (schema.getType(typeName) == null) {\n return addTypes(schema, [\n new GraphQLObjectType({\n name: typeName,\n fields: additionalFields,\n }),\n ]);\n }\n return mapSchema(schema, {\n [MapperKind.OBJECT_TYPE]: type => {\n if (type.name === typeName) {\n const config = type.toConfig();\n const originalFieldConfigMap = config.fields;\n const newFieldConfigMap = {};\n Object.keys(originalFieldConfigMap).forEach(fieldName => {\n newFieldConfigMap[fieldName] = originalFieldConfigMap[fieldName];\n });\n Object.keys(additionalFields).forEach(fieldName => {\n newFieldConfigMap[fieldName] = additionalFields[fieldName];\n });\n return correctASTNodes(new GraphQLObjectType({\n ...config,\n fields: newFieldConfigMap,\n }));\n }\n },\n });\n}\nfunction removeObjectFields(schema, typeName, testFn) {\n const removedFields = {};\n const newSchema = mapSchema(schema, {\n [MapperKind.OBJECT_TYPE]: type => {\n if (type.name === typeName) {\n const config = type.toConfig();\n const originalFieldConfigMap = config.fields;\n const newFieldConfigMap = {};\n Object.keys(originalFieldConfigMap).forEach(fieldName => {\n const originalFieldConfig = originalFieldConfigMap[fieldName];\n if (testFn(fieldName, originalFieldConfig)) {\n removedFields[fieldName] = originalFieldConfig;\n }\n else {\n newFieldConfigMap[fieldName] = originalFieldConfig;\n }\n });\n return correctASTNodes(new GraphQLObjectType({\n ...config,\n fields: newFieldConfigMap,\n }));\n }\n },\n });\n return [newSchema, removedFields];\n}\nfunction selectObjectFields(schema, typeName, testFn) {\n const selectedFields = {};\n mapSchema(schema, {\n [MapperKind.OBJECT_TYPE]: type => {\n if (type.name === typeName) {\n const config = type.toConfig();\n const originalFieldConfigMap = config.fields;\n Object.keys(originalFieldConfigMap).forEach(fieldName => {\n const originalFieldConfig = originalFieldConfigMap[fieldName];\n if (testFn(fieldName, originalFieldConfig)) {\n selectedFields[fieldName] = originalFieldConfig;\n }\n });\n }\n return undefined;\n },\n });\n return selectedFields;\n}\nfunction modifyObjectFields(schema, typeName, testFn, newFields) {\n const removedFields = {};\n const newSchema = mapSchema(schema, {\n [MapperKind.OBJECT_TYPE]: type => {\n if (type.name === typeName) {\n const config = type.toConfig();\n const originalFieldConfigMap = config.fields;\n const newFieldConfigMap = {};\n Object.keys(originalFieldConfigMap).forEach(fieldName => {\n const originalFieldConfig = originalFieldConfigMap[fieldName];\n if (testFn(fieldName, originalFieldConfig)) {\n removedFields[fieldName] = originalFieldConfig;\n }\n else {\n newFieldConfigMap[fieldName] = originalFieldConfig;\n }\n });\n Object.keys(newFields).forEach(fieldName => {\n const fieldConfig = newFields[fieldName];\n newFieldConfigMap[fieldName] = fieldConfig;\n });\n return correctASTNodes(new GraphQLObjectType({\n ...config,\n fields: newFieldConfigMap,\n }));\n }\n },\n });\n return [newSchema, removedFields];\n}\n\nfunction renameType(type, newTypeName) {\n if (isObjectType(type)) {\n return new GraphQLObjectType({\n ...type.toConfig(),\n name: newTypeName,\n astNode: type.astNode == null\n ? type.astNode\n : {\n ...type.astNode,\n name: {\n ...type.astNode.name,\n value: newTypeName,\n },\n },\n extensionASTNodes: type.extensionASTNodes == null\n ? type.extensionASTNodes\n : type.extensionASTNodes.map(node => ({\n ...node,\n name: {\n ...node.name,\n value: newTypeName,\n },\n })),\n });\n }\n else if (isInterfaceType(type)) {\n return new GraphQLInterfaceType({\n ...type.toConfig(),\n name: newTypeName,\n astNode: type.astNode == null\n ? type.astNode\n : {\n ...type.astNode,\n name: {\n ...type.astNode.name,\n value: newTypeName,\n },\n },\n extensionASTNodes: type.extensionASTNodes == null\n ? type.extensionASTNodes\n : type.extensionASTNodes.map(node => ({\n ...node,\n name: {\n ...node.name,\n value: newTypeName,\n },\n })),\n });\n }\n else if (isUnionType(type)) {\n return new GraphQLUnionType({\n ...type.toConfig(),\n name: newTypeName,\n astNode: type.astNode == null\n ? type.astNode\n : {\n ...type.astNode,\n name: {\n ...type.astNode.name,\n value: newTypeName,\n },\n },\n extensionASTNodes: type.extensionASTNodes == null\n ? type.extensionASTNodes\n : type.extensionASTNodes.map(node => ({\n ...node,\n name: {\n ...node.name,\n value: newTypeName,\n },\n })),\n });\n }\n else if (isInputObjectType(type)) {\n return new GraphQLInputObjectType({\n ...type.toConfig(),\n name: newTypeName,\n astNode: type.astNode == null\n ? type.astNode\n : {\n ...type.astNode,\n name: {\n ...type.astNode.name,\n value: newTypeName,\n },\n },\n extensionASTNodes: type.extensionASTNodes == null\n ? type.extensionASTNodes\n : type.extensionASTNodes.map(node => ({\n ...node,\n name: {\n ...node.name,\n value: newTypeName,\n },\n })),\n });\n }\n else if (isEnumType(type)) {\n return new GraphQLEnumType({\n ...type.toConfig(),\n name: newTypeName,\n astNode: type.astNode == null\n ? type.astNode\n : {\n ...type.astNode,\n name: {\n ...type.astNode.name,\n value: newTypeName,\n },\n },\n extensionASTNodes: type.extensionASTNodes == null\n ? type.extensionASTNodes\n : type.extensionASTNodes.map(node => ({\n ...node,\n name: {\n ...node.name,\n value: newTypeName,\n },\n })),\n });\n }\n else if (isScalarType(type)) {\n return new GraphQLScalarType({\n ...type.toConfig(),\n name: newTypeName,\n astNode: type.astNode == null\n ? type.astNode\n : {\n ...type.astNode,\n name: {\n ...type.astNode.name,\n value: newTypeName,\n },\n },\n extensionASTNodes: type.extensionASTNodes == null\n ? type.extensionASTNodes\n : type.extensionASTNodes.map(node => ({\n ...node,\n name: {\n ...node.name,\n value: newTypeName,\n },\n })),\n });\n }\n throw new Error(`Unknown type ${type}.`);\n}\n\n/**\n * Given a selectionSet, adds all of the fields in that selection to\n * the passed in map of fields, and returns it at the end.\n *\n * CollectFields requires the \"runtime type\" of an object. For a field which\n * returns an Interface or Union type, the \"runtime type\" will be the actual\n * Object type returned by that field.\n *\n * @internal\n */\nfunction collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) {\n for (const selection of selectionSet.selections) {\n switch (selection.kind) {\n case Kind.FIELD: {\n if (!shouldIncludeNode(exeContext, selection)) {\n continue;\n }\n const name = getFieldEntryKey(selection);\n if (!(name in fields)) {\n fields[name] = [];\n }\n fields[name].push(selection);\n break;\n }\n case Kind.INLINE_FRAGMENT: {\n if (!shouldIncludeNode(exeContext, selection) ||\n !doesFragmentConditionMatch(exeContext, selection, runtimeType)) {\n continue;\n }\n collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames);\n break;\n }\n case Kind.FRAGMENT_SPREAD: {\n const fragName = selection.name.value;\n if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) {\n continue;\n }\n visitedFragmentNames[fragName] = true;\n const fragment = exeContext.fragments[fragName];\n if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) {\n continue;\n }\n collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames);\n break;\n }\n }\n }\n return fields;\n}\n/**\n * Determines if a field should be included based on the @include and @skip\n * directives, where @skip has higher precedence than @include.\n */\nfunction shouldIncludeNode(exeContext, node) {\n const skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues);\n if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {\n return false;\n }\n const include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues);\n if ((include === null || include === void 0 ? void 0 : include.if) === false) {\n return false;\n }\n return true;\n}\n/**\n * Determines if a fragment is applicable to the given type.\n */\nfunction doesFragmentConditionMatch(exeContext, fragment, type) {\n const typeConditionNode = fragment.typeCondition;\n if (!typeConditionNode) {\n return true;\n }\n const conditionalType = typeFromAST(exeContext.schema, typeConditionNode);\n if (conditionalType === type) {\n return true;\n }\n if (isAbstractType(conditionalType)) {\n return exeContext.schema.isPossibleType(conditionalType, type);\n }\n return false;\n}\n/**\n * Implements the logic to compute the key of a given field's entry\n */\nfunction getFieldEntryKey(node) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return node.alias ? node.alias.value : node.name.value;\n}\n\n/**\n * Given an AsyncIterable and a callback function, return an AsyncIterator\n * which produces values mapped via calling the callback function.\n */\nfunction mapAsyncIterator(iterator, callback, rejectCallback) {\n let $return;\n let abruptClose;\n if (typeof iterator.return === 'function') {\n $return = iterator.return;\n abruptClose = (error) => {\n const rethrow = () => Promise.reject(error);\n return $return.call(iterator).then(rethrow, rethrow);\n };\n }\n function mapResult(result) {\n return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);\n }\n let mapReject;\n if (rejectCallback) {\n // Capture rejectCallback to ensure it cannot be null.\n const reject = rejectCallback;\n mapReject = (error) => asyncMapValue(error, reject).then(iteratorResult, abruptClose);\n }\n return {\n next() {\n return iterator.next().then(mapResult, mapReject);\n },\n return() {\n return $return\n ? $return.call(iterator).then(mapResult, mapReject)\n : Promise.resolve({ value: undefined, done: true });\n },\n throw(error) {\n if (typeof iterator.throw === 'function') {\n return iterator.throw(error).then(mapResult, mapReject);\n }\n return Promise.reject(error).catch(abruptClose);\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\nfunction asyncMapValue(value, callback) {\n return new Promise(resolve => resolve(callback(value)));\n}\nfunction iteratorResult(value) {\n return { value, done: false };\n}\n\nfunction updateArgument(argName, argType, argumentNodes, variableDefinitionsMap, variableValues, newArg) {\n let varName;\n let numGeneratedVariables = 0;\n do {\n varName = `_v${(numGeneratedVariables++).toString()}_${argName}`;\n } while (varName in variableDefinitionsMap);\n argumentNodes[argName] = {\n kind: Kind.ARGUMENT,\n name: {\n kind: Kind.NAME,\n value: argName,\n },\n value: {\n kind: Kind.VARIABLE,\n name: {\n kind: Kind.NAME,\n value: varName,\n },\n },\n };\n variableDefinitionsMap[varName] = {\n kind: Kind.VARIABLE_DEFINITION,\n variable: {\n kind: Kind.VARIABLE,\n name: {\n kind: Kind.NAME,\n value: varName,\n },\n },\n type: astFromType(argType),\n };\n if (newArg === undefined) {\n delete variableValues[varName];\n }\n else {\n variableValues[varName] = newArg;\n }\n}\n\nfunction implementsAbstractType(schema, typeA, typeB) {\n if (typeA === typeB) {\n return true;\n }\n else if (isCompositeType(typeA) && isCompositeType(typeB)) {\n return doTypesOverlap(schema, typeA, typeB);\n }\n return false;\n}\n\nfunction relocatedError(originalError, path) {\n return new GraphQLError(originalError.message, originalError.nodes, originalError.source, originalError.positions, path === null ? undefined : path === undefined ? originalError.path : path, originalError.originalError, originalError.extensions);\n}\n\nfunction inputFieldToFieldConfig(field) {\n return {\n description: field.description,\n type: field.type,\n defaultValue: field.defaultValue,\n extensions: field.extensions,\n astNode: field.astNode,\n };\n}\nfunction fieldToFieldConfig(field) {\n return {\n description: field.description,\n type: field.type,\n args: argsToFieldConfigArgumentMap(field.args),\n resolve: field.resolve,\n subscribe: field.subscribe,\n deprecationReason: field.deprecationReason,\n extensions: field.extensions,\n astNode: field.astNode,\n };\n}\nfunction argsToFieldConfigArgumentMap(args) {\n const newArguments = {};\n args.forEach(arg => {\n newArguments[arg.name] = argumentToArgumentConfig(arg);\n });\n return newArguments;\n}\nfunction argumentToArgumentConfig(arg) {\n return {\n description: arg.description,\n type: arg.type,\n defaultValue: arg.defaultValue,\n extensions: arg.extensions,\n astNode: arg.astNode,\n };\n}\n\nfunction observableToAsyncIterable(observable) {\n const pullQueue = [];\n const pushQueue = [];\n let listening = true;\n const pushValue = (value) => {\n if (pullQueue.length !== 0) {\n pullQueue.shift()({ value, done: false });\n }\n else {\n pushQueue.push({ value, done: false });\n }\n };\n const pushError = (error) => {\n if (pullQueue.length !== 0) {\n pullQueue.shift()({ value: { errors: [error] }, done: false });\n }\n else {\n pushQueue.push({ value: { errors: [error] }, done: false });\n }\n };\n const pushDone = () => {\n if (pullQueue.length !== 0) {\n pullQueue.shift()({ done: true });\n }\n else {\n pushQueue.push({ done: true });\n }\n };\n const pullValue = () => new Promise(resolve => {\n if (pushQueue.length !== 0) {\n const element = pushQueue.shift();\n // either {value: {errors: [...]}} or {value: ...}\n resolve(element);\n }\n else {\n pullQueue.push(resolve);\n }\n });\n const subscription = observable.subscribe({\n next(value) {\n pushValue(value);\n },\n error(err) {\n pushError(err);\n },\n complete() {\n pushDone();\n },\n });\n const emptyQueue = () => {\n if (listening) {\n listening = false;\n subscription.unsubscribe();\n pullQueue.forEach(resolve => resolve({ value: undefined, done: true }));\n pullQueue.length = 0;\n pushQueue.length = 0;\n }\n };\n return {\n next() {\n return listening ? pullValue() : this.return();\n },\n return() {\n emptyQueue();\n return Promise.resolve({ value: undefined, done: true });\n },\n throw(error) {\n emptyQueue();\n return Promise.reject(error);\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n\nfunction visitData(data, enter, leave) {\n if (Array.isArray(data)) {\n return data.map(value => visitData(value, enter, leave));\n }\n else if (typeof data === 'object') {\n const newData = enter != null ? enter(data) : data;\n if (newData != null) {\n Object.keys(newData).forEach(key => {\n const value = newData[key];\n newData[key] = visitData(value, enter, leave);\n });\n }\n return leave != null ? leave(newData) : newData;\n }\n return data;\n}\nfunction visitErrors(errors, visitor) {\n return errors.map(error => visitor(error));\n}\nfunction visitResult(result, request, schema, resultVisitorMap, errorVisitorMap) {\n const partialExecutionContext = {\n schema,\n fragments: request.document.definitions.reduce((acc, def) => {\n if (def.kind === Kind.FRAGMENT_DEFINITION) {\n acc[def.name.value] = def;\n }\n return acc;\n }, {}),\n variableValues: request.variables,\n };\n const errorInfo = {\n segmentInfoMap: new Map(),\n unpathedErrors: new Set(),\n };\n const data = result.data;\n const errors = result.errors;\n const visitingErrors = errors != null && errorVisitorMap != null;\n if (data != null) {\n result.data = visitRoot(data, getOperationAST(request.document, undefined), partialExecutionContext, resultVisitorMap, visitingErrors ? errors : undefined, errorInfo);\n }\n if (visitingErrors) {\n result.errors = visitErrorsByType(errors, errorVisitorMap, errorInfo);\n }\n return result;\n}\nfunction visitErrorsByType(errors, errorVisitorMap, errorInfo) {\n const segmentInfoMap = errorInfo.segmentInfoMap;\n const unpathedErrors = errorInfo.unpathedErrors;\n const unpathedErrorVisitor = errorVisitorMap['__unpathed'];\n return errors.map(originalError => {\n const pathSegmentsInfo = segmentInfoMap.get(originalError);\n const newError = pathSegmentsInfo == null\n ? originalError\n : pathSegmentsInfo.reduceRight((acc, segmentInfo) => {\n const typeName = segmentInfo.type.name;\n const typeVisitorMap = errorVisitorMap[typeName];\n if (typeVisitorMap == null) {\n return acc;\n }\n const errorVisitor = typeVisitorMap[segmentInfo.fieldName];\n return errorVisitor == null ? acc : errorVisitor(acc, segmentInfo.pathIndex);\n }, originalError);\n if (unpathedErrorVisitor && unpathedErrors.has(originalError)) {\n return unpathedErrorVisitor(newError);\n }\n return newError;\n });\n}\nfunction visitRoot(root, operation, exeContext, resultVisitorMap, errors, errorInfo) {\n const operationRootType = getOperationRootType(exeContext.schema, operation);\n const collectedFields = collectFields(exeContext, operationRootType, operation.selectionSet, Object.create(null), Object.create(null));\n return visitObjectValue(root, operationRootType, collectedFields, exeContext, resultVisitorMap, 0, errors, errorInfo);\n}\nfunction visitObjectValue(object, type, fieldNodeMap, exeContext, resultVisitorMap, pathIndex, errors, errorInfo) {\n const fieldMap = type.getFields();\n const typeVisitorMap = resultVisitorMap === null || resultVisitorMap === void 0 ? void 0 : resultVisitorMap[type.name];\n const enterObject = typeVisitorMap === null || typeVisitorMap === void 0 ? void 0 : typeVisitorMap.__enter;\n const newObject = enterObject != null ? enterObject(object) : object;\n let sortedErrors;\n let errorMap;\n if (errors != null) {\n sortedErrors = sortErrorsByPathSegment(errors, pathIndex);\n errorMap = sortedErrors.errorMap;\n sortedErrors.unpathedErrors.forEach(error => errorInfo.unpathedErrors.add(error));\n }\n Object.keys(fieldNodeMap).forEach(responseKey => {\n const subFieldNodes = fieldNodeMap[responseKey];\n const fieldName = subFieldNodes[0].name.value;\n const fieldType = fieldMap[fieldName].type;\n const newPathIndex = pathIndex + 1;\n let fieldErrors;\n if (errors != null) {\n fieldErrors = errorMap[responseKey];\n if (fieldErrors != null) {\n delete errorMap[responseKey];\n }\n addPathSegmentInfo(type, fieldName, newPathIndex, fieldErrors, errorInfo);\n }\n const newValue = visitFieldValue(object[responseKey], fieldType, subFieldNodes, exeContext, resultVisitorMap, newPathIndex, fieldErrors, errorInfo);\n updateObject(newObject, responseKey, newValue, typeVisitorMap, fieldName);\n });\n const oldTypename = newObject.__typename;\n if (oldTypename != null) {\n updateObject(newObject, '__typename', oldTypename, typeVisitorMap, '__typename');\n }\n if (errors != null) {\n Object.keys(errorMap).forEach(unknownResponseKey => {\n errorMap[unknownResponseKey].forEach(error => errorInfo.unpathedErrors.add(error));\n });\n }\n const leaveObject = typeVisitorMap === null || typeVisitorMap === void 0 ? void 0 : typeVisitorMap.__leave;\n return leaveObject != null ? leaveObject(newObject) : newObject;\n}\nfunction updateObject(object, responseKey, newValue, typeVisitorMap, fieldName) {\n if (typeVisitorMap == null) {\n object[responseKey] = newValue;\n return;\n }\n const fieldVisitor = typeVisitorMap[fieldName];\n if (fieldVisitor == null) {\n object[responseKey] = newValue;\n return;\n }\n const visitedValue = fieldVisitor(newValue);\n if (visitedValue === undefined) {\n delete object[responseKey];\n return;\n }\n object[responseKey] = visitedValue;\n}\nfunction visitListValue(list, returnType, fieldNodes, exeContext, resultVisitorMap, pathIndex, errors, errorInfo) {\n return list.map(listMember => visitFieldValue(listMember, returnType, fieldNodes, exeContext, resultVisitorMap, pathIndex + 1, errors, errorInfo));\n}\nfunction visitFieldValue(value, returnType, fieldNodes, exeContext, resultVisitorMap, pathIndex, errors = [], errorInfo) {\n if (value == null) {\n return value;\n }\n const nullableType = getNullableType(returnType);\n if (isListType(nullableType)) {\n return visitListValue(value, nullableType.ofType, fieldNodes, exeContext, resultVisitorMap, pathIndex, errors, errorInfo);\n }\n else if (isAbstractType(nullableType)) {\n const finalType = exeContext.schema.getType(value.__typename);\n const collectedFields = collectSubFields(exeContext, finalType, fieldNodes);\n return visitObjectValue(value, finalType, collectedFields, exeContext, resultVisitorMap, pathIndex, errors, errorInfo);\n }\n else if (isObjectType(nullableType)) {\n const collectedFields = collectSubFields(exeContext, nullableType, fieldNodes);\n return visitObjectValue(value, nullableType, collectedFields, exeContext, resultVisitorMap, pathIndex, errors, errorInfo);\n }\n const typeVisitorMap = resultVisitorMap === null || resultVisitorMap === void 0 ? void 0 : resultVisitorMap[nullableType.name];\n if (typeVisitorMap == null) {\n return value;\n }\n const visitedValue = typeVisitorMap(value);\n return visitedValue === undefined ? value : visitedValue;\n}\nfunction sortErrorsByPathSegment(errors, pathIndex) {\n const errorMap = Object.create(null);\n const unpathedErrors = new Set();\n errors.forEach(error => {\n var _a;\n const pathSegment = (_a = error.path) === null || _a === void 0 ? void 0 : _a[pathIndex];\n if (pathSegment == null) {\n unpathedErrors.add(error);\n return;\n }\n if (pathSegment in errorMap) {\n errorMap[pathSegment].push(error);\n }\n else {\n errorMap[pathSegment] = [error];\n }\n });\n return {\n errorMap,\n unpathedErrors,\n };\n}\nfunction addPathSegmentInfo(type, fieldName, pathIndex, errors = [], errorInfo) {\n errors.forEach(error => {\n const segmentInfo = {\n type,\n fieldName,\n pathIndex,\n };\n const pathSegmentsInfo = errorInfo.segmentInfoMap.get(error);\n if (pathSegmentsInfo == null) {\n errorInfo.segmentInfoMap.set(error, [segmentInfo]);\n }\n else {\n pathSegmentsInfo.push(segmentInfo);\n }\n });\n}\nfunction collectSubFields(exeContext, type, fieldNodes) {\n let subFieldNodes = Object.create(null);\n const visitedFragmentNames = Object.create(null);\n fieldNodes.forEach(fieldNode => {\n subFieldNodes = collectFields(exeContext, type, fieldNode.selectionSet, subFieldNodes, visitedFragmentNames);\n });\n return subFieldNodes;\n}\n\nfunction valueMatchesCriteria(value, criteria) {\n if (value == null) {\n return value === criteria;\n }\n else if (Array.isArray(value)) {\n return Array.isArray(criteria) && value.every((val, index) => valueMatchesCriteria(val, criteria[index]));\n }\n else if (typeof value === 'object') {\n return (typeof criteria === 'object' &&\n criteria &&\n Object.keys(criteria).every(propertyName => valueMatchesCriteria(value[propertyName], criteria[propertyName])));\n }\n else if (criteria instanceof RegExp) {\n return criteria.test(value);\n }\n return value === criteria;\n}\n\nfunction isAsyncIterable(value) {\n return typeof value === 'object' && value != null && Symbol.asyncIterator in value;\n}\n\nfunction isDocumentNode(object) {\n return object && typeof object === 'object' && 'kind' in object && object.kind === Kind.DOCUMENT;\n}\n\nexport { MapperKind, SchemaDirectiveVisitor, SchemaVisitor, VisitSchemaKind, addTypes, appendObjectFields, argsToFieldConfigArgumentMap, argumentToArgumentConfig, asArray, astFromArg, astFromDirective, astFromEnumType, astFromEnumValue, astFromField, astFromInputField, astFromInputObjectType, astFromInterfaceType, astFromObjectType, astFromScalarType, astFromSchema, astFromUnionType, astFromValueUntyped, buildOperationNodeForField, checkValidationErrors, cloneDirective, cloneSchema, cloneType, collectFields, compareNodes, compareStrings, correctASTNodes, createNamedStub, createSchemaDefinition, createStub, debugLog, fieldToFieldConfig, filterSchema, fixSchemaAst, fixWindowsPath, flattenArray, forEachDefaultValue, forEachField, getArgumentValues, getBuiltInForStub, getDeprecatableDirectiveNodes, getDirectiveNodes, getDirectives, getDirectivesInExtensions, getDocumentNodeFromSchema, getFieldsWithDirectives, getImplementingTypes, getLeadingCommentBlock, getResolversFromSchema, getResponseKeyFromInfo, getUserTypesFromSchema, healSchema, healTypes, implementsAbstractType, inputFieldToFieldConfig, isAsyncIterable, isDescribable, isDocumentNode, isDocumentString, isEqual, isNamedStub, isNotEqual, isValidPath, makeDeprecatedDirective, makeDirectiveNode, makeDirectiveNodes, mapAsyncIterator, mapSchema, mergeDeep, modifyObjectFields, nodeToString, observableToAsyncIterable, parseGraphQLJSON, parseGraphQLSDL, parseInputValue, parseInputValueLiteral, parseSelectionSet, printSchemaWithDirectives, pruneSchema, relocatedError, removeObjectFields, renameType, rewireTypes, selectObjectFields, serializeInputValue, transformCommentsToDescriptions, transformInputValue, updateArgument, validateGraphQlDocuments, valueMatchesCriteria, visitData, visitErrors, visitResult, visitSchema };\n//# sourceMappingURL=index.esm.js.map\n","import { getNamedType, GraphQLList } from 'graphql';\nimport DataLoader from 'dataloader';\nimport { delegateToSchema } from '@graphql-tools/delegate';\nimport { relocatedError } from '@graphql-tools/utils';\nconst cache1 = new WeakMap();\nfunction createBatchFn(options) {\n var _a;\n const argsFromKeys = (_a = options.argsFromKeys) !== null && _a !== void 0 ? _a : ((keys) => ({ ids: keys }));\n const { valuesFromResults, lazyOptionsFn } = options;\n return async (keys) => {\n const results = await delegateToSchema({\n returnType: new GraphQLList(getNamedType(options.info.returnType)),\n onLocatedError: originalError => relocatedError(originalError, originalError.path.slice(0, 0).concat(originalError.path.slice(2))),\n args: argsFromKeys(keys),\n ...(lazyOptionsFn == null ? options : lazyOptionsFn(options)),\n });\n if (results instanceof Error) {\n return keys.map(() => results);\n }\n const values = valuesFromResults == null ? results : valuesFromResults(results, keys);\n return Array.isArray(values) ? values : keys.map(() => values);\n };\n}\nexport function getLoader(options) {\n var _a;\n const fieldName = (_a = options.fieldName) !== null && _a !== void 0 ? _a : options.info.fieldName;\n let cache2 = cache1.get(options.info.fieldNodes);\n if (cache2 === undefined) {\n cache2 = new WeakMap();\n cache1.set(options.info.fieldNodes, cache2);\n const loaders = Object.create(null);\n cache2.set(options.schema, loaders);\n const batchFn = createBatchFn(options);\n const loader = new DataLoader(keys => batchFn(keys), options.dataLoaderOptions);\n loaders[fieldName] = loader;\n return loader;\n }\n let loaders = cache2.get(options.schema);\n if (loaders === undefined) {\n loaders = Object.create(null);\n cache2.set(options.schema, loaders);\n const batchFn = createBatchFn(options);\n const loader = new DataLoader(keys => batchFn(keys), options.dataLoaderOptions);\n loaders[fieldName] = loader;\n return loader;\n }\n let loader = loaders[fieldName];\n if (loader === undefined) {\n const batchFn = createBatchFn(options);\n loader = new DataLoader(keys => batchFn(keys), options.dataLoaderOptions);\n loaders[fieldName] = loader;\n }\n return loader;\n}\n//# sourceMappingURL=getLoader.js.map","import { getLoader } from './getLoader';\nexport function batchDelegateToSchema(options) {\n const key = options.key;\n if (key == null) {\n return null;\n }\n else if (Array.isArray(key) && !key.length) {\n return [];\n }\n const loader = getLoader(options);\n return Array.isArray(key) ? loader.loadMany(key) : loader.load(key);\n}\n//# sourceMappingURL=batchDelegateToSchema.js.map","import { getLoader } from './getLoader';\nexport function createBatchDelegateFn(optionsOrArgsFromKeys, lazyOptionsFn, dataLoaderOptions, valuesFromResults) {\n return typeof optionsOrArgsFromKeys === 'function'\n ? createBatchDelegateFnImpl({\n argsFromKeys: optionsOrArgsFromKeys,\n lazyOptionsFn,\n dataLoaderOptions,\n valuesFromResults,\n })\n : createBatchDelegateFnImpl(optionsOrArgsFromKeys);\n}\nfunction createBatchDelegateFnImpl(options) {\n return batchDelegateOptions => {\n const loader = getLoader({\n ...options,\n ...batchDelegateOptions,\n });\n return loader.load(batchDelegateOptions.key);\n };\n}\n//# sourceMappingURL=createBatchDelegateFn.js.map"],"names":["GraphQLError","delegateToSchema","GraphQLList","getNamedType"],"mappings":"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"}
\No newline at end of file