Initial commit
This commit is contained in:
commit
f47e08fdcb
2409 files changed
+363607
No files matched your search
+345
@@ -0,0 +1,345 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.TypeInfo = void 0;
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _introspection = require("../type/introspection");
|
||||
|
||||
var _typeFromAST = require("./typeFromAST");
|
||||
|
||||
var _find = _interopRequireDefault(require("../jsutils/find"));
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
||||
|
||||
/**
|
||||
* TypeInfo is a utility class which, given a GraphQL schema, can keep track
|
||||
* of the current field and type definitions at any point in a GraphQL document
|
||||
* AST during a recursive descent by calling `enter(node)` and `leave(node)`.
|
||||
*/
|
||||
var TypeInfo =
|
||||
/*#__PURE__*/
|
||||
function () {
|
||||
function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order
|
||||
// to support non-spec-compliant codebases. You should never need to use it.
|
||||
getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals
|
||||
initialType) {
|
||||
_defineProperty(this, "_schema", void 0);
|
||||
|
||||
_defineProperty(this, "_typeStack", void 0);
|
||||
|
||||
_defineProperty(this, "_parentTypeStack", void 0);
|
||||
|
||||
_defineProperty(this, "_inputTypeStack", void 0);
|
||||
|
||||
_defineProperty(this, "_fieldDefStack", void 0);
|
||||
|
||||
_defineProperty(this, "_defaultValueStack", void 0);
|
||||
|
||||
_defineProperty(this, "_directive", void 0);
|
||||
|
||||
_defineProperty(this, "_argument", void 0);
|
||||
|
||||
_defineProperty(this, "_enumValue", void 0);
|
||||
|
||||
_defineProperty(this, "_getFieldDef", void 0);
|
||||
|
||||
this._schema = schema;
|
||||
this._typeStack = [];
|
||||
this._parentTypeStack = [];
|
||||
this._inputTypeStack = [];
|
||||
this._fieldDefStack = [];
|
||||
this._defaultValueStack = [];
|
||||
this._directive = null;
|
||||
this._argument = null;
|
||||
this._enumValue = null;
|
||||
this._getFieldDef = getFieldDefFn || getFieldDef;
|
||||
|
||||
if (initialType) {
|
||||
if ((0, _definition.isInputType)(initialType)) {
|
||||
this._inputTypeStack.push(initialType);
|
||||
}
|
||||
|
||||
if ((0, _definition.isCompositeType)(initialType)) {
|
||||
this._parentTypeStack.push(initialType);
|
||||
}
|
||||
|
||||
if ((0, _definition.isOutputType)(initialType)) {
|
||||
this._typeStack.push(initialType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _proto = TypeInfo.prototype;
|
||||
|
||||
_proto.getType = function getType() {
|
||||
if (this._typeStack.length > 0) {
|
||||
return this._typeStack[this._typeStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getParentType = function getParentType() {
|
||||
if (this._parentTypeStack.length > 0) {
|
||||
return this._parentTypeStack[this._parentTypeStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getInputType = function getInputType() {
|
||||
if (this._inputTypeStack.length > 0) {
|
||||
return this._inputTypeStack[this._inputTypeStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getParentInputType = function getParentInputType() {
|
||||
if (this._inputTypeStack.length > 1) {
|
||||
return this._inputTypeStack[this._inputTypeStack.length - 2];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getFieldDef = function getFieldDef() {
|
||||
if (this._fieldDefStack.length > 0) {
|
||||
return this._fieldDefStack[this._fieldDefStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getDefaultValue = function getDefaultValue() {
|
||||
if (this._defaultValueStack.length > 0) {
|
||||
return this._defaultValueStack[this._defaultValueStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getDirective = function getDirective() {
|
||||
return this._directive;
|
||||
};
|
||||
|
||||
_proto.getArgument = function getArgument() {
|
||||
return this._argument;
|
||||
};
|
||||
|
||||
_proto.getEnumValue = function getEnumValue() {
|
||||
return this._enumValue;
|
||||
};
|
||||
|
||||
_proto.enter = function enter(node) {
|
||||
var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop
|
||||
// any assumptions of a valid schema to ensure runtime types are properly
|
||||
// checked before continuing since TypeInfo is used as part of validation
|
||||
// which occurs before guarantees of schema and document validity.
|
||||
|
||||
switch (node.kind) {
|
||||
case _kinds.Kind.SELECTION_SET:
|
||||
var namedType = (0, _definition.getNamedType)(this.getType());
|
||||
|
||||
this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.FIELD:
|
||||
var parentType = this.getParentType();
|
||||
var fieldDef;
|
||||
var fieldType;
|
||||
|
||||
if (parentType) {
|
||||
fieldDef = this._getFieldDef(schema, parentType, node);
|
||||
|
||||
if (fieldDef) {
|
||||
fieldType = fieldDef.type;
|
||||
}
|
||||
}
|
||||
|
||||
this._fieldDefStack.push(fieldDef);
|
||||
|
||||
this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.DIRECTIVE:
|
||||
this._directive = schema.getDirective(node.name.value);
|
||||
break;
|
||||
|
||||
case _kinds.Kind.OPERATION_DEFINITION:
|
||||
var type;
|
||||
|
||||
if (node.operation === 'query') {
|
||||
type = schema.getQueryType();
|
||||
} else if (node.operation === 'mutation') {
|
||||
type = schema.getMutationType();
|
||||
} else if (node.operation === 'subscription') {
|
||||
type = schema.getSubscriptionType();
|
||||
}
|
||||
|
||||
this._typeStack.push((0, _definition.isObjectType)(type) ? type : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.INLINE_FRAGMENT:
|
||||
case _kinds.Kind.FRAGMENT_DEFINITION:
|
||||
var typeConditionAST = node.typeCondition;
|
||||
var outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType());
|
||||
|
||||
this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.VARIABLE_DEFINITION:
|
||||
var inputType = (0, _typeFromAST.typeFromAST)(schema, node.type);
|
||||
|
||||
this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.ARGUMENT:
|
||||
var argDef;
|
||||
var argType;
|
||||
var fieldOrDirective = this.getDirective() || this.getFieldDef();
|
||||
|
||||
if (fieldOrDirective) {
|
||||
argDef = (0, _find.default)(fieldOrDirective.args, function (arg) {
|
||||
return arg.name === node.name.value;
|
||||
});
|
||||
|
||||
if (argDef) {
|
||||
argType = argDef.type;
|
||||
}
|
||||
}
|
||||
|
||||
this._argument = argDef;
|
||||
|
||||
this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);
|
||||
|
||||
this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.LIST:
|
||||
var listType = (0, _definition.getNullableType)(this.getInputType());
|
||||
var itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value.
|
||||
|
||||
this._defaultValueStack.push(undefined);
|
||||
|
||||
this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.OBJECT_FIELD:
|
||||
var objectType = (0, _definition.getNamedType)(this.getInputType());
|
||||
var inputFieldType;
|
||||
var inputField;
|
||||
|
||||
if ((0, _definition.isInputObjectType)(objectType)) {
|
||||
inputField = objectType.getFields()[node.name.value];
|
||||
|
||||
if (inputField) {
|
||||
inputFieldType = inputField.type;
|
||||
}
|
||||
}
|
||||
|
||||
this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined);
|
||||
|
||||
this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.ENUM:
|
||||
var enumType = (0, _definition.getNamedType)(this.getInputType());
|
||||
var enumValue;
|
||||
|
||||
if ((0, _definition.isEnumType)(enumType)) {
|
||||
enumValue = enumType.getValue(node.value);
|
||||
}
|
||||
|
||||
this._enumValue = enumValue;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.leave = function leave(node) {
|
||||
switch (node.kind) {
|
||||
case _kinds.Kind.SELECTION_SET:
|
||||
this._parentTypeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.FIELD:
|
||||
this._fieldDefStack.pop();
|
||||
|
||||
this._typeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.DIRECTIVE:
|
||||
this._directive = null;
|
||||
break;
|
||||
|
||||
case _kinds.Kind.OPERATION_DEFINITION:
|
||||
case _kinds.Kind.INLINE_FRAGMENT:
|
||||
case _kinds.Kind.FRAGMENT_DEFINITION:
|
||||
this._typeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.VARIABLE_DEFINITION:
|
||||
this._inputTypeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.ARGUMENT:
|
||||
this._argument = null;
|
||||
|
||||
this._defaultValueStack.pop();
|
||||
|
||||
this._inputTypeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.LIST:
|
||||
case _kinds.Kind.OBJECT_FIELD:
|
||||
this._defaultValueStack.pop();
|
||||
|
||||
this._inputTypeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.ENUM:
|
||||
this._enumValue = null;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
return TypeInfo;
|
||||
}();
|
||||
/**
|
||||
* Not exactly the same as the executor's definition of getFieldDef, in this
|
||||
* statically evaluated environment we do not always have an Object type,
|
||||
* and need to handle Interface and Union types.
|
||||
*/
|
||||
|
||||
|
||||
exports.TypeInfo = TypeInfo;
|
||||
|
||||
function getFieldDef(schema, parentType, fieldNode) {
|
||||
var name = fieldNode.name.value;
|
||||
|
||||
if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return _introspection.SchemaMetaFieldDef;
|
||||
}
|
||||
|
||||
if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return _introspection.TypeMetaFieldDef;
|
||||
}
|
||||
|
||||
if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) {
|
||||
return _introspection.TypeNameMetaFieldDef;
|
||||
}
|
||||
|
||||
if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) {
|
||||
return parentType.getFields()[name];
|
||||
}
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { Kind } from '../language/kinds';
|
||||
import {
|
||||
isObjectType,
|
||||
isInterfaceType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
isListType,
|
||||
isCompositeType,
|
||||
isInputType,
|
||||
isOutputType,
|
||||
getNullableType,
|
||||
getNamedType,
|
||||
} from '../type/definition';
|
||||
import type {
|
||||
GraphQLType,
|
||||
GraphQLInputType,
|
||||
GraphQLOutputType,
|
||||
GraphQLCompositeType,
|
||||
GraphQLField,
|
||||
GraphQLArgument,
|
||||
GraphQLInputField,
|
||||
GraphQLEnumValue,
|
||||
} from '../type/definition';
|
||||
import type { GraphQLDirective } from '../type/directives';
|
||||
import {
|
||||
SchemaMetaFieldDef,
|
||||
TypeMetaFieldDef,
|
||||
TypeNameMetaFieldDef,
|
||||
} from '../type/introspection';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
import type { ASTNode, FieldNode } from '../language/ast';
|
||||
import { typeFromAST } from './typeFromAST';
|
||||
import find from '../jsutils/find';
|
||||
|
||||
/**
|
||||
* TypeInfo is a utility class which, given a GraphQL schema, can keep track
|
||||
* of the current field and type definitions at any point in a GraphQL document
|
||||
* AST during a recursive descent by calling `enter(node)` and `leave(node)`.
|
||||
*/
|
||||
export class TypeInfo {
|
||||
_schema: GraphQLSchema;
|
||||
_typeStack: Array<?GraphQLOutputType>;
|
||||
_parentTypeStack: Array<?GraphQLCompositeType>;
|
||||
_inputTypeStack: Array<?GraphQLInputType>;
|
||||
_fieldDefStack: Array<?GraphQLField<*, *>>;
|
||||
_defaultValueStack: Array<?mixed>;
|
||||
_directive: ?GraphQLDirective;
|
||||
_argument: ?GraphQLArgument;
|
||||
_enumValue: ?GraphQLEnumValue;
|
||||
_getFieldDef: typeof getFieldDef;
|
||||
|
||||
constructor(
|
||||
schema: GraphQLSchema,
|
||||
// NOTE: this experimental optional second parameter is only needed in order
|
||||
// to support non-spec-compliant codebases. You should never need to use it.
|
||||
// It may disappear in the future.
|
||||
getFieldDefFn?: typeof getFieldDef,
|
||||
// Initial type may be provided in rare cases to facilitate traversals
|
||||
// beginning somewhere other than documents.
|
||||
initialType?: GraphQLType,
|
||||
): void {
|
||||
this._schema = schema;
|
||||
this._typeStack = [];
|
||||
this._parentTypeStack = [];
|
||||
this._inputTypeStack = [];
|
||||
this._fieldDefStack = [];
|
||||
this._defaultValueStack = [];
|
||||
this._directive = null;
|
||||
this._argument = null;
|
||||
this._enumValue = null;
|
||||
this._getFieldDef = getFieldDefFn || getFieldDef;
|
||||
if (initialType) {
|
||||
if (isInputType(initialType)) {
|
||||
this._inputTypeStack.push(initialType);
|
||||
}
|
||||
if (isCompositeType(initialType)) {
|
||||
this._parentTypeStack.push(initialType);
|
||||
}
|
||||
if (isOutputType(initialType)) {
|
||||
this._typeStack.push(initialType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getType(): ?GraphQLOutputType {
|
||||
if (this._typeStack.length > 0) {
|
||||
return this._typeStack[this._typeStack.length - 1];
|
||||
}
|
||||
}
|
||||
|
||||
getParentType(): ?GraphQLCompositeType {
|
||||
if (this._parentTypeStack.length > 0) {
|
||||
return this._parentTypeStack[this._parentTypeStack.length - 1];
|
||||
}
|
||||
}
|
||||
|
||||
getInputType(): ?GraphQLInputType {
|
||||
if (this._inputTypeStack.length > 0) {
|
||||
return this._inputTypeStack[this._inputTypeStack.length - 1];
|
||||
}
|
||||
}
|
||||
|
||||
getParentInputType(): ?GraphQLInputType {
|
||||
if (this._inputTypeStack.length > 1) {
|
||||
return this._inputTypeStack[this._inputTypeStack.length - 2];
|
||||
}
|
||||
}
|
||||
|
||||
getFieldDef(): ?GraphQLField<*, *> {
|
||||
if (this._fieldDefStack.length > 0) {
|
||||
return this._fieldDefStack[this._fieldDefStack.length - 1];
|
||||
}
|
||||
}
|
||||
|
||||
getDefaultValue(): ?mixed {
|
||||
if (this._defaultValueStack.length > 0) {
|
||||
return this._defaultValueStack[this._defaultValueStack.length - 1];
|
||||
}
|
||||
}
|
||||
|
||||
getDirective(): ?GraphQLDirective {
|
||||
return this._directive;
|
||||
}
|
||||
|
||||
getArgument(): ?GraphQLArgument {
|
||||
return this._argument;
|
||||
}
|
||||
|
||||
getEnumValue(): ?GraphQLEnumValue {
|
||||
return this._enumValue;
|
||||
}
|
||||
|
||||
enter(node: ASTNode) {
|
||||
const schema = this._schema;
|
||||
// Note: many of the types below are explicitly typed as "mixed" to drop
|
||||
// any assumptions of a valid schema to ensure runtime types are properly
|
||||
// checked before continuing since TypeInfo is used as part of validation
|
||||
// which occurs before guarantees of schema and document validity.
|
||||
switch (node.kind) {
|
||||
case Kind.SELECTION_SET:
|
||||
const namedType: mixed = getNamedType(this.getType());
|
||||
this._parentTypeStack.push(
|
||||
isCompositeType(namedType) ? namedType : undefined,
|
||||
);
|
||||
break;
|
||||
case Kind.FIELD:
|
||||
const parentType = this.getParentType();
|
||||
let fieldDef;
|
||||
let fieldType: mixed;
|
||||
if (parentType) {
|
||||
fieldDef = this._getFieldDef(schema, parentType, node);
|
||||
if (fieldDef) {
|
||||
fieldType = fieldDef.type;
|
||||
}
|
||||
}
|
||||
this._fieldDefStack.push(fieldDef);
|
||||
this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined);
|
||||
break;
|
||||
case Kind.DIRECTIVE:
|
||||
this._directive = schema.getDirective(node.name.value);
|
||||
break;
|
||||
case Kind.OPERATION_DEFINITION:
|
||||
let type: mixed;
|
||||
if (node.operation === 'query') {
|
||||
type = schema.getQueryType();
|
||||
} else if (node.operation === 'mutation') {
|
||||
type = schema.getMutationType();
|
||||
} else if (node.operation === 'subscription') {
|
||||
type = schema.getSubscriptionType();
|
||||
}
|
||||
this._typeStack.push(isObjectType(type) ? type : undefined);
|
||||
break;
|
||||
case Kind.INLINE_FRAGMENT:
|
||||
case Kind.FRAGMENT_DEFINITION:
|
||||
const typeConditionAST = node.typeCondition;
|
||||
const outputType: mixed = typeConditionAST
|
||||
? typeFromAST(schema, typeConditionAST)
|
||||
: getNamedType(this.getType());
|
||||
this._typeStack.push(isOutputType(outputType) ? outputType : undefined);
|
||||
break;
|
||||
case Kind.VARIABLE_DEFINITION:
|
||||
const inputType: mixed = typeFromAST(schema, node.type);
|
||||
this._inputTypeStack.push(
|
||||
isInputType(inputType) ? inputType : undefined,
|
||||
);
|
||||
break;
|
||||
case Kind.ARGUMENT:
|
||||
let argDef;
|
||||
let argType: mixed;
|
||||
const fieldOrDirective = this.getDirective() || this.getFieldDef();
|
||||
if (fieldOrDirective) {
|
||||
argDef = find(
|
||||
fieldOrDirective.args,
|
||||
arg => arg.name === node.name.value,
|
||||
);
|
||||
if (argDef) {
|
||||
argType = argDef.type;
|
||||
}
|
||||
}
|
||||
this._argument = argDef;
|
||||
this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);
|
||||
this._inputTypeStack.push(isInputType(argType) ? argType : undefined);
|
||||
break;
|
||||
case Kind.LIST:
|
||||
const listType: mixed = getNullableType(this.getInputType());
|
||||
const itemType: mixed = isListType(listType)
|
||||
? listType.ofType
|
||||
: listType;
|
||||
// List positions never have a default value.
|
||||
this._defaultValueStack.push(undefined);
|
||||
this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined);
|
||||
break;
|
||||
case Kind.OBJECT_FIELD:
|
||||
const objectType: mixed = getNamedType(this.getInputType());
|
||||
let inputFieldType: GraphQLInputType | void;
|
||||
let inputField: GraphQLInputField | void;
|
||||
if (isInputObjectType(objectType)) {
|
||||
inputField = objectType.getFields()[node.name.value];
|
||||
if (inputField) {
|
||||
inputFieldType = inputField.type;
|
||||
}
|
||||
}
|
||||
this._defaultValueStack.push(
|
||||
inputField ? inputField.defaultValue : undefined,
|
||||
);
|
||||
this._inputTypeStack.push(
|
||||
isInputType(inputFieldType) ? inputFieldType : undefined,
|
||||
);
|
||||
break;
|
||||
case Kind.ENUM:
|
||||
const enumType: mixed = getNamedType(this.getInputType());
|
||||
let enumValue;
|
||||
if (isEnumType(enumType)) {
|
||||
enumValue = enumType.getValue(node.value);
|
||||
}
|
||||
this._enumValue = enumValue;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
leave(node: ASTNode) {
|
||||
switch (node.kind) {
|
||||
case Kind.SELECTION_SET:
|
||||
this._parentTypeStack.pop();
|
||||
break;
|
||||
case Kind.FIELD:
|
||||
this._fieldDefStack.pop();
|
||||
this._typeStack.pop();
|
||||
break;
|
||||
case Kind.DIRECTIVE:
|
||||
this._directive = null;
|
||||
break;
|
||||
case Kind.OPERATION_DEFINITION:
|
||||
case Kind.INLINE_FRAGMENT:
|
||||
case Kind.FRAGMENT_DEFINITION:
|
||||
this._typeStack.pop();
|
||||
break;
|
||||
case Kind.VARIABLE_DEFINITION:
|
||||
this._inputTypeStack.pop();
|
||||
break;
|
||||
case Kind.ARGUMENT:
|
||||
this._argument = null;
|
||||
this._defaultValueStack.pop();
|
||||
this._inputTypeStack.pop();
|
||||
break;
|
||||
case Kind.LIST:
|
||||
case Kind.OBJECT_FIELD:
|
||||
this._defaultValueStack.pop();
|
||||
this._inputTypeStack.pop();
|
||||
break;
|
||||
case Kind.ENUM:
|
||||
this._enumValue = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Not exactly the same as the executor's definition of getFieldDef, in this
|
||||
* statically evaluated environment we do not always have an Object type,
|
||||
* and need to handle Interface and Union types.
|
||||
*/
|
||||
function getFieldDef(
|
||||
schema: GraphQLSchema,
|
||||
parentType: GraphQLType,
|
||||
fieldNode: FieldNode,
|
||||
): ?GraphQLField<*, *> {
|
||||
const name = fieldNode.name.value;
|
||||
if (
|
||||
name === SchemaMetaFieldDef.name &&
|
||||
schema.getQueryType() === parentType
|
||||
) {
|
||||
return SchemaMetaFieldDef;
|
||||
}
|
||||
if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return TypeMetaFieldDef;
|
||||
}
|
||||
if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) {
|
||||
return TypeNameMetaFieldDef;
|
||||
}
|
||||
if (isObjectType(parentType) || isInterfaceType(parentType)) {
|
||||
return parentType.getFields()[name];
|
||||
}
|
||||
}
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { Kind } from '../language/kinds';
|
||||
import { isObjectType, isInterfaceType, isEnumType, isInputObjectType, isListType, isCompositeType, isInputType, isOutputType, getNullableType, getNamedType } from '../type/definition';
|
||||
import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from '../type/introspection';
|
||||
import { typeFromAST } from './typeFromAST';
|
||||
import find from '../jsutils/find';
|
||||
/**
|
||||
* TypeInfo is a utility class which, given a GraphQL schema, can keep track
|
||||
* of the current field and type definitions at any point in a GraphQL document
|
||||
* AST during a recursive descent by calling `enter(node)` and `leave(node)`.
|
||||
*/
|
||||
|
||||
export var TypeInfo =
|
||||
/*#__PURE__*/
|
||||
function () {
|
||||
function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order
|
||||
// to support non-spec-compliant codebases. You should never need to use it.
|
||||
getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals
|
||||
initialType) {
|
||||
_defineProperty(this, "_schema", void 0);
|
||||
|
||||
_defineProperty(this, "_typeStack", void 0);
|
||||
|
||||
_defineProperty(this, "_parentTypeStack", void 0);
|
||||
|
||||
_defineProperty(this, "_inputTypeStack", void 0);
|
||||
|
||||
_defineProperty(this, "_fieldDefStack", void 0);
|
||||
|
||||
_defineProperty(this, "_defaultValueStack", void 0);
|
||||
|
||||
_defineProperty(this, "_directive", void 0);
|
||||
|
||||
_defineProperty(this, "_argument", void 0);
|
||||
|
||||
_defineProperty(this, "_enumValue", void 0);
|
||||
|
||||
_defineProperty(this, "_getFieldDef", void 0);
|
||||
|
||||
this._schema = schema;
|
||||
this._typeStack = [];
|
||||
this._parentTypeStack = [];
|
||||
this._inputTypeStack = [];
|
||||
this._fieldDefStack = [];
|
||||
this._defaultValueStack = [];
|
||||
this._directive = null;
|
||||
this._argument = null;
|
||||
this._enumValue = null;
|
||||
this._getFieldDef = getFieldDefFn || getFieldDef;
|
||||
|
||||
if (initialType) {
|
||||
if (isInputType(initialType)) {
|
||||
this._inputTypeStack.push(initialType);
|
||||
}
|
||||
|
||||
if (isCompositeType(initialType)) {
|
||||
this._parentTypeStack.push(initialType);
|
||||
}
|
||||
|
||||
if (isOutputType(initialType)) {
|
||||
this._typeStack.push(initialType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var _proto = TypeInfo.prototype;
|
||||
|
||||
_proto.getType = function getType() {
|
||||
if (this._typeStack.length > 0) {
|
||||
return this._typeStack[this._typeStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getParentType = function getParentType() {
|
||||
if (this._parentTypeStack.length > 0) {
|
||||
return this._parentTypeStack[this._parentTypeStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getInputType = function getInputType() {
|
||||
if (this._inputTypeStack.length > 0) {
|
||||
return this._inputTypeStack[this._inputTypeStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getParentInputType = function getParentInputType() {
|
||||
if (this._inputTypeStack.length > 1) {
|
||||
return this._inputTypeStack[this._inputTypeStack.length - 2];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getFieldDef = function getFieldDef() {
|
||||
if (this._fieldDefStack.length > 0) {
|
||||
return this._fieldDefStack[this._fieldDefStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getDefaultValue = function getDefaultValue() {
|
||||
if (this._defaultValueStack.length > 0) {
|
||||
return this._defaultValueStack[this._defaultValueStack.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getDirective = function getDirective() {
|
||||
return this._directive;
|
||||
};
|
||||
|
||||
_proto.getArgument = function getArgument() {
|
||||
return this._argument;
|
||||
};
|
||||
|
||||
_proto.getEnumValue = function getEnumValue() {
|
||||
return this._enumValue;
|
||||
};
|
||||
|
||||
_proto.enter = function enter(node) {
|
||||
var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop
|
||||
// any assumptions of a valid schema to ensure runtime types are properly
|
||||
// checked before continuing since TypeInfo is used as part of validation
|
||||
// which occurs before guarantees of schema and document validity.
|
||||
|
||||
switch (node.kind) {
|
||||
case Kind.SELECTION_SET:
|
||||
var namedType = getNamedType(this.getType());
|
||||
|
||||
this._parentTypeStack.push(isCompositeType(namedType) ? namedType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case Kind.FIELD:
|
||||
var parentType = this.getParentType();
|
||||
var fieldDef;
|
||||
var fieldType;
|
||||
|
||||
if (parentType) {
|
||||
fieldDef = this._getFieldDef(schema, parentType, node);
|
||||
|
||||
if (fieldDef) {
|
||||
fieldType = fieldDef.type;
|
||||
}
|
||||
}
|
||||
|
||||
this._fieldDefStack.push(fieldDef);
|
||||
|
||||
this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case Kind.DIRECTIVE:
|
||||
this._directive = schema.getDirective(node.name.value);
|
||||
break;
|
||||
|
||||
case Kind.OPERATION_DEFINITION:
|
||||
var type;
|
||||
|
||||
if (node.operation === 'query') {
|
||||
type = schema.getQueryType();
|
||||
} else if (node.operation === 'mutation') {
|
||||
type = schema.getMutationType();
|
||||
} else if (node.operation === 'subscription') {
|
||||
type = schema.getSubscriptionType();
|
||||
}
|
||||
|
||||
this._typeStack.push(isObjectType(type) ? type : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case Kind.INLINE_FRAGMENT:
|
||||
case Kind.FRAGMENT_DEFINITION:
|
||||
var typeConditionAST = node.typeCondition;
|
||||
var outputType = typeConditionAST ? typeFromAST(schema, typeConditionAST) : getNamedType(this.getType());
|
||||
|
||||
this._typeStack.push(isOutputType(outputType) ? outputType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case Kind.VARIABLE_DEFINITION:
|
||||
var inputType = typeFromAST(schema, node.type);
|
||||
|
||||
this._inputTypeStack.push(isInputType(inputType) ? inputType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case Kind.ARGUMENT:
|
||||
var argDef;
|
||||
var argType;
|
||||
var fieldOrDirective = this.getDirective() || this.getFieldDef();
|
||||
|
||||
if (fieldOrDirective) {
|
||||
argDef = find(fieldOrDirective.args, function (arg) {
|
||||
return arg.name === node.name.value;
|
||||
});
|
||||
|
||||
if (argDef) {
|
||||
argType = argDef.type;
|
||||
}
|
||||
}
|
||||
|
||||
this._argument = argDef;
|
||||
|
||||
this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);
|
||||
|
||||
this._inputTypeStack.push(isInputType(argType) ? argType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case Kind.LIST:
|
||||
var listType = getNullableType(this.getInputType());
|
||||
var itemType = isListType(listType) ? listType.ofType : listType; // List positions never have a default value.
|
||||
|
||||
this._defaultValueStack.push(undefined);
|
||||
|
||||
this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case Kind.OBJECT_FIELD:
|
||||
var objectType = getNamedType(this.getInputType());
|
||||
var inputFieldType;
|
||||
var inputField;
|
||||
|
||||
if (isInputObjectType(objectType)) {
|
||||
inputField = objectType.getFields()[node.name.value];
|
||||
|
||||
if (inputField) {
|
||||
inputFieldType = inputField.type;
|
||||
}
|
||||
}
|
||||
|
||||
this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined);
|
||||
|
||||
this._inputTypeStack.push(isInputType(inputFieldType) ? inputFieldType : undefined);
|
||||
|
||||
break;
|
||||
|
||||
case Kind.ENUM:
|
||||
var enumType = getNamedType(this.getInputType());
|
||||
var enumValue;
|
||||
|
||||
if (isEnumType(enumType)) {
|
||||
enumValue = enumType.getValue(node.value);
|
||||
}
|
||||
|
||||
this._enumValue = enumValue;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.leave = function leave(node) {
|
||||
switch (node.kind) {
|
||||
case Kind.SELECTION_SET:
|
||||
this._parentTypeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case Kind.FIELD:
|
||||
this._fieldDefStack.pop();
|
||||
|
||||
this._typeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case Kind.DIRECTIVE:
|
||||
this._directive = null;
|
||||
break;
|
||||
|
||||
case Kind.OPERATION_DEFINITION:
|
||||
case Kind.INLINE_FRAGMENT:
|
||||
case Kind.FRAGMENT_DEFINITION:
|
||||
this._typeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case Kind.VARIABLE_DEFINITION:
|
||||
this._inputTypeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case Kind.ARGUMENT:
|
||||
this._argument = null;
|
||||
|
||||
this._defaultValueStack.pop();
|
||||
|
||||
this._inputTypeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case Kind.LIST:
|
||||
case Kind.OBJECT_FIELD:
|
||||
this._defaultValueStack.pop();
|
||||
|
||||
this._inputTypeStack.pop();
|
||||
|
||||
break;
|
||||
|
||||
case Kind.ENUM:
|
||||
this._enumValue = null;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
return TypeInfo;
|
||||
}();
|
||||
/**
|
||||
* Not exactly the same as the executor's definition of getFieldDef, in this
|
||||
* statically evaluated environment we do not always have an Object type,
|
||||
* and need to handle Interface and Union types.
|
||||
*/
|
||||
|
||||
function getFieldDef(schema, parentType, fieldNode) {
|
||||
var name = fieldNode.name.value;
|
||||
|
||||
if (name === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return SchemaMetaFieldDef;
|
||||
}
|
||||
|
||||
if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
|
||||
return TypeMetaFieldDef;
|
||||
}
|
||||
|
||||
if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) {
|
||||
return TypeNameMetaFieldDef;
|
||||
}
|
||||
|
||||
if (isObjectType(parentType) || isInterfaceType(parentType)) {
|
||||
return parentType.getFields()[name];
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.assertValidName = assertValidName;
|
||||
exports.isValidNameError = isValidNameError;
|
||||
|
||||
var _GraphQLError = require("../error/GraphQLError");
|
||||
|
||||
var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
|
||||
/**
|
||||
* Upholds the spec rules about naming.
|
||||
*/
|
||||
|
||||
function assertValidName(name) {
|
||||
var error = isValidNameError(name);
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
/**
|
||||
* Returns an Error if a name is invalid.
|
||||
*/
|
||||
|
||||
|
||||
function isValidNameError(name, node) {
|
||||
!(typeof name === 'string') ? (0, _invariant.default)(0, 'Expected string') : void 0;
|
||||
|
||||
if (name.length > 1 && name[0] === '_' && name[1] === '_') {
|
||||
return new _GraphQLError.GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by ") + 'GraphQL introspection.', node);
|
||||
}
|
||||
|
||||
if (!NAME_RX.test(name)) {
|
||||
return new _GraphQLError.GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."), node);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import type { ASTNode } from '../language/ast';
|
||||
import invariant from '../jsutils/invariant';
|
||||
|
||||
const NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
|
||||
|
||||
/**
|
||||
* Upholds the spec rules about naming.
|
||||
*/
|
||||
export function assertValidName(name: string): string {
|
||||
const error = isValidNameError(name);
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an Error if a name is invalid.
|
||||
*/
|
||||
export function isValidNameError(
|
||||
name: string,
|
||||
node?: ASTNode | void,
|
||||
): GraphQLError | void {
|
||||
invariant(typeof name === 'string', 'Expected string');
|
||||
if (name.length > 1 && name[0] === '_' && name[1] === '_') {
|
||||
return new GraphQLError(
|
||||
`Name "${name}" must not begin with "__", which is reserved by ` +
|
||||
'GraphQL introspection.',
|
||||
node,
|
||||
);
|
||||
}
|
||||
if (!NAME_RX.test(name)) {
|
||||
return new GraphQLError(
|
||||
`Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "${name}" does not.`,
|
||||
node,
|
||||
);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import invariant from '../jsutils/invariant';
|
||||
var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
|
||||
/**
|
||||
* Upholds the spec rules about naming.
|
||||
*/
|
||||
|
||||
export function assertValidName(name) {
|
||||
var error = isValidNameError(name);
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
/**
|
||||
* Returns an Error if a name is invalid.
|
||||
*/
|
||||
|
||||
export function isValidNameError(name, node) {
|
||||
!(typeof name === 'string') ? invariant(0, 'Expected string') : void 0;
|
||||
|
||||
if (name.length > 1 && name[0] === '_' && name[1] === '_') {
|
||||
return new GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by ") + 'GraphQL introspection.', node);
|
||||
}
|
||||
|
||||
if (!NAME_RX.test(name)) {
|
||||
return new GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."), node);
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.astFromValue = astFromValue;
|
||||
|
||||
var _iterall = require("iterall");
|
||||
|
||||
var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
|
||||
|
||||
var _isNullish = _interopRequireDefault(require("../jsutils/isNullish"));
|
||||
|
||||
var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
|
||||
|
||||
var _objectValues = _interopRequireDefault(require("../jsutils/objectValues"));
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _scalars = require("../type/scalars");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
/**
|
||||
* Produces a GraphQL Value AST given a JavaScript value.
|
||||
*
|
||||
* A GraphQL type must be provided, which will be used to interpret different
|
||||
* JavaScript values.
|
||||
*
|
||||
* | JSON Value | GraphQL Value |
|
||||
* | ------------- | -------------------- |
|
||||
* | Object | Input Object |
|
||||
* | Array | List |
|
||||
* | Boolean | Boolean |
|
||||
* | String | String / Enum Value |
|
||||
* | Number | Int / Float |
|
||||
* | Mixed | Enum Value |
|
||||
* | null | NullValue |
|
||||
*
|
||||
*/
|
||||
function astFromValue(value, type) {
|
||||
if ((0, _definition.isNonNullType)(type)) {
|
||||
var astValue = astFromValue(value, type.ofType);
|
||||
|
||||
if (astValue && astValue.kind === _kinds.Kind.NULL) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return astValue;
|
||||
} // only explicit null, not undefined, NaN
|
||||
|
||||
|
||||
if (value === null) {
|
||||
return {
|
||||
kind: _kinds.Kind.NULL
|
||||
};
|
||||
} // undefined, NaN
|
||||
|
||||
|
||||
if ((0, _isInvalid.default)(value)) {
|
||||
return null;
|
||||
} // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
|
||||
// the value is not an array, convert the value using the list's item type.
|
||||
|
||||
|
||||
if ((0, _definition.isListType)(type)) {
|
||||
var itemType = type.ofType;
|
||||
|
||||
if ((0, _iterall.isCollection)(value)) {
|
||||
var valuesNodes = [];
|
||||
(0, _iterall.forEach)(value, function (item) {
|
||||
var itemNode = astFromValue(item, itemType);
|
||||
|
||||
if (itemNode) {
|
||||
valuesNodes.push(itemNode);
|
||||
}
|
||||
});
|
||||
return {
|
||||
kind: _kinds.Kind.LIST,
|
||||
values: valuesNodes
|
||||
};
|
||||
}
|
||||
|
||||
return astFromValue(value, itemType);
|
||||
} // Populate the fields of the input object by creating ASTs from each value
|
||||
// in the JavaScript object according to the fields in the input type.
|
||||
|
||||
|
||||
if ((0, _definition.isInputObjectType)(type)) {
|
||||
if (value === null || _typeof(value) !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
var fields = (0, _objectValues.default)(type.getFields());
|
||||
var fieldNodes = [];
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var field = _step.value;
|
||||
var fieldValue = astFromValue(value[field.name], field.type);
|
||||
|
||||
if (fieldValue) {
|
||||
fieldNodes.push({
|
||||
kind: _kinds.Kind.OBJECT_FIELD,
|
||||
name: {
|
||||
kind: _kinds.Kind.NAME,
|
||||
value: field.name
|
||||
},
|
||||
value: fieldValue
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
kind: _kinds.Kind.OBJECT,
|
||||
fields: fieldNodes
|
||||
};
|
||||
}
|
||||
|
||||
if ((0, _definition.isScalarType)(type) || (0, _definition.isEnumType)(type)) {
|
||||
// Since value is an internally represented value, it must be serialized
|
||||
// to an externally represented value before converting into an AST.
|
||||
var serialized = type.serialize(value);
|
||||
|
||||
if ((0, _isNullish.default)(serialized)) {
|
||||
return null;
|
||||
} // Others serialize based on their corresponding JavaScript scalar types.
|
||||
|
||||
|
||||
if (typeof serialized === 'boolean') {
|
||||
return {
|
||||
kind: _kinds.Kind.BOOLEAN,
|
||||
value: serialized
|
||||
};
|
||||
} // JavaScript numbers can be Int or Float values.
|
||||
|
||||
|
||||
if (typeof serialized === 'number') {
|
||||
var stringNum = String(serialized);
|
||||
return integerStringRegExp.test(stringNum) ? {
|
||||
kind: _kinds.Kind.INT,
|
||||
value: stringNum
|
||||
} : {
|
||||
kind: _kinds.Kind.FLOAT,
|
||||
value: stringNum
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof serialized === 'string') {
|
||||
// Enum types use Enum literals.
|
||||
if ((0, _definition.isEnumType)(type)) {
|
||||
return {
|
||||
kind: _kinds.Kind.ENUM,
|
||||
value: serialized
|
||||
};
|
||||
} // ID types can use Int literals.
|
||||
|
||||
|
||||
if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) {
|
||||
return {
|
||||
kind: _kinds.Kind.INT,
|
||||
value: serialized
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: _kinds.Kind.STRING,
|
||||
value: serialized
|
||||
};
|
||||
}
|
||||
|
||||
throw new TypeError("Cannot convert value to AST: ".concat((0, _inspect.default)(serialized)));
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unknown type: ".concat(type, "."));
|
||||
}
|
||||
/**
|
||||
* IntValue:
|
||||
* - NegativeSign? 0
|
||||
* - NegativeSign? NonZeroDigit ( Digit+ )?
|
||||
*/
|
||||
|
||||
|
||||
var integerStringRegExp = /^-?(0|[1-9][0-9]*)$/;
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { forEach, isCollection } from 'iterall';
|
||||
|
||||
import inspect from '../jsutils/inspect';
|
||||
import isNullish from '../jsutils/isNullish';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import type { ValueNode } from '../language/ast';
|
||||
import { Kind } from '../language/kinds';
|
||||
import type { GraphQLInputType } from '../type/definition';
|
||||
import {
|
||||
isScalarType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
isListType,
|
||||
isNonNullType,
|
||||
} from '../type/definition';
|
||||
import { GraphQLID } from '../type/scalars';
|
||||
|
||||
/**
|
||||
* Produces a GraphQL Value AST given a JavaScript value.
|
||||
*
|
||||
* A GraphQL type must be provided, which will be used to interpret different
|
||||
* JavaScript values.
|
||||
*
|
||||
* | JSON Value | GraphQL Value |
|
||||
* | ------------- | -------------------- |
|
||||
* | Object | Input Object |
|
||||
* | Array | List |
|
||||
* | Boolean | Boolean |
|
||||
* | String | String / Enum Value |
|
||||
* | Number | Int / Float |
|
||||
* | Mixed | Enum Value |
|
||||
* | null | NullValue |
|
||||
*
|
||||
*/
|
||||
export function astFromValue(value: mixed, type: GraphQLInputType): ?ValueNode {
|
||||
if (isNonNullType(type)) {
|
||||
const astValue = astFromValue(value, type.ofType);
|
||||
if (astValue && astValue.kind === Kind.NULL) {
|
||||
return null;
|
||||
}
|
||||
return astValue;
|
||||
}
|
||||
|
||||
// only explicit null, not undefined, NaN
|
||||
if (value === null) {
|
||||
return { kind: Kind.NULL };
|
||||
}
|
||||
|
||||
// undefined, NaN
|
||||
if (isInvalid(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
|
||||
// the value is not an array, convert the value using the list's item type.
|
||||
if (isListType(type)) {
|
||||
const itemType = type.ofType;
|
||||
if (isCollection(value)) {
|
||||
const valuesNodes = [];
|
||||
forEach((value: any), item => {
|
||||
const itemNode = astFromValue(item, itemType);
|
||||
if (itemNode) {
|
||||
valuesNodes.push(itemNode);
|
||||
}
|
||||
});
|
||||
return { kind: Kind.LIST, values: valuesNodes };
|
||||
}
|
||||
return astFromValue(value, itemType);
|
||||
}
|
||||
|
||||
// Populate the fields of the input object by creating ASTs from each value
|
||||
// in the JavaScript object according to the fields in the input type.
|
||||
if (isInputObjectType(type)) {
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return null;
|
||||
}
|
||||
const fields = objectValues(type.getFields());
|
||||
const fieldNodes = [];
|
||||
for (const field of fields) {
|
||||
const fieldValue = astFromValue(value[field.name], field.type);
|
||||
if (fieldValue) {
|
||||
fieldNodes.push({
|
||||
kind: Kind.OBJECT_FIELD,
|
||||
name: { kind: Kind.NAME, value: field.name },
|
||||
value: fieldValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { kind: Kind.OBJECT, fields: fieldNodes };
|
||||
}
|
||||
|
||||
if (isScalarType(type) || isEnumType(type)) {
|
||||
// Since value is an internally represented value, it must be serialized
|
||||
// to an externally represented value before converting into an AST.
|
||||
const serialized = type.serialize(value);
|
||||
if (isNullish(serialized)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Others serialize based on their corresponding JavaScript scalar types.
|
||||
if (typeof serialized === 'boolean') {
|
||||
return { kind: Kind.BOOLEAN, value: serialized };
|
||||
}
|
||||
|
||||
// JavaScript numbers can be Int or Float values.
|
||||
if (typeof serialized === 'number') {
|
||||
const stringNum = String(serialized);
|
||||
return integerStringRegExp.test(stringNum)
|
||||
? { kind: Kind.INT, value: stringNum }
|
||||
: { kind: Kind.FLOAT, value: stringNum };
|
||||
}
|
||||
|
||||
if (typeof serialized === 'string') {
|
||||
// Enum types use Enum literals.
|
||||
if (isEnumType(type)) {
|
||||
return { kind: Kind.ENUM, value: serialized };
|
||||
}
|
||||
|
||||
// ID types can use Int literals.
|
||||
if (type === GraphQLID && integerStringRegExp.test(serialized)) {
|
||||
return { kind: Kind.INT, value: serialized };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: Kind.STRING,
|
||||
value: serialized,
|
||||
};
|
||||
}
|
||||
|
||||
throw new TypeError(`Cannot convert value to AST: ${inspect(serialized)}`);
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
throw new Error(`Unknown type: ${(type: empty)}.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* IntValue:
|
||||
* - NegativeSign? 0
|
||||
* - NegativeSign? NonZeroDigit ( Digit+ )?
|
||||
*/
|
||||
const integerStringRegExp = /^-?(0|[1-9][0-9]*)$/;
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { forEach, isCollection } from 'iterall';
|
||||
import inspect from '../jsutils/inspect';
|
||||
import isNullish from '../jsutils/isNullish';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition';
|
||||
import { GraphQLID } from '../type/scalars';
|
||||
/**
|
||||
* Produces a GraphQL Value AST given a JavaScript value.
|
||||
*
|
||||
* A GraphQL type must be provided, which will be used to interpret different
|
||||
* JavaScript values.
|
||||
*
|
||||
* | JSON Value | GraphQL Value |
|
||||
* | ------------- | -------------------- |
|
||||
* | Object | Input Object |
|
||||
* | Array | List |
|
||||
* | Boolean | Boolean |
|
||||
* | String | String / Enum Value |
|
||||
* | Number | Int / Float |
|
||||
* | Mixed | Enum Value |
|
||||
* | null | NullValue |
|
||||
*
|
||||
*/
|
||||
|
||||
export function astFromValue(value, type) {
|
||||
if (isNonNullType(type)) {
|
||||
var astValue = astFromValue(value, type.ofType);
|
||||
|
||||
if (astValue && astValue.kind === Kind.NULL) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return astValue;
|
||||
} // only explicit null, not undefined, NaN
|
||||
|
||||
|
||||
if (value === null) {
|
||||
return {
|
||||
kind: Kind.NULL
|
||||
};
|
||||
} // undefined, NaN
|
||||
|
||||
|
||||
if (isInvalid(value)) {
|
||||
return null;
|
||||
} // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
|
||||
// the value is not an array, convert the value using the list's item type.
|
||||
|
||||
|
||||
if (isListType(type)) {
|
||||
var itemType = type.ofType;
|
||||
|
||||
if (isCollection(value)) {
|
||||
var valuesNodes = [];
|
||||
forEach(value, function (item) {
|
||||
var itemNode = astFromValue(item, itemType);
|
||||
|
||||
if (itemNode) {
|
||||
valuesNodes.push(itemNode);
|
||||
}
|
||||
});
|
||||
return {
|
||||
kind: Kind.LIST,
|
||||
values: valuesNodes
|
||||
};
|
||||
}
|
||||
|
||||
return astFromValue(value, itemType);
|
||||
} // Populate the fields of the input object by creating ASTs from each value
|
||||
// in the JavaScript object according to the fields in the input type.
|
||||
|
||||
|
||||
if (isInputObjectType(type)) {
|
||||
if (value === null || _typeof(value) !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
var fields = objectValues(type.getFields());
|
||||
var fieldNodes = [];
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var field = _step.value;
|
||||
var fieldValue = astFromValue(value[field.name], field.type);
|
||||
|
||||
if (fieldValue) {
|
||||
fieldNodes.push({
|
||||
kind: Kind.OBJECT_FIELD,
|
||||
name: {
|
||||
kind: Kind.NAME,
|
||||
value: field.name
|
||||
},
|
||||
value: fieldValue
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
kind: Kind.OBJECT,
|
||||
fields: fieldNodes
|
||||
};
|
||||
}
|
||||
|
||||
if (isScalarType(type) || isEnumType(type)) {
|
||||
// Since value is an internally represented value, it must be serialized
|
||||
// to an externally represented value before converting into an AST.
|
||||
var serialized = type.serialize(value);
|
||||
|
||||
if (isNullish(serialized)) {
|
||||
return null;
|
||||
} // Others serialize based on their corresponding JavaScript scalar types.
|
||||
|
||||
|
||||
if (typeof serialized === 'boolean') {
|
||||
return {
|
||||
kind: Kind.BOOLEAN,
|
||||
value: serialized
|
||||
};
|
||||
} // JavaScript numbers can be Int or Float values.
|
||||
|
||||
|
||||
if (typeof serialized === 'number') {
|
||||
var stringNum = String(serialized);
|
||||
return integerStringRegExp.test(stringNum) ? {
|
||||
kind: Kind.INT,
|
||||
value: stringNum
|
||||
} : {
|
||||
kind: Kind.FLOAT,
|
||||
value: stringNum
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof serialized === 'string') {
|
||||
// Enum types use Enum literals.
|
||||
if (isEnumType(type)) {
|
||||
return {
|
||||
kind: Kind.ENUM,
|
||||
value: serialized
|
||||
};
|
||||
} // ID types can use Int literals.
|
||||
|
||||
|
||||
if (type === GraphQLID && integerStringRegExp.test(serialized)) {
|
||||
return {
|
||||
kind: Kind.INT,
|
||||
value: serialized
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: Kind.STRING,
|
||||
value: serialized
|
||||
};
|
||||
}
|
||||
|
||||
throw new TypeError("Cannot convert value to AST: ".concat(inspect(serialized)));
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unknown type: ".concat(type, "."));
|
||||
}
|
||||
/**
|
||||
* IntValue:
|
||||
* - NegativeSign? 0
|
||||
* - NegativeSign? NonZeroDigit ( Digit+ )?
|
||||
*/
|
||||
|
||||
var integerStringRegExp = /^-?(0|[1-9][0-9]*)$/;
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.buildASTSchema = buildASTSchema;
|
||||
exports.getDescription = getDescription;
|
||||
exports.buildSchema = buildSchema;
|
||||
exports.ASTDefinitionBuilder = void 0;
|
||||
|
||||
var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
|
||||
|
||||
var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
|
||||
|
||||
var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
|
||||
|
||||
var _valueFromAST = require("./valueFromAST");
|
||||
|
||||
var _validate = require("../validation/validate");
|
||||
|
||||
var _blockStringValue = _interopRequireDefault(require("../language/blockStringValue"));
|
||||
|
||||
var _lexer = require("../language/lexer");
|
||||
|
||||
var _parser = require("../language/parser");
|
||||
|
||||
var _values = require("../execution/values");
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _predicates = require("../language/predicates");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _directives = require("../type/directives");
|
||||
|
||||
var _introspection = require("../type/introspection");
|
||||
|
||||
var _scalars = require("../type/scalars");
|
||||
|
||||
var _schema = require("../type/schema");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
||||
|
||||
/**
|
||||
* This takes the ast of a schema document produced by the parse function in
|
||||
* src/language/parser.js.
|
||||
*
|
||||
* If no schema definition is provided, then it will look for types named Query
|
||||
* and Mutation.
|
||||
*
|
||||
* Given that AST it constructs a GraphQLSchema. The resulting schema
|
||||
* has no resolve methods, so execution will use default resolvers.
|
||||
*
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
function buildASTSchema(documentAST, options) {
|
||||
!(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0;
|
||||
|
||||
if (!options || !(options.assumeValid || options.assumeValidSDL)) {
|
||||
(0, _validate.assertValidSDL)(documentAST);
|
||||
}
|
||||
|
||||
var schemaDef;
|
||||
var typeDefs = [];
|
||||
var nodeMap = Object.create(null);
|
||||
var directiveDefs = [];
|
||||
|
||||
for (var i = 0; i < documentAST.definitions.length; i++) {
|
||||
var def = documentAST.definitions[i];
|
||||
|
||||
if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) {
|
||||
schemaDef = def;
|
||||
} else if ((0, _predicates.isTypeDefinitionNode)(def)) {
|
||||
var typeName = def.name.value;
|
||||
|
||||
if (nodeMap[typeName]) {
|
||||
throw new Error("Type \"".concat(typeName, "\" was defined more than once."));
|
||||
}
|
||||
|
||||
typeDefs.push(def);
|
||||
nodeMap[typeName] = def;
|
||||
} else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
|
||||
directiveDefs.push(def);
|
||||
}
|
||||
}
|
||||
|
||||
var operationTypes = schemaDef ? getOperationTypes(schemaDef) : {
|
||||
query: nodeMap.Query,
|
||||
mutation: nodeMap.Mutation,
|
||||
subscription: nodeMap.Subscription
|
||||
};
|
||||
var definitionBuilder = new ASTDefinitionBuilder(nodeMap, options, function (typeRef) {
|
||||
throw new Error("Type \"".concat(typeRef.name.value, "\" not found in document."));
|
||||
});
|
||||
var directives = directiveDefs.map(function (def) {
|
||||
return definitionBuilder.buildDirective(def);
|
||||
}); // If specified directives were not explicitly declared, add them.
|
||||
|
||||
if (!directives.some(function (directive) {
|
||||
return directive.name === 'skip';
|
||||
})) {
|
||||
directives.push(_directives.GraphQLSkipDirective);
|
||||
}
|
||||
|
||||
if (!directives.some(function (directive) {
|
||||
return directive.name === 'include';
|
||||
})) {
|
||||
directives.push(_directives.GraphQLIncludeDirective);
|
||||
}
|
||||
|
||||
if (!directives.some(function (directive) {
|
||||
return directive.name === 'deprecated';
|
||||
})) {
|
||||
directives.push(_directives.GraphQLDeprecatedDirective);
|
||||
} // Note: While this could make early assertions to get the correctly
|
||||
// typed values below, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
|
||||
|
||||
return new _schema.GraphQLSchema({
|
||||
query: operationTypes.query ? definitionBuilder.buildType(operationTypes.query) : null,
|
||||
mutation: operationTypes.mutation ? definitionBuilder.buildType(operationTypes.mutation) : null,
|
||||
subscription: operationTypes.subscription ? definitionBuilder.buildType(operationTypes.subscription) : null,
|
||||
types: typeDefs.map(function (node) {
|
||||
return definitionBuilder.buildType(node);
|
||||
}),
|
||||
directives: directives,
|
||||
astNode: schemaDef,
|
||||
assumeValid: options && options.assumeValid,
|
||||
allowedLegacyNames: options && options.allowedLegacyNames
|
||||
});
|
||||
|
||||
function getOperationTypes(schema) {
|
||||
var opTypes = {};
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = schema.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var operationType = _step.value;
|
||||
var _typeName = operationType.type.name.value;
|
||||
var operation = operationType.operation;
|
||||
|
||||
if (opTypes[operation]) {
|
||||
throw new Error("Must provide only one ".concat(operation, " type in schema."));
|
||||
}
|
||||
|
||||
if (!nodeMap[_typeName]) {
|
||||
throw new Error("Specified ".concat(operation, " type \"").concat(_typeName, "\" not found in document."));
|
||||
}
|
||||
|
||||
opTypes[operation] = operationType.type;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return opTypes;
|
||||
}
|
||||
}
|
||||
|
||||
var ASTDefinitionBuilder =
|
||||
/*#__PURE__*/
|
||||
function () {
|
||||
function ASTDefinitionBuilder(typeDefinitionsMap, options, resolveType) {
|
||||
_defineProperty(this, "_typeDefinitionsMap", void 0);
|
||||
|
||||
_defineProperty(this, "_options", void 0);
|
||||
|
||||
_defineProperty(this, "_resolveType", void 0);
|
||||
|
||||
_defineProperty(this, "_cache", void 0);
|
||||
|
||||
this._typeDefinitionsMap = typeDefinitionsMap;
|
||||
this._options = options;
|
||||
this._resolveType = resolveType; // Initialize to the GraphQL built in scalars and introspection types.
|
||||
|
||||
this._cache = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) {
|
||||
return type.name;
|
||||
});
|
||||
}
|
||||
|
||||
var _proto = ASTDefinitionBuilder.prototype;
|
||||
|
||||
_proto.buildType = function buildType(node) {
|
||||
var typeName = node.name.value;
|
||||
|
||||
if (!this._cache[typeName]) {
|
||||
if (node.kind === _kinds.Kind.NAMED_TYPE) {
|
||||
var defNode = this._typeDefinitionsMap[typeName];
|
||||
this._cache[typeName] = defNode ? this._makeSchemaDef(defNode) : this._resolveType(node);
|
||||
} else {
|
||||
this._cache[typeName] = this._makeSchemaDef(node);
|
||||
}
|
||||
}
|
||||
|
||||
return this._cache[typeName];
|
||||
};
|
||||
|
||||
_proto._buildWrappedType = function _buildWrappedType(typeNode) {
|
||||
if (typeNode.kind === _kinds.Kind.LIST_TYPE) {
|
||||
return (0, _definition.GraphQLList)(this._buildWrappedType(typeNode.type));
|
||||
}
|
||||
|
||||
if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) {
|
||||
return (0, _definition.GraphQLNonNull)( // Note: GraphQLNonNull constructor validates this type
|
||||
this._buildWrappedType(typeNode.type));
|
||||
}
|
||||
|
||||
return this.buildType(typeNode);
|
||||
};
|
||||
|
||||
_proto.buildDirective = function buildDirective(directiveNode) {
|
||||
return new _directives.GraphQLDirective({
|
||||
name: directiveNode.name.value,
|
||||
description: getDescription(directiveNode, this._options),
|
||||
locations: directiveNode.locations.map(function (node) {
|
||||
return node.value;
|
||||
}),
|
||||
args: directiveNode.arguments && this._makeInputValues(directiveNode.arguments),
|
||||
astNode: directiveNode
|
||||
});
|
||||
};
|
||||
|
||||
_proto.buildField = function buildField(field) {
|
||||
return {
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// value, that would throw immediately while type system validation
|
||||
// with validateSchema() will produce more actionable results.
|
||||
type: this._buildWrappedType(field.type),
|
||||
description: getDescription(field, this._options),
|
||||
args: field.arguments && this._makeInputValues(field.arguments),
|
||||
deprecationReason: getDeprecationReason(field),
|
||||
astNode: field
|
||||
};
|
||||
};
|
||||
|
||||
_proto.buildInputField = function buildInputField(value) {
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// value, that would throw immediately while type system validation
|
||||
var type = this._buildWrappedType(value.type);
|
||||
|
||||
return {
|
||||
name: value.name.value,
|
||||
type: type,
|
||||
description: getDescription(value, this._options),
|
||||
defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type),
|
||||
astNode: value
|
||||
};
|
||||
};
|
||||
|
||||
_proto.buildEnumValue = function buildEnumValue(value) {
|
||||
return {
|
||||
description: getDescription(value, this._options),
|
||||
deprecationReason: getDeprecationReason(value),
|
||||
astNode: value
|
||||
};
|
||||
};
|
||||
|
||||
_proto._makeSchemaDef = function _makeSchemaDef(def) {
|
||||
switch (def.kind) {
|
||||
case _kinds.Kind.OBJECT_TYPE_DEFINITION:
|
||||
return this._makeTypeDef(def);
|
||||
|
||||
case _kinds.Kind.INTERFACE_TYPE_DEFINITION:
|
||||
return this._makeInterfaceDef(def);
|
||||
|
||||
case _kinds.Kind.ENUM_TYPE_DEFINITION:
|
||||
return this._makeEnumDef(def);
|
||||
|
||||
case _kinds.Kind.UNION_TYPE_DEFINITION:
|
||||
return this._makeUnionDef(def);
|
||||
|
||||
case _kinds.Kind.SCALAR_TYPE_DEFINITION:
|
||||
return this._makeScalarDef(def);
|
||||
|
||||
case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION:
|
||||
return this._makeInputObjectDef(def);
|
||||
|
||||
default:
|
||||
throw new Error("Type kind \"".concat(def.kind, "\" not supported."));
|
||||
}
|
||||
};
|
||||
|
||||
_proto._makeTypeDef = function _makeTypeDef(def) {
|
||||
var _this = this;
|
||||
|
||||
var interfaces = def.interfaces;
|
||||
return new _definition.GraphQLObjectType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: function fields() {
|
||||
return _this._makeFieldDefMap(def);
|
||||
},
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
interfaces: interfaces ? function () {
|
||||
return interfaces.map(function (ref) {
|
||||
return _this.buildType(ref);
|
||||
});
|
||||
} : [],
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeFieldDefMap = function _makeFieldDefMap(def) {
|
||||
var _this2 = this;
|
||||
|
||||
return def.fields ? (0, _keyValMap.default)(def.fields, function (field) {
|
||||
return field.name.value;
|
||||
}, function (field) {
|
||||
return _this2.buildField(field);
|
||||
}) : {};
|
||||
};
|
||||
|
||||
_proto._makeInputValues = function _makeInputValues(values) {
|
||||
var _this3 = this;
|
||||
|
||||
return (0, _keyValMap.default)(values, function (value) {
|
||||
return value.name.value;
|
||||
}, function (value) {
|
||||
return _this3.buildInputField(value);
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeInterfaceDef = function _makeInterfaceDef(def) {
|
||||
var _this4 = this;
|
||||
|
||||
return new _definition.GraphQLInterfaceType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: function fields() {
|
||||
return _this4._makeFieldDefMap(def);
|
||||
},
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeEnumDef = function _makeEnumDef(def) {
|
||||
return new _definition.GraphQLEnumType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
values: this._makeValueDefMap(def),
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeValueDefMap = function _makeValueDefMap(def) {
|
||||
var _this5 = this;
|
||||
|
||||
return def.values ? (0, _keyValMap.default)(def.values, function (enumValue) {
|
||||
return enumValue.name.value;
|
||||
}, function (enumValue) {
|
||||
return _this5.buildEnumValue(enumValue);
|
||||
}) : {};
|
||||
};
|
||||
|
||||
_proto._makeUnionDef = function _makeUnionDef(def) {
|
||||
var _this6 = this;
|
||||
|
||||
var types = def.types;
|
||||
return new _definition.GraphQLUnionType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// values below, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
types: types ? function () {
|
||||
return types.map(function (ref) {
|
||||
return _this6.buildType(ref);
|
||||
});
|
||||
} : [],
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeScalarDef = function _makeScalarDef(def) {
|
||||
return new _definition.GraphQLScalarType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
astNode: def,
|
||||
serialize: function serialize(value) {
|
||||
return value;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeInputObjectDef = function _makeInputObjectDef(def) {
|
||||
var _this7 = this;
|
||||
|
||||
return new _definition.GraphQLInputObjectType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: function fields() {
|
||||
return def.fields ? _this7._makeInputValues(def.fields) : {};
|
||||
},
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
return ASTDefinitionBuilder;
|
||||
}();
|
||||
/**
|
||||
* Given a field or enum value node, returns the string value for the
|
||||
* deprecation reason.
|
||||
*/
|
||||
|
||||
|
||||
exports.ASTDefinitionBuilder = ASTDefinitionBuilder;
|
||||
|
||||
function getDeprecationReason(node) {
|
||||
var deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node);
|
||||
return deprecated && deprecated.reason;
|
||||
}
|
||||
/**
|
||||
* Given an ast node, returns its string description.
|
||||
* @deprecated: provided to ease adoption and will be removed in v16.
|
||||
*
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
function getDescription(node, options) {
|
||||
if (node.description) {
|
||||
return node.description.value;
|
||||
}
|
||||
|
||||
if (options && options.commentDescriptions) {
|
||||
var rawValue = getLeadingCommentBlock(node);
|
||||
|
||||
if (rawValue !== undefined) {
|
||||
return (0, _blockStringValue.default)('\n' + rawValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getLeadingCommentBlock(node) {
|
||||
var loc = node.loc;
|
||||
|
||||
if (!loc) {
|
||||
return;
|
||||
}
|
||||
|
||||
var comments = [];
|
||||
var token = loc.startToken.prev;
|
||||
|
||||
while (token && token.kind === _lexer.TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) {
|
||||
var value = String(token.value);
|
||||
comments.push(value);
|
||||
token = token.prev;
|
||||
}
|
||||
|
||||
return comments.reverse().join('\n');
|
||||
}
|
||||
/**
|
||||
* A helper function to build a GraphQLSchema directly from a source
|
||||
* document.
|
||||
*/
|
||||
|
||||
|
||||
function buildSchema(source, options) {
|
||||
return buildASTSchema((0, _parser.parse)(source, options), options);
|
||||
}
|
||||
+506
@@ -0,0 +1,506 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import invariant from '../jsutils/invariant';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import type { ObjMap } from '../jsutils/ObjMap';
|
||||
import { valueFromAST } from './valueFromAST';
|
||||
import { assertValidSDL } from '../validation/validate';
|
||||
import blockStringValue from '../language/blockStringValue';
|
||||
import { TokenKind } from '../language/lexer';
|
||||
import { parse } from '../language/parser';
|
||||
import type { ParseOptions } from '../language/parser';
|
||||
import type { Source } from '../language/source';
|
||||
import { getDirectiveValues } from '../execution/values';
|
||||
import { Kind } from '../language/kinds';
|
||||
|
||||
import type {
|
||||
DocumentNode,
|
||||
TypeNode,
|
||||
NamedTypeNode,
|
||||
SchemaDefinitionNode,
|
||||
TypeDefinitionNode,
|
||||
ScalarTypeDefinitionNode,
|
||||
ObjectTypeDefinitionNode,
|
||||
FieldDefinitionNode,
|
||||
InputValueDefinitionNode,
|
||||
InterfaceTypeDefinitionNode,
|
||||
UnionTypeDefinitionNode,
|
||||
EnumTypeDefinitionNode,
|
||||
EnumValueDefinitionNode,
|
||||
InputObjectTypeDefinitionNode,
|
||||
DirectiveDefinitionNode,
|
||||
StringValueNode,
|
||||
Location,
|
||||
} from '../language/ast';
|
||||
import { isTypeDefinitionNode } from '../language/predicates';
|
||||
|
||||
import type { DirectiveLocationEnum } from '../language/directiveLocation';
|
||||
|
||||
import type {
|
||||
GraphQLType,
|
||||
GraphQLNamedType,
|
||||
GraphQLFieldConfig,
|
||||
GraphQLEnumValueConfig,
|
||||
GraphQLInputField,
|
||||
} from '../type/definition';
|
||||
|
||||
import {
|
||||
GraphQLScalarType,
|
||||
GraphQLObjectType,
|
||||
GraphQLInterfaceType,
|
||||
GraphQLUnionType,
|
||||
GraphQLEnumType,
|
||||
GraphQLInputObjectType,
|
||||
GraphQLList,
|
||||
GraphQLNonNull,
|
||||
} from '../type/definition';
|
||||
|
||||
import {
|
||||
GraphQLDirective,
|
||||
GraphQLSkipDirective,
|
||||
GraphQLIncludeDirective,
|
||||
GraphQLDeprecatedDirective,
|
||||
} from '../type/directives';
|
||||
|
||||
import { introspectionTypes } from '../type/introspection';
|
||||
|
||||
import { specifiedScalarTypes } from '../type/scalars';
|
||||
|
||||
import { GraphQLSchema } from '../type/schema';
|
||||
import type { GraphQLSchemaValidationOptions } from '../type/schema';
|
||||
|
||||
export type BuildSchemaOptions = {
|
||||
...GraphQLSchemaValidationOptions,
|
||||
|
||||
/**
|
||||
* Descriptions are defined as preceding string literals, however an older
|
||||
* experimental version of the SDL supported preceding comments as
|
||||
* descriptions. Set to true to enable this deprecated behavior.
|
||||
* This option is provided to ease adoption and will be removed in v16.
|
||||
*
|
||||
* Default: false
|
||||
*/
|
||||
commentDescriptions?: boolean,
|
||||
|
||||
/**
|
||||
* Set to true to assume the SDL is valid.
|
||||
*
|
||||
* Default: false
|
||||
*/
|
||||
assumeValidSDL?: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* This takes the ast of a schema document produced by the parse function in
|
||||
* src/language/parser.js.
|
||||
*
|
||||
* If no schema definition is provided, then it will look for types named Query
|
||||
* and Mutation.
|
||||
*
|
||||
* Given that AST it constructs a GraphQLSchema. The resulting schema
|
||||
* has no resolve methods, so execution will use default resolvers.
|
||||
*
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
export function buildASTSchema(
|
||||
documentAST: DocumentNode,
|
||||
options?: BuildSchemaOptions,
|
||||
): GraphQLSchema {
|
||||
invariant(
|
||||
documentAST && documentAST.kind === Kind.DOCUMENT,
|
||||
'Must provide valid Document AST',
|
||||
);
|
||||
|
||||
if (!options || !(options.assumeValid || options.assumeValidSDL)) {
|
||||
assertValidSDL(documentAST);
|
||||
}
|
||||
|
||||
let schemaDef: ?SchemaDefinitionNode;
|
||||
|
||||
const typeDefs: Array<TypeDefinitionNode> = [];
|
||||
const nodeMap: ObjMap<TypeDefinitionNode> = Object.create(null);
|
||||
const directiveDefs: Array<DirectiveDefinitionNode> = [];
|
||||
for (let i = 0; i < documentAST.definitions.length; i++) {
|
||||
const def = documentAST.definitions[i];
|
||||
if (def.kind === Kind.SCHEMA_DEFINITION) {
|
||||
schemaDef = def;
|
||||
} else if (isTypeDefinitionNode(def)) {
|
||||
const typeName = def.name.value;
|
||||
if (nodeMap[typeName]) {
|
||||
throw new Error(`Type "${typeName}" was defined more than once.`);
|
||||
}
|
||||
typeDefs.push(def);
|
||||
nodeMap[typeName] = def;
|
||||
} else if (def.kind === Kind.DIRECTIVE_DEFINITION) {
|
||||
directiveDefs.push(def);
|
||||
}
|
||||
}
|
||||
|
||||
const operationTypes = schemaDef
|
||||
? getOperationTypes(schemaDef)
|
||||
: {
|
||||
query: nodeMap.Query,
|
||||
mutation: nodeMap.Mutation,
|
||||
subscription: nodeMap.Subscription,
|
||||
};
|
||||
|
||||
const definitionBuilder = new ASTDefinitionBuilder(
|
||||
nodeMap,
|
||||
options,
|
||||
typeRef => {
|
||||
throw new Error(`Type "${typeRef.name.value}" not found in document.`);
|
||||
},
|
||||
);
|
||||
|
||||
const directives = directiveDefs.map(def =>
|
||||
definitionBuilder.buildDirective(def),
|
||||
);
|
||||
|
||||
// If specified directives were not explicitly declared, add them.
|
||||
if (!directives.some(directive => directive.name === 'skip')) {
|
||||
directives.push(GraphQLSkipDirective);
|
||||
}
|
||||
|
||||
if (!directives.some(directive => directive.name === 'include')) {
|
||||
directives.push(GraphQLIncludeDirective);
|
||||
}
|
||||
|
||||
if (!directives.some(directive => directive.name === 'deprecated')) {
|
||||
directives.push(GraphQLDeprecatedDirective);
|
||||
}
|
||||
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values below, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
return new GraphQLSchema({
|
||||
query: operationTypes.query
|
||||
? (definitionBuilder.buildType(operationTypes.query): any)
|
||||
: null,
|
||||
mutation: operationTypes.mutation
|
||||
? (definitionBuilder.buildType(operationTypes.mutation): any)
|
||||
: null,
|
||||
subscription: operationTypes.subscription
|
||||
? (definitionBuilder.buildType(operationTypes.subscription): any)
|
||||
: null,
|
||||
types: typeDefs.map(node => definitionBuilder.buildType(node)),
|
||||
directives,
|
||||
astNode: schemaDef,
|
||||
assumeValid: options && options.assumeValid,
|
||||
allowedLegacyNames: options && options.allowedLegacyNames,
|
||||
});
|
||||
|
||||
function getOperationTypes(schema: SchemaDefinitionNode) {
|
||||
const opTypes = {};
|
||||
for (const operationType of schema.operationTypes) {
|
||||
const typeName = operationType.type.name.value;
|
||||
const operation = operationType.operation;
|
||||
if (opTypes[operation]) {
|
||||
throw new Error(`Must provide only one ${operation} type in schema.`);
|
||||
}
|
||||
if (!nodeMap[typeName]) {
|
||||
throw new Error(
|
||||
`Specified ${operation} type "${typeName}" not found in document.`,
|
||||
);
|
||||
}
|
||||
opTypes[operation] = operationType.type;
|
||||
}
|
||||
return opTypes;
|
||||
}
|
||||
}
|
||||
|
||||
type TypeDefinitionsMap = ObjMap<TypeDefinitionNode>;
|
||||
type TypeResolver = (typeRef: NamedTypeNode) => GraphQLNamedType;
|
||||
|
||||
export class ASTDefinitionBuilder {
|
||||
_typeDefinitionsMap: TypeDefinitionsMap;
|
||||
_options: ?BuildSchemaOptions;
|
||||
_resolveType: TypeResolver;
|
||||
_cache: ObjMap<GraphQLNamedType>;
|
||||
|
||||
constructor(
|
||||
typeDefinitionsMap: TypeDefinitionsMap,
|
||||
options: ?BuildSchemaOptions,
|
||||
resolveType: TypeResolver,
|
||||
) {
|
||||
this._typeDefinitionsMap = typeDefinitionsMap;
|
||||
this._options = options;
|
||||
this._resolveType = resolveType;
|
||||
// Initialize to the GraphQL built in scalars and introspection types.
|
||||
this._cache = keyMap(
|
||||
specifiedScalarTypes.concat(introspectionTypes),
|
||||
type => type.name,
|
||||
);
|
||||
}
|
||||
|
||||
buildType(node: NamedTypeNode | TypeDefinitionNode): GraphQLNamedType {
|
||||
const typeName = node.name.value;
|
||||
if (!this._cache[typeName]) {
|
||||
if (node.kind === Kind.NAMED_TYPE) {
|
||||
const defNode = this._typeDefinitionsMap[typeName];
|
||||
this._cache[typeName] = defNode
|
||||
? this._makeSchemaDef(defNode)
|
||||
: this._resolveType(node);
|
||||
} else {
|
||||
this._cache[typeName] = this._makeSchemaDef(node);
|
||||
}
|
||||
}
|
||||
return this._cache[typeName];
|
||||
}
|
||||
|
||||
_buildWrappedType(typeNode: TypeNode): GraphQLType {
|
||||
if (typeNode.kind === Kind.LIST_TYPE) {
|
||||
return GraphQLList(this._buildWrappedType(typeNode.type));
|
||||
}
|
||||
if (typeNode.kind === Kind.NON_NULL_TYPE) {
|
||||
return GraphQLNonNull(
|
||||
// Note: GraphQLNonNull constructor validates this type
|
||||
(this._buildWrappedType(typeNode.type): any),
|
||||
);
|
||||
}
|
||||
return this.buildType(typeNode);
|
||||
}
|
||||
|
||||
buildDirective(directiveNode: DirectiveDefinitionNode): GraphQLDirective {
|
||||
return new GraphQLDirective({
|
||||
name: directiveNode.name.value,
|
||||
description: getDescription(directiveNode, this._options),
|
||||
locations: directiveNode.locations.map(
|
||||
node => ((node.value: any): DirectiveLocationEnum),
|
||||
),
|
||||
args:
|
||||
directiveNode.arguments &&
|
||||
this._makeInputValues(directiveNode.arguments),
|
||||
astNode: directiveNode,
|
||||
});
|
||||
}
|
||||
|
||||
buildField(field: FieldDefinitionNode): GraphQLFieldConfig<*, *> {
|
||||
return {
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// value, that would throw immediately while type system validation
|
||||
// with validateSchema() will produce more actionable results.
|
||||
type: (this._buildWrappedType(field.type): any),
|
||||
description: getDescription(field, this._options),
|
||||
args: field.arguments && this._makeInputValues(field.arguments),
|
||||
deprecationReason: getDeprecationReason(field),
|
||||
astNode: field,
|
||||
};
|
||||
}
|
||||
|
||||
buildInputField(value: InputValueDefinitionNode): GraphQLInputField {
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// value, that would throw immediately while type system validation
|
||||
// with validateSchema() will produce more actionable results.
|
||||
const type: any = this._buildWrappedType(value.type);
|
||||
return {
|
||||
name: value.name.value,
|
||||
type,
|
||||
description: getDescription(value, this._options),
|
||||
defaultValue: valueFromAST(value.defaultValue, type),
|
||||
astNode: value,
|
||||
};
|
||||
}
|
||||
|
||||
buildEnumValue(value: EnumValueDefinitionNode): GraphQLEnumValueConfig {
|
||||
return {
|
||||
description: getDescription(value, this._options),
|
||||
deprecationReason: getDeprecationReason(value),
|
||||
astNode: value,
|
||||
};
|
||||
}
|
||||
|
||||
_makeSchemaDef(def: TypeDefinitionNode): GraphQLNamedType {
|
||||
switch (def.kind) {
|
||||
case Kind.OBJECT_TYPE_DEFINITION:
|
||||
return this._makeTypeDef(def);
|
||||
case Kind.INTERFACE_TYPE_DEFINITION:
|
||||
return this._makeInterfaceDef(def);
|
||||
case Kind.ENUM_TYPE_DEFINITION:
|
||||
return this._makeEnumDef(def);
|
||||
case Kind.UNION_TYPE_DEFINITION:
|
||||
return this._makeUnionDef(def);
|
||||
case Kind.SCALAR_TYPE_DEFINITION:
|
||||
return this._makeScalarDef(def);
|
||||
case Kind.INPUT_OBJECT_TYPE_DEFINITION:
|
||||
return this._makeInputObjectDef(def);
|
||||
default:
|
||||
throw new Error(`Type kind "${def.kind}" not supported.`);
|
||||
}
|
||||
}
|
||||
|
||||
_makeTypeDef(def: ObjectTypeDefinitionNode) {
|
||||
const interfaces: ?$ReadOnlyArray<NamedTypeNode> = def.interfaces;
|
||||
return new GraphQLObjectType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: () => this._makeFieldDefMap(def),
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
interfaces: interfaces
|
||||
? () => interfaces.map(ref => (this.buildType(ref): any))
|
||||
: [],
|
||||
astNode: def,
|
||||
});
|
||||
}
|
||||
|
||||
_makeFieldDefMap(
|
||||
def: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode,
|
||||
) {
|
||||
return def.fields
|
||||
? keyValMap(
|
||||
def.fields,
|
||||
field => field.name.value,
|
||||
field => this.buildField(field),
|
||||
)
|
||||
: {};
|
||||
}
|
||||
|
||||
_makeInputValues(values: $ReadOnlyArray<InputValueDefinitionNode>) {
|
||||
return keyValMap(
|
||||
values,
|
||||
value => value.name.value,
|
||||
value => this.buildInputField(value),
|
||||
);
|
||||
}
|
||||
|
||||
_makeInterfaceDef(def: InterfaceTypeDefinitionNode) {
|
||||
return new GraphQLInterfaceType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: () => this._makeFieldDefMap(def),
|
||||
astNode: def,
|
||||
});
|
||||
}
|
||||
|
||||
_makeEnumDef(def: EnumTypeDefinitionNode) {
|
||||
return new GraphQLEnumType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
values: this._makeValueDefMap(def),
|
||||
astNode: def,
|
||||
});
|
||||
}
|
||||
|
||||
_makeValueDefMap(def: EnumTypeDefinitionNode) {
|
||||
return def.values
|
||||
? keyValMap(
|
||||
def.values,
|
||||
enumValue => enumValue.name.value,
|
||||
enumValue => this.buildEnumValue(enumValue),
|
||||
)
|
||||
: {};
|
||||
}
|
||||
|
||||
_makeUnionDef(def: UnionTypeDefinitionNode) {
|
||||
const types: ?$ReadOnlyArray<NamedTypeNode> = def.types;
|
||||
return new GraphQLUnionType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// values below, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
types: types ? () => types.map(ref => (this.buildType(ref): any)) : [],
|
||||
astNode: def,
|
||||
});
|
||||
}
|
||||
|
||||
_makeScalarDef(def: ScalarTypeDefinitionNode) {
|
||||
return new GraphQLScalarType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
astNode: def,
|
||||
serialize: value => value,
|
||||
});
|
||||
}
|
||||
|
||||
_makeInputObjectDef(def: InputObjectTypeDefinitionNode) {
|
||||
return new GraphQLInputObjectType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: () => (def.fields ? this._makeInputValues(def.fields) : {}),
|
||||
astNode: def,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a field or enum value node, returns the string value for the
|
||||
* deprecation reason.
|
||||
*/
|
||||
function getDeprecationReason(
|
||||
node: EnumValueDefinitionNode | FieldDefinitionNode,
|
||||
): ?string {
|
||||
const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node);
|
||||
return deprecated && (deprecated.reason: any);
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an ast node, returns its string description.
|
||||
* @deprecated: provided to ease adoption and will be removed in v16.
|
||||
*
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
export function getDescription(
|
||||
node: { +description?: StringValueNode, +loc?: Location },
|
||||
options: ?BuildSchemaOptions,
|
||||
): void | string {
|
||||
if (node.description) {
|
||||
return node.description.value;
|
||||
}
|
||||
if (options && options.commentDescriptions) {
|
||||
const rawValue = getLeadingCommentBlock(node);
|
||||
if (rawValue !== undefined) {
|
||||
return blockStringValue('\n' + rawValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getLeadingCommentBlock(node): void | string {
|
||||
const loc = node.loc;
|
||||
if (!loc) {
|
||||
return;
|
||||
}
|
||||
const comments = [];
|
||||
let token = loc.startToken.prev;
|
||||
while (
|
||||
token &&
|
||||
token.kind === TokenKind.COMMENT &&
|
||||
token.next &&
|
||||
token.prev &&
|
||||
token.line + 1 === token.next.line &&
|
||||
token.line !== token.prev.line
|
||||
) {
|
||||
const value = String(token.value);
|
||||
comments.push(value);
|
||||
token = token.prev;
|
||||
}
|
||||
return comments.reverse().join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper function to build a GraphQLSchema directly from a source
|
||||
* document.
|
||||
*/
|
||||
export function buildSchema(
|
||||
source: string | Source,
|
||||
options?: BuildSchemaOptions & ParseOptions,
|
||||
): GraphQLSchema {
|
||||
return buildASTSchema(parse(source, options), options);
|
||||
}
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import invariant from '../jsutils/invariant';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import { valueFromAST } from './valueFromAST';
|
||||
import { assertValidSDL } from '../validation/validate';
|
||||
import blockStringValue from '../language/blockStringValue';
|
||||
import { TokenKind } from '../language/lexer';
|
||||
import { parse } from '../language/parser';
|
||||
import { getDirectiveValues } from '../execution/values';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { isTypeDefinitionNode } from '../language/predicates';
|
||||
import { GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from '../type/definition';
|
||||
import { GraphQLDirective, GraphQLSkipDirective, GraphQLIncludeDirective, GraphQLDeprecatedDirective } from '../type/directives';
|
||||
import { introspectionTypes } from '../type/introspection';
|
||||
import { specifiedScalarTypes } from '../type/scalars';
|
||||
import { GraphQLSchema } from '../type/schema';
|
||||
|
||||
/**
|
||||
* This takes the ast of a schema document produced by the parse function in
|
||||
* src/language/parser.js.
|
||||
*
|
||||
* If no schema definition is provided, then it will look for types named Query
|
||||
* and Mutation.
|
||||
*
|
||||
* Given that AST it constructs a GraphQLSchema. The resulting schema
|
||||
* has no resolve methods, so execution will use default resolvers.
|
||||
*
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
export function buildASTSchema(documentAST, options) {
|
||||
!(documentAST && documentAST.kind === Kind.DOCUMENT) ? invariant(0, 'Must provide valid Document AST') : void 0;
|
||||
|
||||
if (!options || !(options.assumeValid || options.assumeValidSDL)) {
|
||||
assertValidSDL(documentAST);
|
||||
}
|
||||
|
||||
var schemaDef;
|
||||
var typeDefs = [];
|
||||
var nodeMap = Object.create(null);
|
||||
var directiveDefs = [];
|
||||
|
||||
for (var i = 0; i < documentAST.definitions.length; i++) {
|
||||
var def = documentAST.definitions[i];
|
||||
|
||||
if (def.kind === Kind.SCHEMA_DEFINITION) {
|
||||
schemaDef = def;
|
||||
} else if (isTypeDefinitionNode(def)) {
|
||||
var typeName = def.name.value;
|
||||
|
||||
if (nodeMap[typeName]) {
|
||||
throw new Error("Type \"".concat(typeName, "\" was defined more than once."));
|
||||
}
|
||||
|
||||
typeDefs.push(def);
|
||||
nodeMap[typeName] = def;
|
||||
} else if (def.kind === Kind.DIRECTIVE_DEFINITION) {
|
||||
directiveDefs.push(def);
|
||||
}
|
||||
}
|
||||
|
||||
var operationTypes = schemaDef ? getOperationTypes(schemaDef) : {
|
||||
query: nodeMap.Query,
|
||||
mutation: nodeMap.Mutation,
|
||||
subscription: nodeMap.Subscription
|
||||
};
|
||||
var definitionBuilder = new ASTDefinitionBuilder(nodeMap, options, function (typeRef) {
|
||||
throw new Error("Type \"".concat(typeRef.name.value, "\" not found in document."));
|
||||
});
|
||||
var directives = directiveDefs.map(function (def) {
|
||||
return definitionBuilder.buildDirective(def);
|
||||
}); // If specified directives were not explicitly declared, add them.
|
||||
|
||||
if (!directives.some(function (directive) {
|
||||
return directive.name === 'skip';
|
||||
})) {
|
||||
directives.push(GraphQLSkipDirective);
|
||||
}
|
||||
|
||||
if (!directives.some(function (directive) {
|
||||
return directive.name === 'include';
|
||||
})) {
|
||||
directives.push(GraphQLIncludeDirective);
|
||||
}
|
||||
|
||||
if (!directives.some(function (directive) {
|
||||
return directive.name === 'deprecated';
|
||||
})) {
|
||||
directives.push(GraphQLDeprecatedDirective);
|
||||
} // Note: While this could make early assertions to get the correctly
|
||||
// typed values below, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
|
||||
|
||||
return new GraphQLSchema({
|
||||
query: operationTypes.query ? definitionBuilder.buildType(operationTypes.query) : null,
|
||||
mutation: operationTypes.mutation ? definitionBuilder.buildType(operationTypes.mutation) : null,
|
||||
subscription: operationTypes.subscription ? definitionBuilder.buildType(operationTypes.subscription) : null,
|
||||
types: typeDefs.map(function (node) {
|
||||
return definitionBuilder.buildType(node);
|
||||
}),
|
||||
directives: directives,
|
||||
astNode: schemaDef,
|
||||
assumeValid: options && options.assumeValid,
|
||||
allowedLegacyNames: options && options.allowedLegacyNames
|
||||
});
|
||||
|
||||
function getOperationTypes(schema) {
|
||||
var opTypes = {};
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = schema.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var operationType = _step.value;
|
||||
var _typeName = operationType.type.name.value;
|
||||
var operation = operationType.operation;
|
||||
|
||||
if (opTypes[operation]) {
|
||||
throw new Error("Must provide only one ".concat(operation, " type in schema."));
|
||||
}
|
||||
|
||||
if (!nodeMap[_typeName]) {
|
||||
throw new Error("Specified ".concat(operation, " type \"").concat(_typeName, "\" not found in document."));
|
||||
}
|
||||
|
||||
opTypes[operation] = operationType.type;
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return opTypes;
|
||||
}
|
||||
}
|
||||
export var ASTDefinitionBuilder =
|
||||
/*#__PURE__*/
|
||||
function () {
|
||||
function ASTDefinitionBuilder(typeDefinitionsMap, options, resolveType) {
|
||||
_defineProperty(this, "_typeDefinitionsMap", void 0);
|
||||
|
||||
_defineProperty(this, "_options", void 0);
|
||||
|
||||
_defineProperty(this, "_resolveType", void 0);
|
||||
|
||||
_defineProperty(this, "_cache", void 0);
|
||||
|
||||
this._typeDefinitionsMap = typeDefinitionsMap;
|
||||
this._options = options;
|
||||
this._resolveType = resolveType; // Initialize to the GraphQL built in scalars and introspection types.
|
||||
|
||||
this._cache = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) {
|
||||
return type.name;
|
||||
});
|
||||
}
|
||||
|
||||
var _proto = ASTDefinitionBuilder.prototype;
|
||||
|
||||
_proto.buildType = function buildType(node) {
|
||||
var typeName = node.name.value;
|
||||
|
||||
if (!this._cache[typeName]) {
|
||||
if (node.kind === Kind.NAMED_TYPE) {
|
||||
var defNode = this._typeDefinitionsMap[typeName];
|
||||
this._cache[typeName] = defNode ? this._makeSchemaDef(defNode) : this._resolveType(node);
|
||||
} else {
|
||||
this._cache[typeName] = this._makeSchemaDef(node);
|
||||
}
|
||||
}
|
||||
|
||||
return this._cache[typeName];
|
||||
};
|
||||
|
||||
_proto._buildWrappedType = function _buildWrappedType(typeNode) {
|
||||
if (typeNode.kind === Kind.LIST_TYPE) {
|
||||
return GraphQLList(this._buildWrappedType(typeNode.type));
|
||||
}
|
||||
|
||||
if (typeNode.kind === Kind.NON_NULL_TYPE) {
|
||||
return GraphQLNonNull( // Note: GraphQLNonNull constructor validates this type
|
||||
this._buildWrappedType(typeNode.type));
|
||||
}
|
||||
|
||||
return this.buildType(typeNode);
|
||||
};
|
||||
|
||||
_proto.buildDirective = function buildDirective(directiveNode) {
|
||||
return new GraphQLDirective({
|
||||
name: directiveNode.name.value,
|
||||
description: getDescription(directiveNode, this._options),
|
||||
locations: directiveNode.locations.map(function (node) {
|
||||
return node.value;
|
||||
}),
|
||||
args: directiveNode.arguments && this._makeInputValues(directiveNode.arguments),
|
||||
astNode: directiveNode
|
||||
});
|
||||
};
|
||||
|
||||
_proto.buildField = function buildField(field) {
|
||||
return {
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// value, that would throw immediately while type system validation
|
||||
// with validateSchema() will produce more actionable results.
|
||||
type: this._buildWrappedType(field.type),
|
||||
description: getDescription(field, this._options),
|
||||
args: field.arguments && this._makeInputValues(field.arguments),
|
||||
deprecationReason: getDeprecationReason(field),
|
||||
astNode: field
|
||||
};
|
||||
};
|
||||
|
||||
_proto.buildInputField = function buildInputField(value) {
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// value, that would throw immediately while type system validation
|
||||
var type = this._buildWrappedType(value.type);
|
||||
|
||||
return {
|
||||
name: value.name.value,
|
||||
type: type,
|
||||
description: getDescription(value, this._options),
|
||||
defaultValue: valueFromAST(value.defaultValue, type),
|
||||
astNode: value
|
||||
};
|
||||
};
|
||||
|
||||
_proto.buildEnumValue = function buildEnumValue(value) {
|
||||
return {
|
||||
description: getDescription(value, this._options),
|
||||
deprecationReason: getDeprecationReason(value),
|
||||
astNode: value
|
||||
};
|
||||
};
|
||||
|
||||
_proto._makeSchemaDef = function _makeSchemaDef(def) {
|
||||
switch (def.kind) {
|
||||
case Kind.OBJECT_TYPE_DEFINITION:
|
||||
return this._makeTypeDef(def);
|
||||
|
||||
case Kind.INTERFACE_TYPE_DEFINITION:
|
||||
return this._makeInterfaceDef(def);
|
||||
|
||||
case Kind.ENUM_TYPE_DEFINITION:
|
||||
return this._makeEnumDef(def);
|
||||
|
||||
case Kind.UNION_TYPE_DEFINITION:
|
||||
return this._makeUnionDef(def);
|
||||
|
||||
case Kind.SCALAR_TYPE_DEFINITION:
|
||||
return this._makeScalarDef(def);
|
||||
|
||||
case Kind.INPUT_OBJECT_TYPE_DEFINITION:
|
||||
return this._makeInputObjectDef(def);
|
||||
|
||||
default:
|
||||
throw new Error("Type kind \"".concat(def.kind, "\" not supported."));
|
||||
}
|
||||
};
|
||||
|
||||
_proto._makeTypeDef = function _makeTypeDef(def) {
|
||||
var _this = this;
|
||||
|
||||
var interfaces = def.interfaces;
|
||||
return new GraphQLObjectType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: function fields() {
|
||||
return _this._makeFieldDefMap(def);
|
||||
},
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
interfaces: interfaces ? function () {
|
||||
return interfaces.map(function (ref) {
|
||||
return _this.buildType(ref);
|
||||
});
|
||||
} : [],
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeFieldDefMap = function _makeFieldDefMap(def) {
|
||||
var _this2 = this;
|
||||
|
||||
return def.fields ? keyValMap(def.fields, function (field) {
|
||||
return field.name.value;
|
||||
}, function (field) {
|
||||
return _this2.buildField(field);
|
||||
}) : {};
|
||||
};
|
||||
|
||||
_proto._makeInputValues = function _makeInputValues(values) {
|
||||
var _this3 = this;
|
||||
|
||||
return keyValMap(values, function (value) {
|
||||
return value.name.value;
|
||||
}, function (value) {
|
||||
return _this3.buildInputField(value);
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeInterfaceDef = function _makeInterfaceDef(def) {
|
||||
var _this4 = this;
|
||||
|
||||
return new GraphQLInterfaceType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: function fields() {
|
||||
return _this4._makeFieldDefMap(def);
|
||||
},
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeEnumDef = function _makeEnumDef(def) {
|
||||
return new GraphQLEnumType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
values: this._makeValueDefMap(def),
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeValueDefMap = function _makeValueDefMap(def) {
|
||||
var _this5 = this;
|
||||
|
||||
return def.values ? keyValMap(def.values, function (enumValue) {
|
||||
return enumValue.name.value;
|
||||
}, function (enumValue) {
|
||||
return _this5.buildEnumValue(enumValue);
|
||||
}) : {};
|
||||
};
|
||||
|
||||
_proto._makeUnionDef = function _makeUnionDef(def) {
|
||||
var _this6 = this;
|
||||
|
||||
var types = def.types;
|
||||
return new GraphQLUnionType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
// Note: While this could make assertions to get the correctly typed
|
||||
// values below, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
types: types ? function () {
|
||||
return types.map(function (ref) {
|
||||
return _this6.buildType(ref);
|
||||
});
|
||||
} : [],
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeScalarDef = function _makeScalarDef(def) {
|
||||
return new GraphQLScalarType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
astNode: def,
|
||||
serialize: function serialize(value) {
|
||||
return value;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto._makeInputObjectDef = function _makeInputObjectDef(def) {
|
||||
var _this7 = this;
|
||||
|
||||
return new GraphQLInputObjectType({
|
||||
name: def.name.value,
|
||||
description: getDescription(def, this._options),
|
||||
fields: function fields() {
|
||||
return def.fields ? _this7._makeInputValues(def.fields) : {};
|
||||
},
|
||||
astNode: def
|
||||
});
|
||||
};
|
||||
|
||||
return ASTDefinitionBuilder;
|
||||
}();
|
||||
/**
|
||||
* Given a field or enum value node, returns the string value for the
|
||||
* deprecation reason.
|
||||
*/
|
||||
|
||||
function getDeprecationReason(node) {
|
||||
var deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node);
|
||||
return deprecated && deprecated.reason;
|
||||
}
|
||||
/**
|
||||
* Given an ast node, returns its string description.
|
||||
* @deprecated: provided to ease adoption and will be removed in v16.
|
||||
*
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
export function getDescription(node, options) {
|
||||
if (node.description) {
|
||||
return node.description.value;
|
||||
}
|
||||
|
||||
if (options && options.commentDescriptions) {
|
||||
var rawValue = getLeadingCommentBlock(node);
|
||||
|
||||
if (rawValue !== undefined) {
|
||||
return blockStringValue('\n' + rawValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getLeadingCommentBlock(node) {
|
||||
var loc = node.loc;
|
||||
|
||||
if (!loc) {
|
||||
return;
|
||||
}
|
||||
|
||||
var comments = [];
|
||||
var token = loc.startToken.prev;
|
||||
|
||||
while (token && token.kind === TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) {
|
||||
var value = String(token.value);
|
||||
comments.push(value);
|
||||
token = token.prev;
|
||||
}
|
||||
|
||||
return comments.reverse().join('\n');
|
||||
}
|
||||
/**
|
||||
* A helper function to build a GraphQLSchema directly from a source
|
||||
* document.
|
||||
*/
|
||||
|
||||
|
||||
export function buildSchema(source, options) {
|
||||
return buildASTSchema(parse(source, options), options);
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.buildClientSchema = buildClientSchema;
|
||||
|
||||
var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
|
||||
|
||||
var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
|
||||
|
||||
var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
|
||||
|
||||
var _valueFromAST = require("./valueFromAST");
|
||||
|
||||
var _parser = require("../language/parser");
|
||||
|
||||
var _schema = require("../type/schema");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _directives = require("../type/directives");
|
||||
|
||||
var _introspection = require("../type/introspection");
|
||||
|
||||
var _scalars = require("../type/scalars");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Build a GraphQLSchema for use by client tools.
|
||||
*
|
||||
* Given the result of a client running the introspection query, creates and
|
||||
* returns a GraphQLSchema instance which can be then used with all graphql-js
|
||||
* tools, but cannot be used to execute a query, as introspection does not
|
||||
* represent the "resolver", "parse" or "serialize" functions or any other
|
||||
* server-internal mechanisms.
|
||||
*
|
||||
* This function expects a complete introspection result. Don't forget to check
|
||||
* the "errors" field of a server response before calling this function.
|
||||
*/
|
||||
function buildClientSchema(introspection, options) {
|
||||
// Get the schema from the introspection result.
|
||||
var schemaIntrospection = introspection.__schema; // Converts the list of types into a keyMap based on the type names.
|
||||
|
||||
var typeIntrospectionMap = (0, _keyMap.default)(schemaIntrospection.types, function (type) {
|
||||
return type.name;
|
||||
}); // A cache to use to store the actual GraphQLType definition objects by name.
|
||||
// Initialize to the GraphQL built in scalars. All functions below are inline
|
||||
// so that this type def cache is within the scope of the closure.
|
||||
|
||||
var typeDefCache = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) {
|
||||
return type.name;
|
||||
}); // Given a type reference in introspection, return the GraphQLType instance.
|
||||
// preferring cached instances before building new instances.
|
||||
|
||||
function getType(typeRef) {
|
||||
if (typeRef.kind === _introspection.TypeKind.LIST) {
|
||||
var itemRef = typeRef.ofType;
|
||||
|
||||
if (!itemRef) {
|
||||
throw new Error('Decorated type deeper than introspection query.');
|
||||
}
|
||||
|
||||
return (0, _definition.GraphQLList)(getType(itemRef));
|
||||
}
|
||||
|
||||
if (typeRef.kind === _introspection.TypeKind.NON_NULL) {
|
||||
var nullableRef = typeRef.ofType;
|
||||
|
||||
if (!nullableRef) {
|
||||
throw new Error('Decorated type deeper than introspection query.');
|
||||
}
|
||||
|
||||
var nullableType = getType(nullableRef);
|
||||
return (0, _definition.GraphQLNonNull)((0, _definition.assertNullableType)(nullableType));
|
||||
}
|
||||
|
||||
if (!typeRef.name) {
|
||||
throw new Error('Unknown type reference: ' + JSON.stringify(typeRef));
|
||||
}
|
||||
|
||||
return getNamedType(typeRef.name);
|
||||
}
|
||||
|
||||
function getNamedType(typeName) {
|
||||
if (typeDefCache[typeName]) {
|
||||
return typeDefCache[typeName];
|
||||
}
|
||||
|
||||
var typeIntrospection = typeIntrospectionMap[typeName];
|
||||
|
||||
if (!typeIntrospection) {
|
||||
throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure ") + 'that a full introspection query is used in order to build a ' + 'client schema.');
|
||||
}
|
||||
|
||||
var typeDef = buildType(typeIntrospection);
|
||||
typeDefCache[typeName] = typeDef;
|
||||
return typeDef;
|
||||
}
|
||||
|
||||
function getInputType(typeRef) {
|
||||
var type = getType(typeRef);
|
||||
!(0, _definition.isInputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide input type for arguments.') : void 0;
|
||||
return type;
|
||||
}
|
||||
|
||||
function getOutputType(typeRef) {
|
||||
var type = getType(typeRef);
|
||||
!(0, _definition.isOutputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide output type for fields.') : void 0;
|
||||
return type;
|
||||
}
|
||||
|
||||
function getObjectType(typeRef) {
|
||||
var type = getType(typeRef);
|
||||
return (0, _definition.assertObjectType)(type);
|
||||
}
|
||||
|
||||
function getInterfaceType(typeRef) {
|
||||
var type = getType(typeRef);
|
||||
return (0, _definition.assertInterfaceType)(type);
|
||||
} // Given a type's introspection result, construct the correct
|
||||
// GraphQLType instance.
|
||||
|
||||
|
||||
function buildType(type) {
|
||||
if (type && type.name && type.kind) {
|
||||
switch (type.kind) {
|
||||
case _introspection.TypeKind.SCALAR:
|
||||
return buildScalarDef(type);
|
||||
|
||||
case _introspection.TypeKind.OBJECT:
|
||||
return buildObjectDef(type);
|
||||
|
||||
case _introspection.TypeKind.INTERFACE:
|
||||
return buildInterfaceDef(type);
|
||||
|
||||
case _introspection.TypeKind.UNION:
|
||||
return buildUnionDef(type);
|
||||
|
||||
case _introspection.TypeKind.ENUM:
|
||||
return buildEnumDef(type);
|
||||
|
||||
case _introspection.TypeKind.INPUT_OBJECT:
|
||||
return buildInputObjectDef(type);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Invalid or incomplete introspection result. Ensure that a full ' + 'introspection query is used in order to build a client schema:' + JSON.stringify(type));
|
||||
}
|
||||
|
||||
function buildScalarDef(scalarIntrospection) {
|
||||
return new _definition.GraphQLScalarType({
|
||||
name: scalarIntrospection.name,
|
||||
description: scalarIntrospection.description,
|
||||
serialize: function serialize(value) {
|
||||
return value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildObjectDef(objectIntrospection) {
|
||||
if (!objectIntrospection.interfaces) {
|
||||
throw new Error('Introspection result missing interfaces: ' + JSON.stringify(objectIntrospection));
|
||||
}
|
||||
|
||||
return new _definition.GraphQLObjectType({
|
||||
name: objectIntrospection.name,
|
||||
description: objectIntrospection.description,
|
||||
interfaces: objectIntrospection.interfaces.map(getInterfaceType),
|
||||
fields: function fields() {
|
||||
return buildFieldDefMap(objectIntrospection);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildInterfaceDef(interfaceIntrospection) {
|
||||
return new _definition.GraphQLInterfaceType({
|
||||
name: interfaceIntrospection.name,
|
||||
description: interfaceIntrospection.description,
|
||||
fields: function fields() {
|
||||
return buildFieldDefMap(interfaceIntrospection);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildUnionDef(unionIntrospection) {
|
||||
if (!unionIntrospection.possibleTypes) {
|
||||
throw new Error('Introspection result missing possibleTypes: ' + JSON.stringify(unionIntrospection));
|
||||
}
|
||||
|
||||
return new _definition.GraphQLUnionType({
|
||||
name: unionIntrospection.name,
|
||||
description: unionIntrospection.description,
|
||||
types: unionIntrospection.possibleTypes.map(getObjectType)
|
||||
});
|
||||
}
|
||||
|
||||
function buildEnumDef(enumIntrospection) {
|
||||
if (!enumIntrospection.enumValues) {
|
||||
throw new Error('Introspection result missing enumValues: ' + JSON.stringify(enumIntrospection));
|
||||
}
|
||||
|
||||
return new _definition.GraphQLEnumType({
|
||||
name: enumIntrospection.name,
|
||||
description: enumIntrospection.description,
|
||||
values: (0, _keyValMap.default)(enumIntrospection.enumValues, function (valueIntrospection) {
|
||||
return valueIntrospection.name;
|
||||
}, function (valueIntrospection) {
|
||||
return {
|
||||
description: valueIntrospection.description,
|
||||
deprecationReason: valueIntrospection.deprecationReason
|
||||
};
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
function buildInputObjectDef(inputObjectIntrospection) {
|
||||
if (!inputObjectIntrospection.inputFields) {
|
||||
throw new Error('Introspection result missing inputFields: ' + JSON.stringify(inputObjectIntrospection));
|
||||
}
|
||||
|
||||
return new _definition.GraphQLInputObjectType({
|
||||
name: inputObjectIntrospection.name,
|
||||
description: inputObjectIntrospection.description,
|
||||
fields: function fields() {
|
||||
return buildInputValueDefMap(inputObjectIntrospection.inputFields);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildFieldDefMap(typeIntrospection) {
|
||||
if (!typeIntrospection.fields) {
|
||||
throw new Error('Introspection result missing fields: ' + JSON.stringify(typeIntrospection));
|
||||
}
|
||||
|
||||
return (0, _keyValMap.default)(typeIntrospection.fields, function (fieldIntrospection) {
|
||||
return fieldIntrospection.name;
|
||||
}, function (fieldIntrospection) {
|
||||
if (!fieldIntrospection.args) {
|
||||
throw new Error('Introspection result missing field args: ' + JSON.stringify(fieldIntrospection));
|
||||
}
|
||||
|
||||
return {
|
||||
description: fieldIntrospection.description,
|
||||
deprecationReason: fieldIntrospection.deprecationReason,
|
||||
type: getOutputType(fieldIntrospection.type),
|
||||
args: buildInputValueDefMap(fieldIntrospection.args)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildInputValueDefMap(inputValueIntrospections) {
|
||||
return (0, _keyValMap.default)(inputValueIntrospections, function (inputValue) {
|
||||
return inputValue.name;
|
||||
}, buildInputValue);
|
||||
}
|
||||
|
||||
function buildInputValue(inputValueIntrospection) {
|
||||
var type = getInputType(inputValueIntrospection.type);
|
||||
var defaultValue = inputValueIntrospection.defaultValue ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined;
|
||||
return {
|
||||
description: inputValueIntrospection.description,
|
||||
type: type,
|
||||
defaultValue: defaultValue
|
||||
};
|
||||
}
|
||||
|
||||
function buildDirective(directiveIntrospection) {
|
||||
if (!directiveIntrospection.args) {
|
||||
throw new Error('Introspection result missing directive args: ' + JSON.stringify(directiveIntrospection));
|
||||
}
|
||||
|
||||
return new _directives.GraphQLDirective({
|
||||
name: directiveIntrospection.name,
|
||||
description: directiveIntrospection.description,
|
||||
locations: directiveIntrospection.locations.slice(),
|
||||
args: buildInputValueDefMap(directiveIntrospection.args)
|
||||
});
|
||||
} // Iterate through all types, getting the type definition for each, ensuring
|
||||
// that any type not directly referenced by a field will get created.
|
||||
|
||||
|
||||
var types = schemaIntrospection.types.map(function (typeIntrospection) {
|
||||
return getNamedType(typeIntrospection.name);
|
||||
}); // Get the root Query, Mutation, and Subscription types.
|
||||
|
||||
var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null;
|
||||
var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null;
|
||||
var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if
|
||||
// directives were not queried for.
|
||||
|
||||
var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types.
|
||||
|
||||
return new _schema.GraphQLSchema({
|
||||
query: queryType,
|
||||
mutation: mutationType,
|
||||
subscription: subscriptionType,
|
||||
types: types,
|
||||
directives: directives,
|
||||
assumeValid: options && options.assumeValid,
|
||||
allowedLegacyNames: options && options.allowedLegacyNames
|
||||
});
|
||||
}
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import invariant from '../jsutils/invariant';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import { valueFromAST } from './valueFromAST';
|
||||
import { parseValue } from '../language/parser';
|
||||
import { GraphQLSchema } from '../type/schema';
|
||||
|
||||
import {
|
||||
isInputType,
|
||||
isOutputType,
|
||||
GraphQLScalarType,
|
||||
GraphQLObjectType,
|
||||
GraphQLInterfaceType,
|
||||
GraphQLUnionType,
|
||||
GraphQLEnumType,
|
||||
GraphQLInputObjectType,
|
||||
GraphQLList,
|
||||
GraphQLNonNull,
|
||||
assertNullableType,
|
||||
assertObjectType,
|
||||
assertInterfaceType,
|
||||
} from '../type/definition';
|
||||
|
||||
import type {
|
||||
GraphQLType,
|
||||
GraphQLInputType,
|
||||
GraphQLOutputType,
|
||||
GraphQLNamedType,
|
||||
} from '../type/definition';
|
||||
|
||||
import { GraphQLDirective } from '../type/directives';
|
||||
|
||||
import { introspectionTypes, TypeKind } from '../type/introspection';
|
||||
|
||||
import { specifiedScalarTypes } from '../type/scalars';
|
||||
|
||||
import type {
|
||||
IntrospectionQuery,
|
||||
IntrospectionType,
|
||||
IntrospectionScalarType,
|
||||
IntrospectionObjectType,
|
||||
IntrospectionInterfaceType,
|
||||
IntrospectionUnionType,
|
||||
IntrospectionEnumType,
|
||||
IntrospectionInputObjectType,
|
||||
IntrospectionTypeRef,
|
||||
IntrospectionInputTypeRef,
|
||||
IntrospectionOutputTypeRef,
|
||||
IntrospectionNamedTypeRef,
|
||||
} from './introspectionQuery';
|
||||
|
||||
import type { GraphQLSchemaValidationOptions } from '../type/schema';
|
||||
|
||||
type Options = {|
|
||||
...GraphQLSchemaValidationOptions,
|
||||
|};
|
||||
|
||||
/**
|
||||
* Build a GraphQLSchema for use by client tools.
|
||||
*
|
||||
* Given the result of a client running the introspection query, creates and
|
||||
* returns a GraphQLSchema instance which can be then used with all graphql-js
|
||||
* tools, but cannot be used to execute a query, as introspection does not
|
||||
* represent the "resolver", "parse" or "serialize" functions or any other
|
||||
* server-internal mechanisms.
|
||||
*
|
||||
* This function expects a complete introspection result. Don't forget to check
|
||||
* the "errors" field of a server response before calling this function.
|
||||
*/
|
||||
export function buildClientSchema(
|
||||
introspection: IntrospectionQuery,
|
||||
options?: Options,
|
||||
): GraphQLSchema {
|
||||
// Get the schema from the introspection result.
|
||||
const schemaIntrospection = introspection.__schema;
|
||||
|
||||
// Converts the list of types into a keyMap based on the type names.
|
||||
const typeIntrospectionMap = keyMap(
|
||||
schemaIntrospection.types,
|
||||
type => type.name,
|
||||
);
|
||||
|
||||
// A cache to use to store the actual GraphQLType definition objects by name.
|
||||
// Initialize to the GraphQL built in scalars. All functions below are inline
|
||||
// so that this type def cache is within the scope of the closure.
|
||||
const typeDefCache = keyMap(
|
||||
specifiedScalarTypes.concat(introspectionTypes),
|
||||
type => type.name,
|
||||
);
|
||||
|
||||
// Given a type reference in introspection, return the GraphQLType instance.
|
||||
// preferring cached instances before building new instances.
|
||||
function getType(typeRef: IntrospectionTypeRef): GraphQLType {
|
||||
if (typeRef.kind === TypeKind.LIST) {
|
||||
const itemRef = typeRef.ofType;
|
||||
if (!itemRef) {
|
||||
throw new Error('Decorated type deeper than introspection query.');
|
||||
}
|
||||
return GraphQLList(getType(itemRef));
|
||||
}
|
||||
if (typeRef.kind === TypeKind.NON_NULL) {
|
||||
const nullableRef = typeRef.ofType;
|
||||
if (!nullableRef) {
|
||||
throw new Error('Decorated type deeper than introspection query.');
|
||||
}
|
||||
const nullableType = getType(nullableRef);
|
||||
return GraphQLNonNull(assertNullableType(nullableType));
|
||||
}
|
||||
if (!typeRef.name) {
|
||||
throw new Error('Unknown type reference: ' + JSON.stringify(typeRef));
|
||||
}
|
||||
return getNamedType(typeRef.name);
|
||||
}
|
||||
|
||||
function getNamedType(typeName: string): GraphQLNamedType {
|
||||
if (typeDefCache[typeName]) {
|
||||
return typeDefCache[typeName];
|
||||
}
|
||||
const typeIntrospection = typeIntrospectionMap[typeName];
|
||||
if (!typeIntrospection) {
|
||||
throw new Error(
|
||||
`Invalid or incomplete schema, unknown type: ${typeName}. Ensure ` +
|
||||
'that a full introspection query is used in order to build a ' +
|
||||
'client schema.',
|
||||
);
|
||||
}
|
||||
const typeDef = buildType(typeIntrospection);
|
||||
typeDefCache[typeName] = typeDef;
|
||||
return typeDef;
|
||||
}
|
||||
|
||||
function getInputType(typeRef: IntrospectionInputTypeRef): GraphQLInputType {
|
||||
const type = getType(typeRef);
|
||||
invariant(
|
||||
isInputType(type),
|
||||
'Introspection must provide input type for arguments.',
|
||||
);
|
||||
return type;
|
||||
}
|
||||
|
||||
function getOutputType(
|
||||
typeRef: IntrospectionOutputTypeRef,
|
||||
): GraphQLOutputType {
|
||||
const type = getType(typeRef);
|
||||
invariant(
|
||||
isOutputType(type),
|
||||
'Introspection must provide output type for fields.',
|
||||
);
|
||||
return type;
|
||||
}
|
||||
|
||||
function getObjectType(
|
||||
typeRef: IntrospectionNamedTypeRef<IntrospectionObjectType>,
|
||||
): GraphQLObjectType {
|
||||
const type = getType(typeRef);
|
||||
return assertObjectType(type);
|
||||
}
|
||||
|
||||
function getInterfaceType(
|
||||
typeRef: IntrospectionTypeRef,
|
||||
): GraphQLInterfaceType {
|
||||
const type = getType(typeRef);
|
||||
return assertInterfaceType(type);
|
||||
}
|
||||
|
||||
// Given a type's introspection result, construct the correct
|
||||
// GraphQLType instance.
|
||||
function buildType(type: IntrospectionType): GraphQLNamedType {
|
||||
if (type && type.name && type.kind) {
|
||||
switch (type.kind) {
|
||||
case TypeKind.SCALAR:
|
||||
return buildScalarDef(type);
|
||||
case TypeKind.OBJECT:
|
||||
return buildObjectDef(type);
|
||||
case TypeKind.INTERFACE:
|
||||
return buildInterfaceDef(type);
|
||||
case TypeKind.UNION:
|
||||
return buildUnionDef(type);
|
||||
case TypeKind.ENUM:
|
||||
return buildEnumDef(type);
|
||||
case TypeKind.INPUT_OBJECT:
|
||||
return buildInputObjectDef(type);
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
'Invalid or incomplete introspection result. Ensure that a full ' +
|
||||
'introspection query is used in order to build a client schema:' +
|
||||
JSON.stringify(type),
|
||||
);
|
||||
}
|
||||
|
||||
function buildScalarDef(
|
||||
scalarIntrospection: IntrospectionScalarType,
|
||||
): GraphQLScalarType {
|
||||
return new GraphQLScalarType({
|
||||
name: scalarIntrospection.name,
|
||||
description: scalarIntrospection.description,
|
||||
serialize: value => value,
|
||||
});
|
||||
}
|
||||
|
||||
function buildObjectDef(
|
||||
objectIntrospection: IntrospectionObjectType,
|
||||
): GraphQLObjectType {
|
||||
if (!objectIntrospection.interfaces) {
|
||||
throw new Error(
|
||||
'Introspection result missing interfaces: ' +
|
||||
JSON.stringify(objectIntrospection),
|
||||
);
|
||||
}
|
||||
return new GraphQLObjectType({
|
||||
name: objectIntrospection.name,
|
||||
description: objectIntrospection.description,
|
||||
interfaces: objectIntrospection.interfaces.map(getInterfaceType),
|
||||
fields: () => buildFieldDefMap(objectIntrospection),
|
||||
});
|
||||
}
|
||||
|
||||
function buildInterfaceDef(
|
||||
interfaceIntrospection: IntrospectionInterfaceType,
|
||||
): GraphQLInterfaceType {
|
||||
return new GraphQLInterfaceType({
|
||||
name: interfaceIntrospection.name,
|
||||
description: interfaceIntrospection.description,
|
||||
fields: () => buildFieldDefMap(interfaceIntrospection),
|
||||
});
|
||||
}
|
||||
|
||||
function buildUnionDef(
|
||||
unionIntrospection: IntrospectionUnionType,
|
||||
): GraphQLUnionType {
|
||||
if (!unionIntrospection.possibleTypes) {
|
||||
throw new Error(
|
||||
'Introspection result missing possibleTypes: ' +
|
||||
JSON.stringify(unionIntrospection),
|
||||
);
|
||||
}
|
||||
return new GraphQLUnionType({
|
||||
name: unionIntrospection.name,
|
||||
description: unionIntrospection.description,
|
||||
types: unionIntrospection.possibleTypes.map(getObjectType),
|
||||
});
|
||||
}
|
||||
|
||||
function buildEnumDef(
|
||||
enumIntrospection: IntrospectionEnumType,
|
||||
): GraphQLEnumType {
|
||||
if (!enumIntrospection.enumValues) {
|
||||
throw new Error(
|
||||
'Introspection result missing enumValues: ' +
|
||||
JSON.stringify(enumIntrospection),
|
||||
);
|
||||
}
|
||||
return new GraphQLEnumType({
|
||||
name: enumIntrospection.name,
|
||||
description: enumIntrospection.description,
|
||||
values: keyValMap(
|
||||
enumIntrospection.enumValues,
|
||||
valueIntrospection => valueIntrospection.name,
|
||||
valueIntrospection => ({
|
||||
description: valueIntrospection.description,
|
||||
deprecationReason: valueIntrospection.deprecationReason,
|
||||
}),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
function buildInputObjectDef(
|
||||
inputObjectIntrospection: IntrospectionInputObjectType,
|
||||
): GraphQLInputObjectType {
|
||||
if (!inputObjectIntrospection.inputFields) {
|
||||
throw new Error(
|
||||
'Introspection result missing inputFields: ' +
|
||||
JSON.stringify(inputObjectIntrospection),
|
||||
);
|
||||
}
|
||||
return new GraphQLInputObjectType({
|
||||
name: inputObjectIntrospection.name,
|
||||
description: inputObjectIntrospection.description,
|
||||
fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields),
|
||||
});
|
||||
}
|
||||
|
||||
function buildFieldDefMap(typeIntrospection) {
|
||||
if (!typeIntrospection.fields) {
|
||||
throw new Error(
|
||||
'Introspection result missing fields: ' +
|
||||
JSON.stringify(typeIntrospection),
|
||||
);
|
||||
}
|
||||
return keyValMap(
|
||||
typeIntrospection.fields,
|
||||
fieldIntrospection => fieldIntrospection.name,
|
||||
fieldIntrospection => {
|
||||
if (!fieldIntrospection.args) {
|
||||
throw new Error(
|
||||
'Introspection result missing field args: ' +
|
||||
JSON.stringify(fieldIntrospection),
|
||||
);
|
||||
}
|
||||
return {
|
||||
description: fieldIntrospection.description,
|
||||
deprecationReason: fieldIntrospection.deprecationReason,
|
||||
type: getOutputType(fieldIntrospection.type),
|
||||
args: buildInputValueDefMap(fieldIntrospection.args),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function buildInputValueDefMap(inputValueIntrospections) {
|
||||
return keyValMap(
|
||||
inputValueIntrospections,
|
||||
inputValue => inputValue.name,
|
||||
buildInputValue,
|
||||
);
|
||||
}
|
||||
|
||||
function buildInputValue(inputValueIntrospection) {
|
||||
const type = getInputType(inputValueIntrospection.type);
|
||||
const defaultValue = inputValueIntrospection.defaultValue
|
||||
? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type)
|
||||
: undefined;
|
||||
return {
|
||||
description: inputValueIntrospection.description,
|
||||
type,
|
||||
defaultValue,
|
||||
};
|
||||
}
|
||||
|
||||
function buildDirective(directiveIntrospection) {
|
||||
if (!directiveIntrospection.args) {
|
||||
throw new Error(
|
||||
'Introspection result missing directive args: ' +
|
||||
JSON.stringify(directiveIntrospection),
|
||||
);
|
||||
}
|
||||
return new GraphQLDirective({
|
||||
name: directiveIntrospection.name,
|
||||
description: directiveIntrospection.description,
|
||||
locations: directiveIntrospection.locations.slice(),
|
||||
args: buildInputValueDefMap(directiveIntrospection.args),
|
||||
});
|
||||
}
|
||||
|
||||
// Iterate through all types, getting the type definition for each, ensuring
|
||||
// that any type not directly referenced by a field will get created.
|
||||
const types = schemaIntrospection.types.map(typeIntrospection =>
|
||||
getNamedType(typeIntrospection.name),
|
||||
);
|
||||
|
||||
// Get the root Query, Mutation, and Subscription types.
|
||||
const queryType = schemaIntrospection.queryType
|
||||
? getObjectType(schemaIntrospection.queryType)
|
||||
: null;
|
||||
|
||||
const mutationType = schemaIntrospection.mutationType
|
||||
? getObjectType(schemaIntrospection.mutationType)
|
||||
: null;
|
||||
|
||||
const subscriptionType = schemaIntrospection.subscriptionType
|
||||
? getObjectType(schemaIntrospection.subscriptionType)
|
||||
: null;
|
||||
|
||||
// Get the directives supported by Introspection, assuming empty-set if
|
||||
// directives were not queried for.
|
||||
const directives = schemaIntrospection.directives
|
||||
? schemaIntrospection.directives.map(buildDirective)
|
||||
: [];
|
||||
|
||||
// Then produce and return a Schema with these types.
|
||||
return new GraphQLSchema({
|
||||
query: queryType,
|
||||
mutation: mutationType,
|
||||
subscription: subscriptionType,
|
||||
types,
|
||||
directives,
|
||||
assumeValid: options && options.assumeValid,
|
||||
allowedLegacyNames: options && options.allowedLegacyNames,
|
||||
});
|
||||
}
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import invariant from '../jsutils/invariant';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import { valueFromAST } from './valueFromAST';
|
||||
import { parseValue } from '../language/parser';
|
||||
import { GraphQLSchema } from '../type/schema';
|
||||
import { isInputType, isOutputType, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, assertNullableType, assertObjectType, assertInterfaceType } from '../type/definition';
|
||||
import { GraphQLDirective } from '../type/directives';
|
||||
import { introspectionTypes, TypeKind } from '../type/introspection';
|
||||
import { specifiedScalarTypes } from '../type/scalars';
|
||||
|
||||
/**
|
||||
* Build a GraphQLSchema for use by client tools.
|
||||
*
|
||||
* Given the result of a client running the introspection query, creates and
|
||||
* returns a GraphQLSchema instance which can be then used with all graphql-js
|
||||
* tools, but cannot be used to execute a query, as introspection does not
|
||||
* represent the "resolver", "parse" or "serialize" functions or any other
|
||||
* server-internal mechanisms.
|
||||
*
|
||||
* This function expects a complete introspection result. Don't forget to check
|
||||
* the "errors" field of a server response before calling this function.
|
||||
*/
|
||||
export function buildClientSchema(introspection, options) {
|
||||
// Get the schema from the introspection result.
|
||||
var schemaIntrospection = introspection.__schema; // Converts the list of types into a keyMap based on the type names.
|
||||
|
||||
var typeIntrospectionMap = keyMap(schemaIntrospection.types, function (type) {
|
||||
return type.name;
|
||||
}); // A cache to use to store the actual GraphQLType definition objects by name.
|
||||
// Initialize to the GraphQL built in scalars. All functions below are inline
|
||||
// so that this type def cache is within the scope of the closure.
|
||||
|
||||
var typeDefCache = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) {
|
||||
return type.name;
|
||||
}); // Given a type reference in introspection, return the GraphQLType instance.
|
||||
// preferring cached instances before building new instances.
|
||||
|
||||
function getType(typeRef) {
|
||||
if (typeRef.kind === TypeKind.LIST) {
|
||||
var itemRef = typeRef.ofType;
|
||||
|
||||
if (!itemRef) {
|
||||
throw new Error('Decorated type deeper than introspection query.');
|
||||
}
|
||||
|
||||
return GraphQLList(getType(itemRef));
|
||||
}
|
||||
|
||||
if (typeRef.kind === TypeKind.NON_NULL) {
|
||||
var nullableRef = typeRef.ofType;
|
||||
|
||||
if (!nullableRef) {
|
||||
throw new Error('Decorated type deeper than introspection query.');
|
||||
}
|
||||
|
||||
var nullableType = getType(nullableRef);
|
||||
return GraphQLNonNull(assertNullableType(nullableType));
|
||||
}
|
||||
|
||||
if (!typeRef.name) {
|
||||
throw new Error('Unknown type reference: ' + JSON.stringify(typeRef));
|
||||
}
|
||||
|
||||
return getNamedType(typeRef.name);
|
||||
}
|
||||
|
||||
function getNamedType(typeName) {
|
||||
if (typeDefCache[typeName]) {
|
||||
return typeDefCache[typeName];
|
||||
}
|
||||
|
||||
var typeIntrospection = typeIntrospectionMap[typeName];
|
||||
|
||||
if (!typeIntrospection) {
|
||||
throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure ") + 'that a full introspection query is used in order to build a ' + 'client schema.');
|
||||
}
|
||||
|
||||
var typeDef = buildType(typeIntrospection);
|
||||
typeDefCache[typeName] = typeDef;
|
||||
return typeDef;
|
||||
}
|
||||
|
||||
function getInputType(typeRef) {
|
||||
var type = getType(typeRef);
|
||||
!isInputType(type) ? invariant(0, 'Introspection must provide input type for arguments.') : void 0;
|
||||
return type;
|
||||
}
|
||||
|
||||
function getOutputType(typeRef) {
|
||||
var type = getType(typeRef);
|
||||
!isOutputType(type) ? invariant(0, 'Introspection must provide output type for fields.') : void 0;
|
||||
return type;
|
||||
}
|
||||
|
||||
function getObjectType(typeRef) {
|
||||
var type = getType(typeRef);
|
||||
return assertObjectType(type);
|
||||
}
|
||||
|
||||
function getInterfaceType(typeRef) {
|
||||
var type = getType(typeRef);
|
||||
return assertInterfaceType(type);
|
||||
} // Given a type's introspection result, construct the correct
|
||||
// GraphQLType instance.
|
||||
|
||||
|
||||
function buildType(type) {
|
||||
if (type && type.name && type.kind) {
|
||||
switch (type.kind) {
|
||||
case TypeKind.SCALAR:
|
||||
return buildScalarDef(type);
|
||||
|
||||
case TypeKind.OBJECT:
|
||||
return buildObjectDef(type);
|
||||
|
||||
case TypeKind.INTERFACE:
|
||||
return buildInterfaceDef(type);
|
||||
|
||||
case TypeKind.UNION:
|
||||
return buildUnionDef(type);
|
||||
|
||||
case TypeKind.ENUM:
|
||||
return buildEnumDef(type);
|
||||
|
||||
case TypeKind.INPUT_OBJECT:
|
||||
return buildInputObjectDef(type);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Invalid or incomplete introspection result. Ensure that a full ' + 'introspection query is used in order to build a client schema:' + JSON.stringify(type));
|
||||
}
|
||||
|
||||
function buildScalarDef(scalarIntrospection) {
|
||||
return new GraphQLScalarType({
|
||||
name: scalarIntrospection.name,
|
||||
description: scalarIntrospection.description,
|
||||
serialize: function serialize(value) {
|
||||
return value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildObjectDef(objectIntrospection) {
|
||||
if (!objectIntrospection.interfaces) {
|
||||
throw new Error('Introspection result missing interfaces: ' + JSON.stringify(objectIntrospection));
|
||||
}
|
||||
|
||||
return new GraphQLObjectType({
|
||||
name: objectIntrospection.name,
|
||||
description: objectIntrospection.description,
|
||||
interfaces: objectIntrospection.interfaces.map(getInterfaceType),
|
||||
fields: function fields() {
|
||||
return buildFieldDefMap(objectIntrospection);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildInterfaceDef(interfaceIntrospection) {
|
||||
return new GraphQLInterfaceType({
|
||||
name: interfaceIntrospection.name,
|
||||
description: interfaceIntrospection.description,
|
||||
fields: function fields() {
|
||||
return buildFieldDefMap(interfaceIntrospection);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildUnionDef(unionIntrospection) {
|
||||
if (!unionIntrospection.possibleTypes) {
|
||||
throw new Error('Introspection result missing possibleTypes: ' + JSON.stringify(unionIntrospection));
|
||||
}
|
||||
|
||||
return new GraphQLUnionType({
|
||||
name: unionIntrospection.name,
|
||||
description: unionIntrospection.description,
|
||||
types: unionIntrospection.possibleTypes.map(getObjectType)
|
||||
});
|
||||
}
|
||||
|
||||
function buildEnumDef(enumIntrospection) {
|
||||
if (!enumIntrospection.enumValues) {
|
||||
throw new Error('Introspection result missing enumValues: ' + JSON.stringify(enumIntrospection));
|
||||
}
|
||||
|
||||
return new GraphQLEnumType({
|
||||
name: enumIntrospection.name,
|
||||
description: enumIntrospection.description,
|
||||
values: keyValMap(enumIntrospection.enumValues, function (valueIntrospection) {
|
||||
return valueIntrospection.name;
|
||||
}, function (valueIntrospection) {
|
||||
return {
|
||||
description: valueIntrospection.description,
|
||||
deprecationReason: valueIntrospection.deprecationReason
|
||||
};
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
function buildInputObjectDef(inputObjectIntrospection) {
|
||||
if (!inputObjectIntrospection.inputFields) {
|
||||
throw new Error('Introspection result missing inputFields: ' + JSON.stringify(inputObjectIntrospection));
|
||||
}
|
||||
|
||||
return new GraphQLInputObjectType({
|
||||
name: inputObjectIntrospection.name,
|
||||
description: inputObjectIntrospection.description,
|
||||
fields: function fields() {
|
||||
return buildInputValueDefMap(inputObjectIntrospection.inputFields);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildFieldDefMap(typeIntrospection) {
|
||||
if (!typeIntrospection.fields) {
|
||||
throw new Error('Introspection result missing fields: ' + JSON.stringify(typeIntrospection));
|
||||
}
|
||||
|
||||
return keyValMap(typeIntrospection.fields, function (fieldIntrospection) {
|
||||
return fieldIntrospection.name;
|
||||
}, function (fieldIntrospection) {
|
||||
if (!fieldIntrospection.args) {
|
||||
throw new Error('Introspection result missing field args: ' + JSON.stringify(fieldIntrospection));
|
||||
}
|
||||
|
||||
return {
|
||||
description: fieldIntrospection.description,
|
||||
deprecationReason: fieldIntrospection.deprecationReason,
|
||||
type: getOutputType(fieldIntrospection.type),
|
||||
args: buildInputValueDefMap(fieldIntrospection.args)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildInputValueDefMap(inputValueIntrospections) {
|
||||
return keyValMap(inputValueIntrospections, function (inputValue) {
|
||||
return inputValue.name;
|
||||
}, buildInputValue);
|
||||
}
|
||||
|
||||
function buildInputValue(inputValueIntrospection) {
|
||||
var type = getInputType(inputValueIntrospection.type);
|
||||
var defaultValue = inputValueIntrospection.defaultValue ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) : undefined;
|
||||
return {
|
||||
description: inputValueIntrospection.description,
|
||||
type: type,
|
||||
defaultValue: defaultValue
|
||||
};
|
||||
}
|
||||
|
||||
function buildDirective(directiveIntrospection) {
|
||||
if (!directiveIntrospection.args) {
|
||||
throw new Error('Introspection result missing directive args: ' + JSON.stringify(directiveIntrospection));
|
||||
}
|
||||
|
||||
return new GraphQLDirective({
|
||||
name: directiveIntrospection.name,
|
||||
description: directiveIntrospection.description,
|
||||
locations: directiveIntrospection.locations.slice(),
|
||||
args: buildInputValueDefMap(directiveIntrospection.args)
|
||||
});
|
||||
} // Iterate through all types, getting the type definition for each, ensuring
|
||||
// that any type not directly referenced by a field will get created.
|
||||
|
||||
|
||||
var types = schemaIntrospection.types.map(function (typeIntrospection) {
|
||||
return getNamedType(typeIntrospection.name);
|
||||
}); // Get the root Query, Mutation, and Subscription types.
|
||||
|
||||
var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null;
|
||||
var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null;
|
||||
var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if
|
||||
// directives were not queried for.
|
||||
|
||||
var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types.
|
||||
|
||||
return new GraphQLSchema({
|
||||
query: queryType,
|
||||
mutation: mutationType,
|
||||
subscription: subscriptionType,
|
||||
types: types,
|
||||
directives: directives,
|
||||
assumeValid: options && options.assumeValid,
|
||||
allowedLegacyNames: options && options.allowedLegacyNames
|
||||
});
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.coerceValue = coerceValue;
|
||||
|
||||
var _iterall = require("iterall");
|
||||
|
||||
var _inspect = _interopRequireDefault(require("../jsutils/inspect"));
|
||||
|
||||
var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
|
||||
|
||||
var _orList = _interopRequireDefault(require("../jsutils/orList"));
|
||||
|
||||
var _suggestionList = _interopRequireDefault(require("../jsutils/suggestionList"));
|
||||
|
||||
var _GraphQLError = require("../error/GraphQLError");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
/**
|
||||
* Coerces a JavaScript value given a GraphQL Type.
|
||||
*
|
||||
* Returns either a value which is valid for the provided type or a list of
|
||||
* encountered coercion errors.
|
||||
*
|
||||
*/
|
||||
function coerceValue(value, type, blameNode, path) {
|
||||
// A value must be provided if the type is non-null.
|
||||
if ((0, _definition.isNonNullType)(type)) {
|
||||
if (value == null) {
|
||||
return ofErrors([coercionError("Expected non-nullable type ".concat((0, _inspect.default)(type), " not to be null"), blameNode, path)]);
|
||||
}
|
||||
|
||||
return coerceValue(value, type.ofType, blameNode, path);
|
||||
}
|
||||
|
||||
if (value == null) {
|
||||
// Explicitly return the value null.
|
||||
return ofValue(null);
|
||||
}
|
||||
|
||||
if ((0, _definition.isScalarType)(type)) {
|
||||
// Scalars determine if a value is valid via parseValue(), which can
|
||||
// throw to indicate failure. If it throws, maintain a reference to
|
||||
// the original error.
|
||||
try {
|
||||
var parseResult = type.parseValue(value);
|
||||
|
||||
if ((0, _isInvalid.default)(parseResult)) {
|
||||
return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path)]);
|
||||
}
|
||||
|
||||
return ofValue(parseResult);
|
||||
} catch (error) {
|
||||
return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, error.message, error)]);
|
||||
}
|
||||
}
|
||||
|
||||
if ((0, _definition.isEnumType)(type)) {
|
||||
if (typeof value === 'string') {
|
||||
var enumValue = type.getValue(value);
|
||||
|
||||
if (enumValue) {
|
||||
return ofValue(enumValue.value);
|
||||
}
|
||||
}
|
||||
|
||||
var suggestions = (0, _suggestionList.default)(String(value), type.getValues().map(function (enumValue) {
|
||||
return enumValue.name;
|
||||
}));
|
||||
var didYouMean = suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined;
|
||||
return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, didYouMean)]);
|
||||
}
|
||||
|
||||
if ((0, _definition.isListType)(type)) {
|
||||
var itemType = type.ofType;
|
||||
|
||||
if ((0, _iterall.isCollection)(value)) {
|
||||
var errors;
|
||||
var coercedValue = [];
|
||||
(0, _iterall.forEach)(value, function (itemValue, index) {
|
||||
var coercedItem = coerceValue(itemValue, itemType, blameNode, atPath(path, index));
|
||||
|
||||
if (coercedItem.errors) {
|
||||
errors = add(errors, coercedItem.errors);
|
||||
} else if (!errors) {
|
||||
coercedValue.push(coercedItem.value);
|
||||
}
|
||||
});
|
||||
return errors ? ofErrors(errors) : ofValue(coercedValue);
|
||||
} // Lists accept a non-list value as a list of one.
|
||||
|
||||
|
||||
var coercedItem = coerceValue(value, itemType, blameNode);
|
||||
return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]);
|
||||
}
|
||||
|
||||
if ((0, _definition.isInputObjectType)(type)) {
|
||||
if (_typeof(value) !== 'object') {
|
||||
return ofErrors([coercionError("Expected type ".concat(type.name, " to be an object"), blameNode, path)]);
|
||||
}
|
||||
|
||||
var _errors;
|
||||
|
||||
var _coercedValue = {};
|
||||
var fields = type.getFields(); // Ensure every defined field is valid.
|
||||
|
||||
for (var fieldName in fields) {
|
||||
if (hasOwnProperty.call(fields, fieldName)) {
|
||||
var field = fields[fieldName];
|
||||
var fieldValue = value[fieldName];
|
||||
|
||||
if ((0, _isInvalid.default)(fieldValue)) {
|
||||
if (!(0, _isInvalid.default)(field.defaultValue)) {
|
||||
_coercedValue[fieldName] = field.defaultValue;
|
||||
} else if ((0, _definition.isNonNullType)(field.type)) {
|
||||
_errors = add(_errors, coercionError("Field ".concat(printPath(atPath(path, fieldName)), " of required ") + "type ".concat((0, _inspect.default)(field.type), " was not provided"), blameNode));
|
||||
}
|
||||
} else {
|
||||
var coercedField = coerceValue(fieldValue, field.type, blameNode, atPath(path, fieldName));
|
||||
|
||||
if (coercedField.errors) {
|
||||
_errors = add(_errors, coercedField.errors);
|
||||
} else if (!_errors) {
|
||||
_coercedValue[fieldName] = coercedField.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // Ensure every provided field is defined.
|
||||
|
||||
|
||||
for (var _fieldName in value) {
|
||||
if (hasOwnProperty.call(value, _fieldName)) {
|
||||
if (!fields[_fieldName]) {
|
||||
var _suggestions = (0, _suggestionList.default)(_fieldName, Object.keys(fields));
|
||||
|
||||
var _didYouMean = _suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(_suggestions), "?") : undefined;
|
||||
|
||||
_errors = add(_errors, coercionError("Field \"".concat(_fieldName, "\" is not defined by type ").concat(type.name), blameNode, path, _didYouMean));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _errors ? ofErrors(_errors) : ofValue(_coercedValue);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unexpected type: ".concat(type, "."));
|
||||
}
|
||||
|
||||
function ofValue(value) {
|
||||
return {
|
||||
errors: undefined,
|
||||
value: value
|
||||
};
|
||||
}
|
||||
|
||||
function ofErrors(errors) {
|
||||
return {
|
||||
errors: errors,
|
||||
value: undefined
|
||||
};
|
||||
}
|
||||
|
||||
function add(errors, moreErrors) {
|
||||
return (errors || []).concat(moreErrors);
|
||||
}
|
||||
|
||||
function atPath(prev, key) {
|
||||
return {
|
||||
prev: prev,
|
||||
key: key
|
||||
};
|
||||
}
|
||||
|
||||
function coercionError(message, blameNode, path, subMessage, originalError) {
|
||||
var pathStr = printPath(path); // Return a GraphQLError instance
|
||||
|
||||
return new _GraphQLError.GraphQLError(message + (pathStr ? ' at ' + pathStr : '') + (subMessage ? '; ' + subMessage : '.'), blameNode, undefined, undefined, undefined, originalError);
|
||||
} // Build a string describing the path into the value where the error was found
|
||||
|
||||
|
||||
function printPath(path) {
|
||||
var pathStr = '';
|
||||
var currentPath = path;
|
||||
|
||||
while (currentPath) {
|
||||
pathStr = (typeof currentPath.key === 'string' ? '.' + currentPath.key : '[' + String(currentPath.key) + ']') + pathStr;
|
||||
currentPath = currentPath.prev;
|
||||
}
|
||||
|
||||
return pathStr ? 'value' + pathStr : '';
|
||||
}
|
||||
|
||||
var hasOwnProperty = Object.prototype.hasOwnProperty;
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { forEach, isCollection } from 'iterall';
|
||||
import inspect from '../jsutils/inspect';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import orList from '../jsutils/orList';
|
||||
import suggestionList from '../jsutils/suggestionList';
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import type { ASTNode } from '../language/ast';
|
||||
import {
|
||||
isScalarType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
isListType,
|
||||
isNonNullType,
|
||||
} from '../type/definition';
|
||||
import type { GraphQLInputType } from '../type/definition';
|
||||
|
||||
type CoercedValue = {|
|
||||
+errors: $ReadOnlyArray<GraphQLError> | void,
|
||||
+value: mixed,
|
||||
|};
|
||||
|
||||
type Path = {| +prev: Path | void, +key: string | number |};
|
||||
|
||||
/**
|
||||
* Coerces a JavaScript value given a GraphQL Type.
|
||||
*
|
||||
* Returns either a value which is valid for the provided type or a list of
|
||||
* encountered coercion errors.
|
||||
*
|
||||
*/
|
||||
export function coerceValue(
|
||||
value: mixed,
|
||||
type: GraphQLInputType,
|
||||
blameNode?: ASTNode,
|
||||
path?: Path,
|
||||
): CoercedValue {
|
||||
// A value must be provided if the type is non-null.
|
||||
if (isNonNullType(type)) {
|
||||
if (value == null) {
|
||||
return ofErrors([
|
||||
coercionError(
|
||||
`Expected non-nullable type ${inspect(type)} not to be null`,
|
||||
blameNode,
|
||||
path,
|
||||
),
|
||||
]);
|
||||
}
|
||||
return coerceValue(value, type.ofType, blameNode, path);
|
||||
}
|
||||
|
||||
if (value == null) {
|
||||
// Explicitly return the value null.
|
||||
return ofValue(null);
|
||||
}
|
||||
|
||||
if (isScalarType(type)) {
|
||||
// Scalars determine if a value is valid via parseValue(), which can
|
||||
// throw to indicate failure. If it throws, maintain a reference to
|
||||
// the original error.
|
||||
try {
|
||||
const parseResult = type.parseValue(value);
|
||||
if (isInvalid(parseResult)) {
|
||||
return ofErrors([
|
||||
coercionError(`Expected type ${type.name}`, blameNode, path),
|
||||
]);
|
||||
}
|
||||
return ofValue(parseResult);
|
||||
} catch (error) {
|
||||
return ofErrors([
|
||||
coercionError(
|
||||
`Expected type ${type.name}`,
|
||||
blameNode,
|
||||
path,
|
||||
error.message,
|
||||
error,
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (isEnumType(type)) {
|
||||
if (typeof value === 'string') {
|
||||
const enumValue = type.getValue(value);
|
||||
if (enumValue) {
|
||||
return ofValue(enumValue.value);
|
||||
}
|
||||
}
|
||||
const suggestions = suggestionList(
|
||||
String(value),
|
||||
type.getValues().map(enumValue => enumValue.name),
|
||||
);
|
||||
const didYouMean =
|
||||
suggestions.length !== 0
|
||||
? `did you mean ${orList(suggestions)}?`
|
||||
: undefined;
|
||||
return ofErrors([
|
||||
coercionError(`Expected type ${type.name}`, blameNode, path, didYouMean),
|
||||
]);
|
||||
}
|
||||
|
||||
if (isListType(type)) {
|
||||
const itemType = type.ofType;
|
||||
if (isCollection(value)) {
|
||||
let errors;
|
||||
const coercedValue = [];
|
||||
forEach((value: any), (itemValue, index) => {
|
||||
const coercedItem = coerceValue(
|
||||
itemValue,
|
||||
itemType,
|
||||
blameNode,
|
||||
atPath(path, index),
|
||||
);
|
||||
if (coercedItem.errors) {
|
||||
errors = add(errors, coercedItem.errors);
|
||||
} else if (!errors) {
|
||||
coercedValue.push(coercedItem.value);
|
||||
}
|
||||
});
|
||||
return errors ? ofErrors(errors) : ofValue(coercedValue);
|
||||
}
|
||||
// Lists accept a non-list value as a list of one.
|
||||
const coercedItem = coerceValue(value, itemType, blameNode);
|
||||
return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]);
|
||||
}
|
||||
|
||||
if (isInputObjectType(type)) {
|
||||
if (typeof value !== 'object') {
|
||||
return ofErrors([
|
||||
coercionError(
|
||||
`Expected type ${type.name} to be an object`,
|
||||
blameNode,
|
||||
path,
|
||||
),
|
||||
]);
|
||||
}
|
||||
let errors;
|
||||
const coercedValue = {};
|
||||
const fields = type.getFields();
|
||||
|
||||
// Ensure every defined field is valid.
|
||||
for (const fieldName in fields) {
|
||||
if (hasOwnProperty.call(fields, fieldName)) {
|
||||
const field = fields[fieldName];
|
||||
const fieldValue = value[fieldName];
|
||||
if (isInvalid(fieldValue)) {
|
||||
if (!isInvalid(field.defaultValue)) {
|
||||
coercedValue[fieldName] = field.defaultValue;
|
||||
} else if (isNonNullType(field.type)) {
|
||||
errors = add(
|
||||
errors,
|
||||
coercionError(
|
||||
`Field ${printPath(atPath(path, fieldName))} of required ` +
|
||||
`type ${inspect(field.type)} was not provided`,
|
||||
blameNode,
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const coercedField = coerceValue(
|
||||
fieldValue,
|
||||
field.type,
|
||||
blameNode,
|
||||
atPath(path, fieldName),
|
||||
);
|
||||
if (coercedField.errors) {
|
||||
errors = add(errors, coercedField.errors);
|
||||
} else if (!errors) {
|
||||
coercedValue[fieldName] = coercedField.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure every provided field is defined.
|
||||
for (const fieldName in value) {
|
||||
if (hasOwnProperty.call(value, fieldName)) {
|
||||
if (!fields[fieldName]) {
|
||||
const suggestions = suggestionList(fieldName, Object.keys(fields));
|
||||
const didYouMean =
|
||||
suggestions.length !== 0
|
||||
? `did you mean ${orList(suggestions)}?`
|
||||
: undefined;
|
||||
errors = add(
|
||||
errors,
|
||||
coercionError(
|
||||
`Field "${fieldName}" is not defined by type ${type.name}`,
|
||||
blameNode,
|
||||
path,
|
||||
didYouMean,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors ? ofErrors(errors) : ofValue(coercedValue);
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
throw new Error(`Unexpected type: ${(type: empty)}.`);
|
||||
}
|
||||
|
||||
function ofValue(value) {
|
||||
return { errors: undefined, value };
|
||||
}
|
||||
|
||||
function ofErrors(errors) {
|
||||
return { errors, value: undefined };
|
||||
}
|
||||
|
||||
function add(errors, moreErrors) {
|
||||
return (errors || []).concat(moreErrors);
|
||||
}
|
||||
|
||||
function atPath(prev, key) {
|
||||
return { prev, key };
|
||||
}
|
||||
|
||||
function coercionError(message, blameNode, path, subMessage, originalError) {
|
||||
const pathStr = printPath(path);
|
||||
// Return a GraphQLError instance
|
||||
return new GraphQLError(
|
||||
message +
|
||||
(pathStr ? ' at ' + pathStr : '') +
|
||||
(subMessage ? '; ' + subMessage : '.'),
|
||||
blameNode,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
originalError,
|
||||
);
|
||||
}
|
||||
|
||||
// Build a string describing the path into the value where the error was found
|
||||
function printPath(path) {
|
||||
let pathStr = '';
|
||||
let currentPath = path;
|
||||
while (currentPath) {
|
||||
pathStr =
|
||||
(typeof currentPath.key === 'string'
|
||||
? '.' + currentPath.key
|
||||
: '[' + String(currentPath.key) + ']') + pathStr;
|
||||
currentPath = currentPath.prev;
|
||||
}
|
||||
return pathStr ? 'value' + pathStr : '';
|
||||
}
|
||||
|
||||
const hasOwnProperty = Object.prototype.hasOwnProperty;
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { forEach, isCollection } from 'iterall';
|
||||
import inspect from '../jsutils/inspect';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import orList from '../jsutils/orList';
|
||||
import suggestionList from '../jsutils/suggestionList';
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition';
|
||||
|
||||
/**
|
||||
* Coerces a JavaScript value given a GraphQL Type.
|
||||
*
|
||||
* Returns either a value which is valid for the provided type or a list of
|
||||
* encountered coercion errors.
|
||||
*
|
||||
*/
|
||||
export function coerceValue(value, type, blameNode, path) {
|
||||
// A value must be provided if the type is non-null.
|
||||
if (isNonNullType(type)) {
|
||||
if (value == null) {
|
||||
return ofErrors([coercionError("Expected non-nullable type ".concat(inspect(type), " not to be null"), blameNode, path)]);
|
||||
}
|
||||
|
||||
return coerceValue(value, type.ofType, blameNode, path);
|
||||
}
|
||||
|
||||
if (value == null) {
|
||||
// Explicitly return the value null.
|
||||
return ofValue(null);
|
||||
}
|
||||
|
||||
if (isScalarType(type)) {
|
||||
// Scalars determine if a value is valid via parseValue(), which can
|
||||
// throw to indicate failure. If it throws, maintain a reference to
|
||||
// the original error.
|
||||
try {
|
||||
var parseResult = type.parseValue(value);
|
||||
|
||||
if (isInvalid(parseResult)) {
|
||||
return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path)]);
|
||||
}
|
||||
|
||||
return ofValue(parseResult);
|
||||
} catch (error) {
|
||||
return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, error.message, error)]);
|
||||
}
|
||||
}
|
||||
|
||||
if (isEnumType(type)) {
|
||||
if (typeof value === 'string') {
|
||||
var enumValue = type.getValue(value);
|
||||
|
||||
if (enumValue) {
|
||||
return ofValue(enumValue.value);
|
||||
}
|
||||
}
|
||||
|
||||
var suggestions = suggestionList(String(value), type.getValues().map(function (enumValue) {
|
||||
return enumValue.name;
|
||||
}));
|
||||
var didYouMean = suggestions.length !== 0 ? "did you mean ".concat(orList(suggestions), "?") : undefined;
|
||||
return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, didYouMean)]);
|
||||
}
|
||||
|
||||
if (isListType(type)) {
|
||||
var itemType = type.ofType;
|
||||
|
||||
if (isCollection(value)) {
|
||||
var errors;
|
||||
var coercedValue = [];
|
||||
forEach(value, function (itemValue, index) {
|
||||
var coercedItem = coerceValue(itemValue, itemType, blameNode, atPath(path, index));
|
||||
|
||||
if (coercedItem.errors) {
|
||||
errors = add(errors, coercedItem.errors);
|
||||
} else if (!errors) {
|
||||
coercedValue.push(coercedItem.value);
|
||||
}
|
||||
});
|
||||
return errors ? ofErrors(errors) : ofValue(coercedValue);
|
||||
} // Lists accept a non-list value as a list of one.
|
||||
|
||||
|
||||
var coercedItem = coerceValue(value, itemType, blameNode);
|
||||
return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]);
|
||||
}
|
||||
|
||||
if (isInputObjectType(type)) {
|
||||
if (_typeof(value) !== 'object') {
|
||||
return ofErrors([coercionError("Expected type ".concat(type.name, " to be an object"), blameNode, path)]);
|
||||
}
|
||||
|
||||
var _errors;
|
||||
|
||||
var _coercedValue = {};
|
||||
var fields = type.getFields(); // Ensure every defined field is valid.
|
||||
|
||||
for (var fieldName in fields) {
|
||||
if (hasOwnProperty.call(fields, fieldName)) {
|
||||
var field = fields[fieldName];
|
||||
var fieldValue = value[fieldName];
|
||||
|
||||
if (isInvalid(fieldValue)) {
|
||||
if (!isInvalid(field.defaultValue)) {
|
||||
_coercedValue[fieldName] = field.defaultValue;
|
||||
} else if (isNonNullType(field.type)) {
|
||||
_errors = add(_errors, coercionError("Field ".concat(printPath(atPath(path, fieldName)), " of required ") + "type ".concat(inspect(field.type), " was not provided"), blameNode));
|
||||
}
|
||||
} else {
|
||||
var coercedField = coerceValue(fieldValue, field.type, blameNode, atPath(path, fieldName));
|
||||
|
||||
if (coercedField.errors) {
|
||||
_errors = add(_errors, coercedField.errors);
|
||||
} else if (!_errors) {
|
||||
_coercedValue[fieldName] = coercedField.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // Ensure every provided field is defined.
|
||||
|
||||
|
||||
for (var _fieldName in value) {
|
||||
if (hasOwnProperty.call(value, _fieldName)) {
|
||||
if (!fields[_fieldName]) {
|
||||
var _suggestions = suggestionList(_fieldName, Object.keys(fields));
|
||||
|
||||
var _didYouMean = _suggestions.length !== 0 ? "did you mean ".concat(orList(_suggestions), "?") : undefined;
|
||||
|
||||
_errors = add(_errors, coercionError("Field \"".concat(_fieldName, "\" is not defined by type ").concat(type.name), blameNode, path, _didYouMean));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _errors ? ofErrors(_errors) : ofValue(_coercedValue);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unexpected type: ".concat(type, "."));
|
||||
}
|
||||
|
||||
function ofValue(value) {
|
||||
return {
|
||||
errors: undefined,
|
||||
value: value
|
||||
};
|
||||
}
|
||||
|
||||
function ofErrors(errors) {
|
||||
return {
|
||||
errors: errors,
|
||||
value: undefined
|
||||
};
|
||||
}
|
||||
|
||||
function add(errors, moreErrors) {
|
||||
return (errors || []).concat(moreErrors);
|
||||
}
|
||||
|
||||
function atPath(prev, key) {
|
||||
return {
|
||||
prev: prev,
|
||||
key: key
|
||||
};
|
||||
}
|
||||
|
||||
function coercionError(message, blameNode, path, subMessage, originalError) {
|
||||
var pathStr = printPath(path); // Return a GraphQLError instance
|
||||
|
||||
return new GraphQLError(message + (pathStr ? ' at ' + pathStr : '') + (subMessage ? '; ' + subMessage : '.'), blameNode, undefined, undefined, undefined, originalError);
|
||||
} // Build a string describing the path into the value where the error was found
|
||||
|
||||
|
||||
function printPath(path) {
|
||||
var pathStr = '';
|
||||
var currentPath = path;
|
||||
|
||||
while (currentPath) {
|
||||
pathStr = (typeof currentPath.key === 'string' ? '.' + currentPath.key : '[' + String(currentPath.key) + ']') + pathStr;
|
||||
currentPath = currentPath.prev;
|
||||
}
|
||||
|
||||
return pathStr ? 'value' + pathStr : '';
|
||||
}
|
||||
|
||||
var hasOwnProperty = Object.prototype.hasOwnProperty;
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.concatAST = concatAST;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Provided a collection of ASTs, presumably each from different files,
|
||||
* concatenate the ASTs together into batched AST, useful for validating many
|
||||
* GraphQL source files which together represent one conceptual application.
|
||||
*/
|
||||
function concatAST(asts) {
|
||||
var batchDefinitions = [];
|
||||
|
||||
for (var i = 0; i < asts.length; i++) {
|
||||
var definitions = asts[i].definitions;
|
||||
|
||||
for (var j = 0; j < definitions.length; j++) {
|
||||
batchDefinitions.push(definitions[j]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'Document',
|
||||
definitions: batchDefinitions
|
||||
};
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import type { DocumentNode } from '../language/ast';
|
||||
|
||||
/**
|
||||
* Provided a collection of ASTs, presumably each from different files,
|
||||
* concatenate the ASTs together into batched AST, useful for validating many
|
||||
* GraphQL source files which together represent one conceptual application.
|
||||
*/
|
||||
export function concatAST(asts: $ReadOnlyArray<DocumentNode>): DocumentNode {
|
||||
const batchDefinitions = [];
|
||||
for (let i = 0; i < asts.length; i++) {
|
||||
const definitions = asts[i].definitions;
|
||||
for (let j = 0; j < definitions.length; j++) {
|
||||
batchDefinitions.push(definitions[j]);
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: 'Document',
|
||||
definitions: batchDefinitions,
|
||||
};
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Provided a collection of ASTs, presumably each from different files,
|
||||
* concatenate the ASTs together into batched AST, useful for validating many
|
||||
* GraphQL source files which together represent one conceptual application.
|
||||
*/
|
||||
export function concatAST(asts) {
|
||||
var batchDefinitions = [];
|
||||
|
||||
for (var i = 0; i < asts.length; i++) {
|
||||
var definitions = asts[i].definitions;
|
||||
|
||||
for (var j = 0; j < definitions.length; j++) {
|
||||
batchDefinitions.push(definitions[j]);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'Document',
|
||||
definitions: batchDefinitions
|
||||
};
|
||||
}
|
||||
+794
@@ -0,0 +1,794 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.extendSchema = extendSchema;
|
||||
|
||||
var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
|
||||
|
||||
var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
|
||||
|
||||
var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
|
||||
|
||||
var _objectValues = _interopRequireDefault(require("../jsutils/objectValues"));
|
||||
|
||||
var _buildASTSchema = require("./buildASTSchema");
|
||||
|
||||
var _validate = require("../validation/validate");
|
||||
|
||||
var _GraphQLError = require("../error/GraphQLError");
|
||||
|
||||
var _schema = require("../type/schema");
|
||||
|
||||
var _introspection = require("../type/introspection");
|
||||
|
||||
var _scalars = require("../type/scalars");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _directives = require("../type/directives");
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _predicates = require("../language/predicates");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
|
||||
|
||||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
||||
|
||||
/**
|
||||
* Produces a new schema given an existing schema and a document which may
|
||||
* contain GraphQL type extensions and definitions. The original schema will
|
||||
* remain unaltered.
|
||||
*
|
||||
* Because a schema represents a graph of references, a schema cannot be
|
||||
* extended without effectively making an entire copy. We do not know until it's
|
||||
* too late if subgraphs remain unchanged.
|
||||
*
|
||||
* This algorithm copies the provided schema, applying extensions while
|
||||
* producing the copy. The original schema remains unaltered.
|
||||
*
|
||||
* Accepts options as a third argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
function extendSchema(schema, documentAST, options) {
|
||||
!(0, _schema.isSchema)(schema) ? (0, _invariant.default)(0, 'Must provide valid GraphQLSchema') : void 0;
|
||||
!(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0;
|
||||
|
||||
if (!options || !(options.assumeValid || options.assumeValidSDL)) {
|
||||
(0, _validate.assertValidSDLExtension)(documentAST, schema);
|
||||
} // Collect the type definitions and extensions found in the document.
|
||||
|
||||
|
||||
var typeDefinitionMap = Object.create(null);
|
||||
var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can
|
||||
// have the same name. For example, a type named "skip".
|
||||
|
||||
var directiveDefinitions = [];
|
||||
var schemaDef; // Schema extensions are collected which may add additional operation types.
|
||||
|
||||
var schemaExtensions = [];
|
||||
|
||||
for (var i = 0; i < documentAST.definitions.length; i++) {
|
||||
var def = documentAST.definitions[i];
|
||||
|
||||
if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) {
|
||||
schemaDef = def;
|
||||
} else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) {
|
||||
schemaExtensions.push(def);
|
||||
} else if ((0, _predicates.isTypeDefinitionNode)(def)) {
|
||||
// Sanity check that none of the defined types conflict with the
|
||||
// schema's existing types.
|
||||
var typeName = def.name.value;
|
||||
|
||||
if (schema.getType(typeName)) {
|
||||
throw new _GraphQLError.GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also ") + 'be defined in this type definition.', [def]);
|
||||
}
|
||||
|
||||
typeDefinitionMap[typeName] = def;
|
||||
} else if ((0, _predicates.isTypeExtensionNode)(def)) {
|
||||
// Sanity check that this type extension exists within the
|
||||
// schema's existing types.
|
||||
var extendedTypeName = def.name.value;
|
||||
var existingType = schema.getType(extendedTypeName);
|
||||
|
||||
if (!existingType) {
|
||||
throw new _GraphQLError.GraphQLError("Cannot extend type \"".concat(extendedTypeName, "\" because it does not ") + 'exist in the existing schema.', [def]);
|
||||
}
|
||||
|
||||
checkExtensionNode(existingType, def);
|
||||
var existingTypeExtensions = typeExtensionsMap[extendedTypeName];
|
||||
typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def];
|
||||
} else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
|
||||
var directiveName = def.name.value;
|
||||
var existingDirective = schema.getDirective(directiveName);
|
||||
|
||||
if (existingDirective) {
|
||||
throw new _GraphQLError.GraphQLError("Directive \"".concat(directiveName, "\" already exists in the schema. It ") + 'cannot be redefined.', [def]);
|
||||
}
|
||||
|
||||
directiveDefinitions.push(def);
|
||||
}
|
||||
} // If this document contains no new types, extensions, or directives then
|
||||
// return the same unmodified GraphQLSchema instance.
|
||||
|
||||
|
||||
if (Object.keys(typeExtensionsMap).length === 0 && Object.keys(typeDefinitionMap).length === 0 && directiveDefinitions.length === 0 && schemaExtensions.length === 0 && !schemaDef) {
|
||||
return schema;
|
||||
}
|
||||
|
||||
var astBuilder = new _buildASTSchema.ASTDefinitionBuilder(typeDefinitionMap, options, function (typeRef) {
|
||||
var typeName = typeRef.name.value;
|
||||
var existingType = schema.getType(typeName);
|
||||
|
||||
if (existingType) {
|
||||
return extendNamedType(existingType);
|
||||
}
|
||||
|
||||
throw new _GraphQLError.GraphQLError("Unknown type: \"".concat(typeName, "\". Ensure that this type exists ") + 'either in the original schema, or is added in a type definition.', [typeRef]);
|
||||
});
|
||||
var extendTypeCache = Object.create(null); // Get the extended root operation types.
|
||||
|
||||
var operationTypes = {
|
||||
query: extendMaybeNamedType(schema.getQueryType()),
|
||||
mutation: extendMaybeNamedType(schema.getMutationType()),
|
||||
subscription: extendMaybeNamedType(schema.getSubscriptionType())
|
||||
};
|
||||
|
||||
if (schemaDef) {
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = schemaDef.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var _ref2 = _step.value;
|
||||
var operation = _ref2.operation,
|
||||
type = _ref2.type;
|
||||
|
||||
if (operationTypes[operation]) {
|
||||
throw new Error("Must provide only one ".concat(operation, " type in schema."));
|
||||
} // Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
|
||||
|
||||
operationTypes[operation] = astBuilder.buildType(type);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // Then, incorporate schema definition and all schema extensions.
|
||||
|
||||
|
||||
for (var _i = 0; _i < schemaExtensions.length; _i++) {
|
||||
var schemaExtension = schemaExtensions[_i];
|
||||
|
||||
if (schemaExtension.operationTypes) {
|
||||
var _iteratorNormalCompletion12 = true;
|
||||
var _didIteratorError12 = false;
|
||||
var _iteratorError12 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator12 = schemaExtension.operationTypes[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
|
||||
var _ref4 = _step12.value;
|
||||
var operation = _ref4.operation,
|
||||
type = _ref4.type;
|
||||
|
||||
if (operationTypes[operation]) {
|
||||
throw new Error("Must provide only one ".concat(operation, " type in schema."));
|
||||
} // Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
|
||||
|
||||
operationTypes[operation] = astBuilder.buildType(type);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError12 = true;
|
||||
_iteratorError12 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion12 && _iterator12.return != null) {
|
||||
_iterator12.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError12) {
|
||||
throw _iteratorError12;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var schemaExtensionASTNodes = schemaExtensions ? schema.extensionASTNodes ? schema.extensionASTNodes.concat(schemaExtensions) : schemaExtensions : schema.extensionASTNodes;
|
||||
var types = (0, _objectValues.default)(schema.getTypeMap()).map(function (type) {
|
||||
return extendNamedType(type);
|
||||
}).concat((0, _objectValues.default)(typeDefinitionMap).map(function (type) {
|
||||
return astBuilder.buildType(type);
|
||||
})); // Support both original legacy names and extended legacy names.
|
||||
|
||||
var allowedLegacyNames = schema.__allowedLegacyNames.concat(options && options.allowedLegacyNames || []); // Then produce and return a Schema with these types.
|
||||
|
||||
|
||||
return new _schema.GraphQLSchema(_objectSpread({}, operationTypes, {
|
||||
types: types,
|
||||
directives: getMergedDirectives(),
|
||||
astNode: schema.astNode,
|
||||
extensionASTNodes: schemaExtensionASTNodes,
|
||||
allowedLegacyNames: allowedLegacyNames
|
||||
})); // Below are functions used for producing this schema that have closed over
|
||||
// this scope and have access to the schema, cache, and newly defined types.
|
||||
|
||||
function getMergedDirectives() {
|
||||
var existingDirectives = schema.getDirectives().map(extendDirective);
|
||||
!existingDirectives ? (0, _invariant.default)(0, 'schema must have default directives') : void 0;
|
||||
return existingDirectives.concat(directiveDefinitions.map(function (node) {
|
||||
return astBuilder.buildDirective(node);
|
||||
}));
|
||||
}
|
||||
|
||||
function extendMaybeNamedType(type) {
|
||||
return type ? extendNamedType(type) : null;
|
||||
}
|
||||
|
||||
function extendNamedType(type) {
|
||||
if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) {
|
||||
// Builtin types are not extended.
|
||||
return type;
|
||||
}
|
||||
|
||||
var name = type.name;
|
||||
|
||||
if (!extendTypeCache[name]) {
|
||||
if ((0, _definition.isScalarType)(type)) {
|
||||
extendTypeCache[name] = extendScalarType(type);
|
||||
} else if ((0, _definition.isObjectType)(type)) {
|
||||
extendTypeCache[name] = extendObjectType(type);
|
||||
} else if ((0, _definition.isInterfaceType)(type)) {
|
||||
extendTypeCache[name] = extendInterfaceType(type);
|
||||
} else if ((0, _definition.isUnionType)(type)) {
|
||||
extendTypeCache[name] = extendUnionType(type);
|
||||
} else if ((0, _definition.isEnumType)(type)) {
|
||||
extendTypeCache[name] = extendEnumType(type);
|
||||
} else if ((0, _definition.isInputObjectType)(type)) {
|
||||
extendTypeCache[name] = extendInputObjectType(type);
|
||||
}
|
||||
}
|
||||
|
||||
return extendTypeCache[name];
|
||||
}
|
||||
|
||||
function extendDirective(directive) {
|
||||
return new _directives.GraphQLDirective({
|
||||
name: directive.name,
|
||||
description: directive.description,
|
||||
locations: directive.locations,
|
||||
args: extendArgs(directive.args),
|
||||
astNode: directive.astNode
|
||||
});
|
||||
}
|
||||
|
||||
function extendInputObjectType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new _definition.GraphQLInputObjectType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
fields: function fields() {
|
||||
return extendInputFieldMap(type);
|
||||
},
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes
|
||||
});
|
||||
}
|
||||
|
||||
function extendInputFieldMap(type) {
|
||||
var newFieldMap = Object.create(null);
|
||||
var oldFieldMap = type.getFields();
|
||||
|
||||
var _arr = Object.keys(oldFieldMap);
|
||||
|
||||
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
|
||||
var _fieldName = _arr[_i2];
|
||||
var _field = oldFieldMap[_fieldName];
|
||||
newFieldMap[_fieldName] = {
|
||||
description: _field.description,
|
||||
type: extendType(_field.type),
|
||||
defaultValue: _field.defaultValue,
|
||||
astNode: _field.astNode
|
||||
};
|
||||
} // If there are any extensions to the fields, apply those here.
|
||||
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = extensions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var extension = _step2.value;
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = extension.fields[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var field = _step3.value;
|
||||
var fieldName = field.name.value;
|
||||
|
||||
if (oldFieldMap[fieldName]) {
|
||||
throw new _GraphQLError.GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]);
|
||||
}
|
||||
|
||||
newFieldMap[fieldName] = astBuilder.buildInputField(field);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newFieldMap;
|
||||
}
|
||||
|
||||
function extendEnumType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new _definition.GraphQLEnumType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
values: extendValueMap(type),
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes
|
||||
});
|
||||
}
|
||||
|
||||
function extendValueMap(type) {
|
||||
var newValueMap = Object.create(null);
|
||||
var oldValueMap = (0, _keyMap.default)(type.getValues(), function (value) {
|
||||
return value.name;
|
||||
});
|
||||
|
||||
var _arr2 = Object.keys(oldValueMap);
|
||||
|
||||
for (var _i3 = 0; _i3 < _arr2.length; _i3++) {
|
||||
var _valueName = _arr2[_i3];
|
||||
var _value = oldValueMap[_valueName];
|
||||
newValueMap[_valueName] = {
|
||||
name: _value.name,
|
||||
description: _value.description,
|
||||
value: _value.value,
|
||||
deprecationReason: _value.deprecationReason,
|
||||
astNode: _value.astNode
|
||||
};
|
||||
} // If there are any extensions to the values, apply those here.
|
||||
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion4 = true;
|
||||
var _didIteratorError4 = false;
|
||||
var _iteratorError4 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator4 = extensions[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
|
||||
var extension = _step4.value;
|
||||
var _iteratorNormalCompletion5 = true;
|
||||
var _didIteratorError5 = false;
|
||||
var _iteratorError5 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator5 = extension.values[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
|
||||
var value = _step5.value;
|
||||
var valueName = value.name.value;
|
||||
|
||||
if (oldValueMap[valueName]) {
|
||||
throw new _GraphQLError.GraphQLError("Enum value \"".concat(type.name, ".").concat(valueName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [value]);
|
||||
}
|
||||
|
||||
newValueMap[valueName] = astBuilder.buildEnumValue(value);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError5 = true;
|
||||
_iteratorError5 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
|
||||
_iterator5.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError5) {
|
||||
throw _iteratorError5;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError4 = true;
|
||||
_iteratorError4 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
|
||||
_iterator4.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError4) {
|
||||
throw _iteratorError4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newValueMap;
|
||||
}
|
||||
|
||||
function extendScalarType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new _definition.GraphQLScalarType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes,
|
||||
serialize: type.serialize,
|
||||
parseValue: type.parseValue,
|
||||
parseLiteral: type.parseLiteral
|
||||
});
|
||||
}
|
||||
|
||||
function extendObjectType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new _definition.GraphQLObjectType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
interfaces: function interfaces() {
|
||||
return extendImplementedInterfaces(type);
|
||||
},
|
||||
fields: function fields() {
|
||||
return extendFieldMap(type);
|
||||
},
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes,
|
||||
isTypeOf: type.isTypeOf
|
||||
});
|
||||
}
|
||||
|
||||
function extendArgs(args) {
|
||||
return (0, _keyValMap.default)(args, function (arg) {
|
||||
return arg.name;
|
||||
}, function (arg) {
|
||||
return {
|
||||
type: extendType(arg.type),
|
||||
defaultValue: arg.defaultValue,
|
||||
description: arg.description,
|
||||
astNode: arg.astNode
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function extendInterfaceType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new _definition.GraphQLInterfaceType({
|
||||
name: type.name,
|
||||
description: type.description,
|
||||
fields: function fields() {
|
||||
return extendFieldMap(type);
|
||||
},
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes,
|
||||
resolveType: type.resolveType
|
||||
});
|
||||
}
|
||||
|
||||
function extendUnionType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new _definition.GraphQLUnionType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
types: function types() {
|
||||
return extendPossibleTypes(type);
|
||||
},
|
||||
astNode: type.astNode,
|
||||
resolveType: type.resolveType,
|
||||
extensionASTNodes: extensionASTNodes
|
||||
});
|
||||
}
|
||||
|
||||
function extendPossibleTypes(type) {
|
||||
var possibleTypes = type.getTypes().map(extendNamedType); // If there are any extensions to the union, apply those here.
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion6 = true;
|
||||
var _didIteratorError6 = false;
|
||||
var _iteratorError6 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator6 = extensions[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
|
||||
var extension = _step6.value;
|
||||
var _iteratorNormalCompletion7 = true;
|
||||
var _didIteratorError7 = false;
|
||||
var _iteratorError7 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator7 = extension.types[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
|
||||
var namedType = _step7.value;
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
possibleTypes.push(astBuilder.buildType(namedType));
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError7 = true;
|
||||
_iteratorError7 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
|
||||
_iterator7.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError7) {
|
||||
throw _iteratorError7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError6 = true;
|
||||
_iteratorError6 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
|
||||
_iterator6.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError6) {
|
||||
throw _iteratorError6;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return possibleTypes;
|
||||
}
|
||||
|
||||
function extendImplementedInterfaces(type) {
|
||||
var interfaces = type.getInterfaces().map(extendNamedType); // If there are any extensions to the interfaces, apply those here.
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion8 = true;
|
||||
var _didIteratorError8 = false;
|
||||
var _iteratorError8 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator8 = extensions[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
|
||||
var extension = _step8.value;
|
||||
var _iteratorNormalCompletion9 = true;
|
||||
var _didIteratorError9 = false;
|
||||
var _iteratorError9 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator9 = extension.interfaces[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
|
||||
var namedType = _step9.value;
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
interfaces.push(astBuilder.buildType(namedType));
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError9 = true;
|
||||
_iteratorError9 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
|
||||
_iterator9.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError9) {
|
||||
throw _iteratorError9;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError8 = true;
|
||||
_iteratorError8 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
|
||||
_iterator8.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError8) {
|
||||
throw _iteratorError8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return interfaces;
|
||||
}
|
||||
|
||||
function extendFieldMap(type) {
|
||||
var newFieldMap = Object.create(null);
|
||||
var oldFieldMap = type.getFields();
|
||||
|
||||
var _arr3 = Object.keys(oldFieldMap);
|
||||
|
||||
for (var _i4 = 0; _i4 < _arr3.length; _i4++) {
|
||||
var _fieldName2 = _arr3[_i4];
|
||||
var _field2 = oldFieldMap[_fieldName2];
|
||||
newFieldMap[_fieldName2] = {
|
||||
description: _field2.description,
|
||||
deprecationReason: _field2.deprecationReason,
|
||||
type: extendType(_field2.type),
|
||||
args: extendArgs(_field2.args),
|
||||
astNode: _field2.astNode,
|
||||
resolve: _field2.resolve
|
||||
};
|
||||
} // If there are any extensions to the fields, apply those here.
|
||||
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion10 = true;
|
||||
var _didIteratorError10 = false;
|
||||
var _iteratorError10 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator10 = extensions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
|
||||
var extension = _step10.value;
|
||||
var _iteratorNormalCompletion11 = true;
|
||||
var _didIteratorError11 = false;
|
||||
var _iteratorError11 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator11 = extension.fields[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
|
||||
var field = _step11.value;
|
||||
var fieldName = field.name.value;
|
||||
|
||||
if (oldFieldMap[fieldName]) {
|
||||
throw new _GraphQLError.GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]);
|
||||
}
|
||||
|
||||
newFieldMap[fieldName] = astBuilder.buildField(field);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError11 = true;
|
||||
_iteratorError11 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion11 && _iterator11.return != null) {
|
||||
_iterator11.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError11) {
|
||||
throw _iteratorError11;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError10 = true;
|
||||
_iteratorError10 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
|
||||
_iterator10.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError10) {
|
||||
throw _iteratorError10;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newFieldMap;
|
||||
}
|
||||
|
||||
function extendType(typeDef) {
|
||||
if ((0, _definition.isListType)(typeDef)) {
|
||||
return (0, _definition.GraphQLList)(extendType(typeDef.ofType));
|
||||
}
|
||||
|
||||
if ((0, _definition.isNonNullType)(typeDef)) {
|
||||
return (0, _definition.GraphQLNonNull)(extendType(typeDef.ofType));
|
||||
}
|
||||
|
||||
return extendNamedType(typeDef);
|
||||
}
|
||||
}
|
||||
|
||||
function checkExtensionNode(type, node) {
|
||||
switch (node.kind) {
|
||||
case _kinds.Kind.OBJECT_TYPE_EXTENSION:
|
||||
if (!(0, _definition.isObjectType)(type)) {
|
||||
throw new _GraphQLError.GraphQLError("Cannot extend non-object type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.INTERFACE_TYPE_EXTENSION:
|
||||
if (!(0, _definition.isInterfaceType)(type)) {
|
||||
throw new _GraphQLError.GraphQLError("Cannot extend non-interface type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.ENUM_TYPE_EXTENSION:
|
||||
if (!(0, _definition.isEnumType)(type)) {
|
||||
throw new _GraphQLError.GraphQLError("Cannot extend non-enum type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.UNION_TYPE_EXTENSION:
|
||||
if (!(0, _definition.isUnionType)(type)) {
|
||||
throw new _GraphQLError.GraphQLError("Cannot extend non-union type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION:
|
||||
if (!(0, _definition.isInputObjectType)(type)) {
|
||||
throw new _GraphQLError.GraphQLError("Cannot extend non-input object type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
+645
@@ -0,0 +1,645 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import invariant from '../jsutils/invariant';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import { ASTDefinitionBuilder } from './buildASTSchema';
|
||||
import { assertValidSDLExtension } from '../validation/validate';
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import { isSchema, GraphQLSchema } from '../type/schema';
|
||||
import { isIntrospectionType } from '../type/introspection';
|
||||
import { isSpecifiedScalarType } from '../type/scalars';
|
||||
|
||||
import type { GraphQLSchemaValidationOptions } from '../type/schema';
|
||||
|
||||
import type {
|
||||
GraphQLType,
|
||||
GraphQLNamedType,
|
||||
GraphQLArgument,
|
||||
GraphQLFieldConfigArgumentMap,
|
||||
} from '../type/definition';
|
||||
|
||||
import {
|
||||
isScalarType,
|
||||
isObjectType,
|
||||
isInterfaceType,
|
||||
isUnionType,
|
||||
isListType,
|
||||
isNonNullType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
GraphQLList,
|
||||
GraphQLNonNull,
|
||||
GraphQLScalarType,
|
||||
GraphQLObjectType,
|
||||
GraphQLInterfaceType,
|
||||
GraphQLUnionType,
|
||||
GraphQLEnumType,
|
||||
GraphQLInputObjectType,
|
||||
} from '../type/definition';
|
||||
|
||||
import { GraphQLDirective } from '../type/directives';
|
||||
|
||||
import { Kind } from '../language/kinds';
|
||||
|
||||
import type {
|
||||
DocumentNode,
|
||||
DirectiveDefinitionNode,
|
||||
SchemaExtensionNode,
|
||||
SchemaDefinitionNode,
|
||||
} from '../language/ast';
|
||||
import {
|
||||
isTypeDefinitionNode,
|
||||
isTypeExtensionNode,
|
||||
} from '../language/predicates';
|
||||
|
||||
type Options = {|
|
||||
...GraphQLSchemaValidationOptions,
|
||||
|
||||
/**
|
||||
* Descriptions are defined as preceding string literals, however an older
|
||||
* experimental version of the SDL supported preceding comments as
|
||||
* descriptions. Set to true to enable this deprecated behavior.
|
||||
* This option is provided to ease adoption and will be removed in v16.
|
||||
*
|
||||
* Default: false
|
||||
*/
|
||||
commentDescriptions?: boolean,
|
||||
|
||||
/**
|
||||
* Set to true to assume the SDL is valid.
|
||||
*
|
||||
* Default: false
|
||||
*/
|
||||
assumeValidSDL?: boolean,
|
||||
|};
|
||||
|
||||
/**
|
||||
* Produces a new schema given an existing schema and a document which may
|
||||
* contain GraphQL type extensions and definitions. The original schema will
|
||||
* remain unaltered.
|
||||
*
|
||||
* Because a schema represents a graph of references, a schema cannot be
|
||||
* extended without effectively making an entire copy. We do not know until it's
|
||||
* too late if subgraphs remain unchanged.
|
||||
*
|
||||
* This algorithm copies the provided schema, applying extensions while
|
||||
* producing the copy. The original schema remains unaltered.
|
||||
*
|
||||
* Accepts options as a third argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
export function extendSchema(
|
||||
schema: GraphQLSchema,
|
||||
documentAST: DocumentNode,
|
||||
options?: Options,
|
||||
): GraphQLSchema {
|
||||
invariant(isSchema(schema), 'Must provide valid GraphQLSchema');
|
||||
|
||||
invariant(
|
||||
documentAST && documentAST.kind === Kind.DOCUMENT,
|
||||
'Must provide valid Document AST',
|
||||
);
|
||||
|
||||
if (!options || !(options.assumeValid || options.assumeValidSDL)) {
|
||||
assertValidSDLExtension(documentAST, schema);
|
||||
}
|
||||
|
||||
// Collect the type definitions and extensions found in the document.
|
||||
const typeDefinitionMap = Object.create(null);
|
||||
const typeExtensionsMap = Object.create(null);
|
||||
|
||||
// New directives and types are separate because a directives and types can
|
||||
// have the same name. For example, a type named "skip".
|
||||
const directiveDefinitions: Array<DirectiveDefinitionNode> = [];
|
||||
|
||||
let schemaDef: ?SchemaDefinitionNode;
|
||||
// Schema extensions are collected which may add additional operation types.
|
||||
const schemaExtensions: Array<SchemaExtensionNode> = [];
|
||||
|
||||
for (let i = 0; i < documentAST.definitions.length; i++) {
|
||||
const def = documentAST.definitions[i];
|
||||
if (def.kind === Kind.SCHEMA_DEFINITION) {
|
||||
schemaDef = def;
|
||||
} else if (def.kind === Kind.SCHEMA_EXTENSION) {
|
||||
schemaExtensions.push(def);
|
||||
} else if (isTypeDefinitionNode(def)) {
|
||||
// Sanity check that none of the defined types conflict with the
|
||||
// schema's existing types.
|
||||
const typeName = def.name.value;
|
||||
if (schema.getType(typeName)) {
|
||||
throw new GraphQLError(
|
||||
`Type "${typeName}" already exists in the schema. It cannot also ` +
|
||||
'be defined in this type definition.',
|
||||
[def],
|
||||
);
|
||||
}
|
||||
typeDefinitionMap[typeName] = def;
|
||||
} else if (isTypeExtensionNode(def)) {
|
||||
// Sanity check that this type extension exists within the
|
||||
// schema's existing types.
|
||||
const extendedTypeName = def.name.value;
|
||||
const existingType = schema.getType(extendedTypeName);
|
||||
if (!existingType) {
|
||||
throw new GraphQLError(
|
||||
`Cannot extend type "${extendedTypeName}" because it does not ` +
|
||||
'exist in the existing schema.',
|
||||
[def],
|
||||
);
|
||||
}
|
||||
checkExtensionNode(existingType, def);
|
||||
|
||||
const existingTypeExtensions = typeExtensionsMap[extendedTypeName];
|
||||
typeExtensionsMap[extendedTypeName] = existingTypeExtensions
|
||||
? existingTypeExtensions.concat([def])
|
||||
: [def];
|
||||
} else if (def.kind === Kind.DIRECTIVE_DEFINITION) {
|
||||
const directiveName = def.name.value;
|
||||
const existingDirective = schema.getDirective(directiveName);
|
||||
if (existingDirective) {
|
||||
throw new GraphQLError(
|
||||
`Directive "${directiveName}" already exists in the schema. It ` +
|
||||
'cannot be redefined.',
|
||||
[def],
|
||||
);
|
||||
}
|
||||
directiveDefinitions.push(def);
|
||||
}
|
||||
}
|
||||
|
||||
// If this document contains no new types, extensions, or directives then
|
||||
// return the same unmodified GraphQLSchema instance.
|
||||
if (
|
||||
Object.keys(typeExtensionsMap).length === 0 &&
|
||||
Object.keys(typeDefinitionMap).length === 0 &&
|
||||
directiveDefinitions.length === 0 &&
|
||||
schemaExtensions.length === 0 &&
|
||||
!schemaDef
|
||||
) {
|
||||
return schema;
|
||||
}
|
||||
|
||||
const astBuilder = new ASTDefinitionBuilder(
|
||||
typeDefinitionMap,
|
||||
options,
|
||||
typeRef => {
|
||||
const typeName = typeRef.name.value;
|
||||
const existingType = schema.getType(typeName);
|
||||
if (existingType) {
|
||||
return extendNamedType(existingType);
|
||||
}
|
||||
|
||||
throw new GraphQLError(
|
||||
`Unknown type: "${typeName}". Ensure that this type exists ` +
|
||||
'either in the original schema, or is added in a type definition.',
|
||||
[typeRef],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const extendTypeCache = Object.create(null);
|
||||
|
||||
// Get the extended root operation types.
|
||||
const operationTypes = {
|
||||
query: extendMaybeNamedType(schema.getQueryType()),
|
||||
mutation: extendMaybeNamedType(schema.getMutationType()),
|
||||
subscription: extendMaybeNamedType(schema.getSubscriptionType()),
|
||||
};
|
||||
|
||||
if (schemaDef) {
|
||||
for (const { operation, type } of schemaDef.operationTypes) {
|
||||
if (operationTypes[operation]) {
|
||||
throw new Error(`Must provide only one ${operation} type in schema.`);
|
||||
}
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
operationTypes[operation] = (astBuilder.buildType(type): any);
|
||||
}
|
||||
}
|
||||
// Then, incorporate schema definition and all schema extensions.
|
||||
for (const schemaExtension of schemaExtensions) {
|
||||
if (schemaExtension.operationTypes) {
|
||||
for (const { operation, type } of schemaExtension.operationTypes) {
|
||||
if (operationTypes[operation]) {
|
||||
throw new Error(`Must provide only one ${operation} type in schema.`);
|
||||
}
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
operationTypes[operation] = (astBuilder.buildType(type): any);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const schemaExtensionASTNodes = schemaExtensions
|
||||
? schema.extensionASTNodes
|
||||
? schema.extensionASTNodes.concat(schemaExtensions)
|
||||
: schemaExtensions
|
||||
: schema.extensionASTNodes;
|
||||
|
||||
const types = [
|
||||
// Iterate through all types, getting the type definition for each, ensuring
|
||||
// that any type not directly referenced by a field will get created.
|
||||
...objectValues(schema.getTypeMap()).map(type => extendNamedType(type)),
|
||||
// Do the same with new types.
|
||||
...objectValues(typeDefinitionMap).map(type => astBuilder.buildType(type)),
|
||||
];
|
||||
|
||||
// Support both original legacy names and extended legacy names.
|
||||
const allowedLegacyNames = schema.__allowedLegacyNames.concat(
|
||||
(options && options.allowedLegacyNames) || [],
|
||||
);
|
||||
|
||||
// Then produce and return a Schema with these types.
|
||||
return new GraphQLSchema({
|
||||
...operationTypes,
|
||||
types,
|
||||
directives: getMergedDirectives(),
|
||||
astNode: schema.astNode,
|
||||
extensionASTNodes: schemaExtensionASTNodes,
|
||||
allowedLegacyNames,
|
||||
});
|
||||
|
||||
// Below are functions used for producing this schema that have closed over
|
||||
// this scope and have access to the schema, cache, and newly defined types.
|
||||
|
||||
function getMergedDirectives(): Array<GraphQLDirective> {
|
||||
const existingDirectives = schema.getDirectives().map(extendDirective);
|
||||
invariant(existingDirectives, 'schema must have default directives');
|
||||
|
||||
return existingDirectives.concat(
|
||||
directiveDefinitions.map(node => astBuilder.buildDirective(node)),
|
||||
);
|
||||
}
|
||||
|
||||
function extendMaybeNamedType<T: GraphQLNamedType>(type: ?T): ?T {
|
||||
return type ? extendNamedType(type) : null;
|
||||
}
|
||||
|
||||
function extendNamedType<T: GraphQLNamedType>(type: T): T {
|
||||
if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {
|
||||
// Builtin types are not extended.
|
||||
return type;
|
||||
}
|
||||
|
||||
const name = type.name;
|
||||
if (!extendTypeCache[name]) {
|
||||
if (isScalarType(type)) {
|
||||
extendTypeCache[name] = extendScalarType(type);
|
||||
} else if (isObjectType(type)) {
|
||||
extendTypeCache[name] = extendObjectType(type);
|
||||
} else if (isInterfaceType(type)) {
|
||||
extendTypeCache[name] = extendInterfaceType(type);
|
||||
} else if (isUnionType(type)) {
|
||||
extendTypeCache[name] = extendUnionType(type);
|
||||
} else if (isEnumType(type)) {
|
||||
extendTypeCache[name] = extendEnumType(type);
|
||||
} else if (isInputObjectType(type)) {
|
||||
extendTypeCache[name] = extendInputObjectType(type);
|
||||
}
|
||||
}
|
||||
return (extendTypeCache[name]: any);
|
||||
}
|
||||
|
||||
function extendDirective(directive: GraphQLDirective): GraphQLDirective {
|
||||
return new GraphQLDirective({
|
||||
name: directive.name,
|
||||
description: directive.description,
|
||||
locations: directive.locations,
|
||||
args: extendArgs(directive.args),
|
||||
astNode: directive.astNode,
|
||||
});
|
||||
}
|
||||
|
||||
function extendInputObjectType(
|
||||
type: GraphQLInputObjectType,
|
||||
): GraphQLInputObjectType {
|
||||
const name = type.name;
|
||||
const extensionASTNodes = typeExtensionsMap[name]
|
||||
? type.extensionASTNodes
|
||||
? type.extensionASTNodes.concat(typeExtensionsMap[name])
|
||||
: typeExtensionsMap[name]
|
||||
: type.extensionASTNodes;
|
||||
return new GraphQLInputObjectType({
|
||||
name,
|
||||
description: type.description,
|
||||
fields: () => extendInputFieldMap(type),
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes,
|
||||
});
|
||||
}
|
||||
|
||||
function extendInputFieldMap(type: GraphQLInputObjectType) {
|
||||
const newFieldMap = Object.create(null);
|
||||
const oldFieldMap = type.getFields();
|
||||
for (const fieldName of Object.keys(oldFieldMap)) {
|
||||
const field = oldFieldMap[fieldName];
|
||||
newFieldMap[fieldName] = {
|
||||
description: field.description,
|
||||
type: extendType(field.type),
|
||||
defaultValue: field.defaultValue,
|
||||
astNode: field.astNode,
|
||||
};
|
||||
}
|
||||
|
||||
// If there are any extensions to the fields, apply those here.
|
||||
const extensions = typeExtensionsMap[type.name];
|
||||
if (extensions) {
|
||||
for (const extension of extensions) {
|
||||
for (const field of extension.fields) {
|
||||
const fieldName = field.name.value;
|
||||
if (oldFieldMap[fieldName]) {
|
||||
throw new GraphQLError(
|
||||
`Field "${type.name}.${fieldName}" already exists in the ` +
|
||||
'schema. It cannot also be defined in this type extension.',
|
||||
[field],
|
||||
);
|
||||
}
|
||||
newFieldMap[fieldName] = astBuilder.buildInputField(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newFieldMap;
|
||||
}
|
||||
|
||||
function extendEnumType(type: GraphQLEnumType): GraphQLEnumType {
|
||||
const name = type.name;
|
||||
const extensionASTNodes = typeExtensionsMap[name]
|
||||
? type.extensionASTNodes
|
||||
? type.extensionASTNodes.concat(typeExtensionsMap[name])
|
||||
: typeExtensionsMap[name]
|
||||
: type.extensionASTNodes;
|
||||
return new GraphQLEnumType({
|
||||
name,
|
||||
description: type.description,
|
||||
values: extendValueMap(type),
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes,
|
||||
});
|
||||
}
|
||||
|
||||
function extendValueMap(type: GraphQLEnumType) {
|
||||
const newValueMap = Object.create(null);
|
||||
const oldValueMap = keyMap(type.getValues(), value => value.name);
|
||||
for (const valueName of Object.keys(oldValueMap)) {
|
||||
const value = oldValueMap[valueName];
|
||||
newValueMap[valueName] = {
|
||||
name: value.name,
|
||||
description: value.description,
|
||||
value: value.value,
|
||||
deprecationReason: value.deprecationReason,
|
||||
astNode: value.astNode,
|
||||
};
|
||||
}
|
||||
|
||||
// If there are any extensions to the values, apply those here.
|
||||
const extensions = typeExtensionsMap[type.name];
|
||||
if (extensions) {
|
||||
for (const extension of extensions) {
|
||||
for (const value of extension.values) {
|
||||
const valueName = value.name.value;
|
||||
if (oldValueMap[valueName]) {
|
||||
throw new GraphQLError(
|
||||
`Enum value "${type.name}.${valueName}" already exists in the ` +
|
||||
'schema. It cannot also be defined in this type extension.',
|
||||
[value],
|
||||
);
|
||||
}
|
||||
newValueMap[valueName] = astBuilder.buildEnumValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newValueMap;
|
||||
}
|
||||
|
||||
function extendScalarType(type: GraphQLScalarType): GraphQLScalarType {
|
||||
const name = type.name;
|
||||
const extensionASTNodes = typeExtensionsMap[name]
|
||||
? type.extensionASTNodes
|
||||
? type.extensionASTNodes.concat(typeExtensionsMap[name])
|
||||
: typeExtensionsMap[name]
|
||||
: type.extensionASTNodes;
|
||||
return new GraphQLScalarType({
|
||||
name,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes,
|
||||
serialize: type.serialize,
|
||||
parseValue: type.parseValue,
|
||||
parseLiteral: type.parseLiteral,
|
||||
});
|
||||
}
|
||||
|
||||
function extendObjectType(type: GraphQLObjectType): GraphQLObjectType {
|
||||
const name = type.name;
|
||||
const extensionASTNodes = typeExtensionsMap[name]
|
||||
? type.extensionASTNodes
|
||||
? type.extensionASTNodes.concat(typeExtensionsMap[name])
|
||||
: typeExtensionsMap[name]
|
||||
: type.extensionASTNodes;
|
||||
return new GraphQLObjectType({
|
||||
name,
|
||||
description: type.description,
|
||||
interfaces: () => extendImplementedInterfaces(type),
|
||||
fields: () => extendFieldMap(type),
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes,
|
||||
isTypeOf: type.isTypeOf,
|
||||
});
|
||||
}
|
||||
|
||||
function extendArgs(
|
||||
args: Array<GraphQLArgument>,
|
||||
): GraphQLFieldConfigArgumentMap {
|
||||
return keyValMap(
|
||||
args,
|
||||
arg => arg.name,
|
||||
arg => ({
|
||||
type: extendType(arg.type),
|
||||
defaultValue: arg.defaultValue,
|
||||
description: arg.description,
|
||||
astNode: arg.astNode,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function extendInterfaceType(
|
||||
type: GraphQLInterfaceType,
|
||||
): GraphQLInterfaceType {
|
||||
const name = type.name;
|
||||
const extensionASTNodes = typeExtensionsMap[name]
|
||||
? type.extensionASTNodes
|
||||
? type.extensionASTNodes.concat(typeExtensionsMap[name])
|
||||
: typeExtensionsMap[name]
|
||||
: type.extensionASTNodes;
|
||||
return new GraphQLInterfaceType({
|
||||
name: type.name,
|
||||
description: type.description,
|
||||
fields: () => extendFieldMap(type),
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes,
|
||||
resolveType: type.resolveType,
|
||||
});
|
||||
}
|
||||
|
||||
function extendUnionType(type: GraphQLUnionType): GraphQLUnionType {
|
||||
const name = type.name;
|
||||
const extensionASTNodes = typeExtensionsMap[name]
|
||||
? type.extensionASTNodes
|
||||
? type.extensionASTNodes.concat(typeExtensionsMap[name])
|
||||
: typeExtensionsMap[name]
|
||||
: type.extensionASTNodes;
|
||||
return new GraphQLUnionType({
|
||||
name,
|
||||
description: type.description,
|
||||
types: () => extendPossibleTypes(type),
|
||||
astNode: type.astNode,
|
||||
resolveType: type.resolveType,
|
||||
extensionASTNodes,
|
||||
});
|
||||
}
|
||||
|
||||
function extendPossibleTypes(
|
||||
type: GraphQLUnionType,
|
||||
): Array<GraphQLObjectType> {
|
||||
const possibleTypes = type.getTypes().map(extendNamedType);
|
||||
|
||||
// If there are any extensions to the union, apply those here.
|
||||
const extensions = typeExtensionsMap[type.name];
|
||||
if (extensions) {
|
||||
for (const extension of extensions) {
|
||||
for (const namedType of extension.types) {
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
possibleTypes.push((astBuilder.buildType(namedType): any));
|
||||
}
|
||||
}
|
||||
}
|
||||
return possibleTypes;
|
||||
}
|
||||
|
||||
function extendImplementedInterfaces(
|
||||
type: GraphQLObjectType,
|
||||
): Array<GraphQLInterfaceType> {
|
||||
const interfaces = type.getInterfaces().map(extendNamedType);
|
||||
|
||||
// If there are any extensions to the interfaces, apply those here.
|
||||
const extensions = typeExtensionsMap[type.name];
|
||||
if (extensions) {
|
||||
for (const extension of extensions) {
|
||||
for (const namedType of extension.interfaces) {
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
interfaces.push((astBuilder.buildType(namedType): any));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return interfaces;
|
||||
}
|
||||
|
||||
function extendFieldMap(type: GraphQLObjectType | GraphQLInterfaceType) {
|
||||
const newFieldMap = Object.create(null);
|
||||
const oldFieldMap = type.getFields();
|
||||
for (const fieldName of Object.keys(oldFieldMap)) {
|
||||
const field = oldFieldMap[fieldName];
|
||||
newFieldMap[fieldName] = {
|
||||
description: field.description,
|
||||
deprecationReason: field.deprecationReason,
|
||||
type: extendType(field.type),
|
||||
args: extendArgs(field.args),
|
||||
astNode: field.astNode,
|
||||
resolve: field.resolve,
|
||||
};
|
||||
}
|
||||
|
||||
// If there are any extensions to the fields, apply those here.
|
||||
const extensions = typeExtensionsMap[type.name];
|
||||
if (extensions) {
|
||||
for (const extension of extensions) {
|
||||
for (const field of extension.fields) {
|
||||
const fieldName = field.name.value;
|
||||
if (oldFieldMap[fieldName]) {
|
||||
throw new GraphQLError(
|
||||
`Field "${type.name}.${fieldName}" already exists in the ` +
|
||||
'schema. It cannot also be defined in this type extension.',
|
||||
[field],
|
||||
);
|
||||
}
|
||||
newFieldMap[fieldName] = astBuilder.buildField(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newFieldMap;
|
||||
}
|
||||
|
||||
function extendType<T: GraphQLType>(typeDef: T): T {
|
||||
if (isListType(typeDef)) {
|
||||
return (GraphQLList(extendType(typeDef.ofType)): any);
|
||||
}
|
||||
if (isNonNullType(typeDef)) {
|
||||
return (GraphQLNonNull(extendType(typeDef.ofType)): any);
|
||||
}
|
||||
return extendNamedType(typeDef);
|
||||
}
|
||||
}
|
||||
|
||||
function checkExtensionNode(type, node) {
|
||||
switch (node.kind) {
|
||||
case Kind.OBJECT_TYPE_EXTENSION:
|
||||
if (!isObjectType(type)) {
|
||||
throw new GraphQLError(
|
||||
`Cannot extend non-object type "${type.name}".`,
|
||||
[node],
|
||||
);
|
||||
}
|
||||
break;
|
||||
case Kind.INTERFACE_TYPE_EXTENSION:
|
||||
if (!isInterfaceType(type)) {
|
||||
throw new GraphQLError(
|
||||
`Cannot extend non-interface type "${type.name}".`,
|
||||
[node],
|
||||
);
|
||||
}
|
||||
break;
|
||||
case Kind.ENUM_TYPE_EXTENSION:
|
||||
if (!isEnumType(type)) {
|
||||
throw new GraphQLError(`Cannot extend non-enum type "${type.name}".`, [
|
||||
node,
|
||||
]);
|
||||
}
|
||||
break;
|
||||
case Kind.UNION_TYPE_EXTENSION:
|
||||
if (!isUnionType(type)) {
|
||||
throw new GraphQLError(`Cannot extend non-union type "${type.name}".`, [
|
||||
node,
|
||||
]);
|
||||
}
|
||||
break;
|
||||
case Kind.INPUT_OBJECT_TYPE_EXTENSION:
|
||||
if (!isInputObjectType(type)) {
|
||||
throw new GraphQLError(
|
||||
`Cannot extend non-input object type "${type.name}".`,
|
||||
[node],
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
+780
@@ -0,0 +1,780 @@
|
||||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
|
||||
|
||||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import invariant from '../jsutils/invariant';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import { ASTDefinitionBuilder } from './buildASTSchema';
|
||||
import { assertValidSDLExtension } from '../validation/validate';
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import { isSchema, GraphQLSchema } from '../type/schema';
|
||||
import { isIntrospectionType } from '../type/introspection';
|
||||
import { isSpecifiedScalarType } from '../type/scalars';
|
||||
import { isScalarType, isObjectType, isInterfaceType, isUnionType, isListType, isNonNullType, isEnumType, isInputObjectType, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType } from '../type/definition';
|
||||
import { GraphQLDirective } from '../type/directives';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { isTypeDefinitionNode, isTypeExtensionNode } from '../language/predicates';
|
||||
|
||||
/**
|
||||
* Produces a new schema given an existing schema and a document which may
|
||||
* contain GraphQL type extensions and definitions. The original schema will
|
||||
* remain unaltered.
|
||||
*
|
||||
* Because a schema represents a graph of references, a schema cannot be
|
||||
* extended without effectively making an entire copy. We do not know until it's
|
||||
* too late if subgraphs remain unchanged.
|
||||
*
|
||||
* This algorithm copies the provided schema, applying extensions while
|
||||
* producing the copy. The original schema remains unaltered.
|
||||
*
|
||||
* Accepts options as a third argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
export function extendSchema(schema, documentAST, options) {
|
||||
!isSchema(schema) ? invariant(0, 'Must provide valid GraphQLSchema') : void 0;
|
||||
!(documentAST && documentAST.kind === Kind.DOCUMENT) ? invariant(0, 'Must provide valid Document AST') : void 0;
|
||||
|
||||
if (!options || !(options.assumeValid || options.assumeValidSDL)) {
|
||||
assertValidSDLExtension(documentAST, schema);
|
||||
} // Collect the type definitions and extensions found in the document.
|
||||
|
||||
|
||||
var typeDefinitionMap = Object.create(null);
|
||||
var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can
|
||||
// have the same name. For example, a type named "skip".
|
||||
|
||||
var directiveDefinitions = [];
|
||||
var schemaDef; // Schema extensions are collected which may add additional operation types.
|
||||
|
||||
var schemaExtensions = [];
|
||||
|
||||
for (var i = 0; i < documentAST.definitions.length; i++) {
|
||||
var def = documentAST.definitions[i];
|
||||
|
||||
if (def.kind === Kind.SCHEMA_DEFINITION) {
|
||||
schemaDef = def;
|
||||
} else if (def.kind === Kind.SCHEMA_EXTENSION) {
|
||||
schemaExtensions.push(def);
|
||||
} else if (isTypeDefinitionNode(def)) {
|
||||
// Sanity check that none of the defined types conflict with the
|
||||
// schema's existing types.
|
||||
var typeName = def.name.value;
|
||||
|
||||
if (schema.getType(typeName)) {
|
||||
throw new GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also ") + 'be defined in this type definition.', [def]);
|
||||
}
|
||||
|
||||
typeDefinitionMap[typeName] = def;
|
||||
} else if (isTypeExtensionNode(def)) {
|
||||
// Sanity check that this type extension exists within the
|
||||
// schema's existing types.
|
||||
var extendedTypeName = def.name.value;
|
||||
var existingType = schema.getType(extendedTypeName);
|
||||
|
||||
if (!existingType) {
|
||||
throw new GraphQLError("Cannot extend type \"".concat(extendedTypeName, "\" because it does not ") + 'exist in the existing schema.', [def]);
|
||||
}
|
||||
|
||||
checkExtensionNode(existingType, def);
|
||||
var existingTypeExtensions = typeExtensionsMap[extendedTypeName];
|
||||
typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def];
|
||||
} else if (def.kind === Kind.DIRECTIVE_DEFINITION) {
|
||||
var directiveName = def.name.value;
|
||||
var existingDirective = schema.getDirective(directiveName);
|
||||
|
||||
if (existingDirective) {
|
||||
throw new GraphQLError("Directive \"".concat(directiveName, "\" already exists in the schema. It ") + 'cannot be redefined.', [def]);
|
||||
}
|
||||
|
||||
directiveDefinitions.push(def);
|
||||
}
|
||||
} // If this document contains no new types, extensions, or directives then
|
||||
// return the same unmodified GraphQLSchema instance.
|
||||
|
||||
|
||||
if (Object.keys(typeExtensionsMap).length === 0 && Object.keys(typeDefinitionMap).length === 0 && directiveDefinitions.length === 0 && schemaExtensions.length === 0 && !schemaDef) {
|
||||
return schema;
|
||||
}
|
||||
|
||||
var astBuilder = new ASTDefinitionBuilder(typeDefinitionMap, options, function (typeRef) {
|
||||
var typeName = typeRef.name.value;
|
||||
var existingType = schema.getType(typeName);
|
||||
|
||||
if (existingType) {
|
||||
return extendNamedType(existingType);
|
||||
}
|
||||
|
||||
throw new GraphQLError("Unknown type: \"".concat(typeName, "\". Ensure that this type exists ") + 'either in the original schema, or is added in a type definition.', [typeRef]);
|
||||
});
|
||||
var extendTypeCache = Object.create(null); // Get the extended root operation types.
|
||||
|
||||
var operationTypes = {
|
||||
query: extendMaybeNamedType(schema.getQueryType()),
|
||||
mutation: extendMaybeNamedType(schema.getMutationType()),
|
||||
subscription: extendMaybeNamedType(schema.getSubscriptionType())
|
||||
};
|
||||
|
||||
if (schemaDef) {
|
||||
var _iteratorNormalCompletion = true;
|
||||
var _didIteratorError = false;
|
||||
var _iteratorError = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator = schemaDef.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
|
||||
var _ref2 = _step.value;
|
||||
var operation = _ref2.operation,
|
||||
type = _ref2.type;
|
||||
|
||||
if (operationTypes[operation]) {
|
||||
throw new Error("Must provide only one ".concat(operation, " type in schema."));
|
||||
} // Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
|
||||
|
||||
operationTypes[operation] = astBuilder.buildType(type);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError = true;
|
||||
_iteratorError = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion && _iterator.return != null) {
|
||||
_iterator.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError) {
|
||||
throw _iteratorError;
|
||||
}
|
||||
}
|
||||
}
|
||||
} // Then, incorporate schema definition and all schema extensions.
|
||||
|
||||
|
||||
for (var _i = 0; _i < schemaExtensions.length; _i++) {
|
||||
var schemaExtension = schemaExtensions[_i];
|
||||
|
||||
if (schemaExtension.operationTypes) {
|
||||
var _iteratorNormalCompletion12 = true;
|
||||
var _didIteratorError12 = false;
|
||||
var _iteratorError12 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator12 = schemaExtension.operationTypes[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
|
||||
var _ref4 = _step12.value;
|
||||
var operation = _ref4.operation,
|
||||
type = _ref4.type;
|
||||
|
||||
if (operationTypes[operation]) {
|
||||
throw new Error("Must provide only one ".concat(operation, " type in schema."));
|
||||
} // Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
|
||||
|
||||
operationTypes[operation] = astBuilder.buildType(type);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError12 = true;
|
||||
_iteratorError12 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion12 && _iterator12.return != null) {
|
||||
_iterator12.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError12) {
|
||||
throw _iteratorError12;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var schemaExtensionASTNodes = schemaExtensions ? schema.extensionASTNodes ? schema.extensionASTNodes.concat(schemaExtensions) : schemaExtensions : schema.extensionASTNodes;
|
||||
var types = objectValues(schema.getTypeMap()).map(function (type) {
|
||||
return extendNamedType(type);
|
||||
}).concat(objectValues(typeDefinitionMap).map(function (type) {
|
||||
return astBuilder.buildType(type);
|
||||
})); // Support both original legacy names and extended legacy names.
|
||||
|
||||
var allowedLegacyNames = schema.__allowedLegacyNames.concat(options && options.allowedLegacyNames || []); // Then produce and return a Schema with these types.
|
||||
|
||||
|
||||
return new GraphQLSchema(_objectSpread({}, operationTypes, {
|
||||
types: types,
|
||||
directives: getMergedDirectives(),
|
||||
astNode: schema.astNode,
|
||||
extensionASTNodes: schemaExtensionASTNodes,
|
||||
allowedLegacyNames: allowedLegacyNames
|
||||
})); // Below are functions used for producing this schema that have closed over
|
||||
// this scope and have access to the schema, cache, and newly defined types.
|
||||
|
||||
function getMergedDirectives() {
|
||||
var existingDirectives = schema.getDirectives().map(extendDirective);
|
||||
!existingDirectives ? invariant(0, 'schema must have default directives') : void 0;
|
||||
return existingDirectives.concat(directiveDefinitions.map(function (node) {
|
||||
return astBuilder.buildDirective(node);
|
||||
}));
|
||||
}
|
||||
|
||||
function extendMaybeNamedType(type) {
|
||||
return type ? extendNamedType(type) : null;
|
||||
}
|
||||
|
||||
function extendNamedType(type) {
|
||||
if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {
|
||||
// Builtin types are not extended.
|
||||
return type;
|
||||
}
|
||||
|
||||
var name = type.name;
|
||||
|
||||
if (!extendTypeCache[name]) {
|
||||
if (isScalarType(type)) {
|
||||
extendTypeCache[name] = extendScalarType(type);
|
||||
} else if (isObjectType(type)) {
|
||||
extendTypeCache[name] = extendObjectType(type);
|
||||
} else if (isInterfaceType(type)) {
|
||||
extendTypeCache[name] = extendInterfaceType(type);
|
||||
} else if (isUnionType(type)) {
|
||||
extendTypeCache[name] = extendUnionType(type);
|
||||
} else if (isEnumType(type)) {
|
||||
extendTypeCache[name] = extendEnumType(type);
|
||||
} else if (isInputObjectType(type)) {
|
||||
extendTypeCache[name] = extendInputObjectType(type);
|
||||
}
|
||||
}
|
||||
|
||||
return extendTypeCache[name];
|
||||
}
|
||||
|
||||
function extendDirective(directive) {
|
||||
return new GraphQLDirective({
|
||||
name: directive.name,
|
||||
description: directive.description,
|
||||
locations: directive.locations,
|
||||
args: extendArgs(directive.args),
|
||||
astNode: directive.astNode
|
||||
});
|
||||
}
|
||||
|
||||
function extendInputObjectType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new GraphQLInputObjectType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
fields: function fields() {
|
||||
return extendInputFieldMap(type);
|
||||
},
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes
|
||||
});
|
||||
}
|
||||
|
||||
function extendInputFieldMap(type) {
|
||||
var newFieldMap = Object.create(null);
|
||||
var oldFieldMap = type.getFields();
|
||||
|
||||
var _arr = Object.keys(oldFieldMap);
|
||||
|
||||
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
|
||||
var _fieldName = _arr[_i2];
|
||||
var _field = oldFieldMap[_fieldName];
|
||||
newFieldMap[_fieldName] = {
|
||||
description: _field.description,
|
||||
type: extendType(_field.type),
|
||||
defaultValue: _field.defaultValue,
|
||||
astNode: _field.astNode
|
||||
};
|
||||
} // If there are any extensions to the fields, apply those here.
|
||||
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion2 = true;
|
||||
var _didIteratorError2 = false;
|
||||
var _iteratorError2 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator2 = extensions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
|
||||
var extension = _step2.value;
|
||||
var _iteratorNormalCompletion3 = true;
|
||||
var _didIteratorError3 = false;
|
||||
var _iteratorError3 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator3 = extension.fields[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
|
||||
var field = _step3.value;
|
||||
var fieldName = field.name.value;
|
||||
|
||||
if (oldFieldMap[fieldName]) {
|
||||
throw new GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]);
|
||||
}
|
||||
|
||||
newFieldMap[fieldName] = astBuilder.buildInputField(field);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError3 = true;
|
||||
_iteratorError3 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
|
||||
_iterator3.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError3) {
|
||||
throw _iteratorError3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError2 = true;
|
||||
_iteratorError2 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
|
||||
_iterator2.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError2) {
|
||||
throw _iteratorError2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newFieldMap;
|
||||
}
|
||||
|
||||
function extendEnumType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new GraphQLEnumType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
values: extendValueMap(type),
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes
|
||||
});
|
||||
}
|
||||
|
||||
function extendValueMap(type) {
|
||||
var newValueMap = Object.create(null);
|
||||
var oldValueMap = keyMap(type.getValues(), function (value) {
|
||||
return value.name;
|
||||
});
|
||||
|
||||
var _arr2 = Object.keys(oldValueMap);
|
||||
|
||||
for (var _i3 = 0; _i3 < _arr2.length; _i3++) {
|
||||
var _valueName = _arr2[_i3];
|
||||
var _value = oldValueMap[_valueName];
|
||||
newValueMap[_valueName] = {
|
||||
name: _value.name,
|
||||
description: _value.description,
|
||||
value: _value.value,
|
||||
deprecationReason: _value.deprecationReason,
|
||||
astNode: _value.astNode
|
||||
};
|
||||
} // If there are any extensions to the values, apply those here.
|
||||
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion4 = true;
|
||||
var _didIteratorError4 = false;
|
||||
var _iteratorError4 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator4 = extensions[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
|
||||
var extension = _step4.value;
|
||||
var _iteratorNormalCompletion5 = true;
|
||||
var _didIteratorError5 = false;
|
||||
var _iteratorError5 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator5 = extension.values[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
|
||||
var value = _step5.value;
|
||||
var valueName = value.name.value;
|
||||
|
||||
if (oldValueMap[valueName]) {
|
||||
throw new GraphQLError("Enum value \"".concat(type.name, ".").concat(valueName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [value]);
|
||||
}
|
||||
|
||||
newValueMap[valueName] = astBuilder.buildEnumValue(value);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError5 = true;
|
||||
_iteratorError5 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
|
||||
_iterator5.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError5) {
|
||||
throw _iteratorError5;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError4 = true;
|
||||
_iteratorError4 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
|
||||
_iterator4.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError4) {
|
||||
throw _iteratorError4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newValueMap;
|
||||
}
|
||||
|
||||
function extendScalarType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new GraphQLScalarType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes,
|
||||
serialize: type.serialize,
|
||||
parseValue: type.parseValue,
|
||||
parseLiteral: type.parseLiteral
|
||||
});
|
||||
}
|
||||
|
||||
function extendObjectType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new GraphQLObjectType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
interfaces: function interfaces() {
|
||||
return extendImplementedInterfaces(type);
|
||||
},
|
||||
fields: function fields() {
|
||||
return extendFieldMap(type);
|
||||
},
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes,
|
||||
isTypeOf: type.isTypeOf
|
||||
});
|
||||
}
|
||||
|
||||
function extendArgs(args) {
|
||||
return keyValMap(args, function (arg) {
|
||||
return arg.name;
|
||||
}, function (arg) {
|
||||
return {
|
||||
type: extendType(arg.type),
|
||||
defaultValue: arg.defaultValue,
|
||||
description: arg.description,
|
||||
astNode: arg.astNode
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function extendInterfaceType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new GraphQLInterfaceType({
|
||||
name: type.name,
|
||||
description: type.description,
|
||||
fields: function fields() {
|
||||
return extendFieldMap(type);
|
||||
},
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: extensionASTNodes,
|
||||
resolveType: type.resolveType
|
||||
});
|
||||
}
|
||||
|
||||
function extendUnionType(type) {
|
||||
var name = type.name;
|
||||
var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes;
|
||||
return new GraphQLUnionType({
|
||||
name: name,
|
||||
description: type.description,
|
||||
types: function types() {
|
||||
return extendPossibleTypes(type);
|
||||
},
|
||||
astNode: type.astNode,
|
||||
resolveType: type.resolveType,
|
||||
extensionASTNodes: extensionASTNodes
|
||||
});
|
||||
}
|
||||
|
||||
function extendPossibleTypes(type) {
|
||||
var possibleTypes = type.getTypes().map(extendNamedType); // If there are any extensions to the union, apply those here.
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion6 = true;
|
||||
var _didIteratorError6 = false;
|
||||
var _iteratorError6 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator6 = extensions[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
|
||||
var extension = _step6.value;
|
||||
var _iteratorNormalCompletion7 = true;
|
||||
var _didIteratorError7 = false;
|
||||
var _iteratorError7 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator7 = extension.types[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
|
||||
var namedType = _step7.value;
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
possibleTypes.push(astBuilder.buildType(namedType));
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError7 = true;
|
||||
_iteratorError7 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
|
||||
_iterator7.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError7) {
|
||||
throw _iteratorError7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError6 = true;
|
||||
_iteratorError6 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
|
||||
_iterator6.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError6) {
|
||||
throw _iteratorError6;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return possibleTypes;
|
||||
}
|
||||
|
||||
function extendImplementedInterfaces(type) {
|
||||
var interfaces = type.getInterfaces().map(extendNamedType); // If there are any extensions to the interfaces, apply those here.
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion8 = true;
|
||||
var _didIteratorError8 = false;
|
||||
var _iteratorError8 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator8 = extensions[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
|
||||
var extension = _step8.value;
|
||||
var _iteratorNormalCompletion9 = true;
|
||||
var _didIteratorError9 = false;
|
||||
var _iteratorError9 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator9 = extension.interfaces[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
|
||||
var namedType = _step9.value;
|
||||
// Note: While this could make early assertions to get the correctly
|
||||
// typed values, that would throw immediately while type system
|
||||
// validation with validateSchema() will produce more actionable results.
|
||||
interfaces.push(astBuilder.buildType(namedType));
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError9 = true;
|
||||
_iteratorError9 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
|
||||
_iterator9.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError9) {
|
||||
throw _iteratorError9;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError8 = true;
|
||||
_iteratorError8 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
|
||||
_iterator8.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError8) {
|
||||
throw _iteratorError8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return interfaces;
|
||||
}
|
||||
|
||||
function extendFieldMap(type) {
|
||||
var newFieldMap = Object.create(null);
|
||||
var oldFieldMap = type.getFields();
|
||||
|
||||
var _arr3 = Object.keys(oldFieldMap);
|
||||
|
||||
for (var _i4 = 0; _i4 < _arr3.length; _i4++) {
|
||||
var _fieldName2 = _arr3[_i4];
|
||||
var _field2 = oldFieldMap[_fieldName2];
|
||||
newFieldMap[_fieldName2] = {
|
||||
description: _field2.description,
|
||||
deprecationReason: _field2.deprecationReason,
|
||||
type: extendType(_field2.type),
|
||||
args: extendArgs(_field2.args),
|
||||
astNode: _field2.astNode,
|
||||
resolve: _field2.resolve
|
||||
};
|
||||
} // If there are any extensions to the fields, apply those here.
|
||||
|
||||
|
||||
var extensions = typeExtensionsMap[type.name];
|
||||
|
||||
if (extensions) {
|
||||
var _iteratorNormalCompletion10 = true;
|
||||
var _didIteratorError10 = false;
|
||||
var _iteratorError10 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator10 = extensions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
|
||||
var extension = _step10.value;
|
||||
var _iteratorNormalCompletion11 = true;
|
||||
var _didIteratorError11 = false;
|
||||
var _iteratorError11 = undefined;
|
||||
|
||||
try {
|
||||
for (var _iterator11 = extension.fields[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
|
||||
var field = _step11.value;
|
||||
var fieldName = field.name.value;
|
||||
|
||||
if (oldFieldMap[fieldName]) {
|
||||
throw new GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]);
|
||||
}
|
||||
|
||||
newFieldMap[fieldName] = astBuilder.buildField(field);
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError11 = true;
|
||||
_iteratorError11 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion11 && _iterator11.return != null) {
|
||||
_iterator11.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError11) {
|
||||
throw _iteratorError11;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_didIteratorError10 = true;
|
||||
_iteratorError10 = err;
|
||||
} finally {
|
||||
try {
|
||||
if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
|
||||
_iterator10.return();
|
||||
}
|
||||
} finally {
|
||||
if (_didIteratorError10) {
|
||||
throw _iteratorError10;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newFieldMap;
|
||||
}
|
||||
|
||||
function extendType(typeDef) {
|
||||
if (isListType(typeDef)) {
|
||||
return GraphQLList(extendType(typeDef.ofType));
|
||||
}
|
||||
|
||||
if (isNonNullType(typeDef)) {
|
||||
return GraphQLNonNull(extendType(typeDef.ofType));
|
||||
}
|
||||
|
||||
return extendNamedType(typeDef);
|
||||
}
|
||||
}
|
||||
|
||||
function checkExtensionNode(type, node) {
|
||||
switch (node.kind) {
|
||||
case Kind.OBJECT_TYPE_EXTENSION:
|
||||
if (!isObjectType(type)) {
|
||||
throw new GraphQLError("Cannot extend non-object type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case Kind.INTERFACE_TYPE_EXTENSION:
|
||||
if (!isInterfaceType(type)) {
|
||||
throw new GraphQLError("Cannot extend non-interface type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case Kind.ENUM_TYPE_EXTENSION:
|
||||
if (!isEnumType(type)) {
|
||||
throw new GraphQLError("Cannot extend non-enum type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case Kind.UNION_TYPE_EXTENSION:
|
||||
if (!isUnionType(type)) {
|
||||
throw new GraphQLError("Cannot extend non-union type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case Kind.INPUT_OBJECT_TYPE_EXTENSION:
|
||||
if (!isInputObjectType(type)) {
|
||||
throw new GraphQLError("Cannot extend non-input object type \"".concat(type.name, "\"."), [node]);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
+1245
File diff suppressed because it is too large.
Load diff
+853
@@ -0,0 +1,853 @@
|
||||
/**
|
||||
* Copyright (c) 2016-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import {
|
||||
isScalarType,
|
||||
isObjectType,
|
||||
isInterfaceType,
|
||||
isUnionType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
isNonNullType,
|
||||
isListType,
|
||||
isNamedType,
|
||||
isRequiredArgument,
|
||||
isRequiredInputField,
|
||||
} from '../type/definition';
|
||||
|
||||
import type {
|
||||
GraphQLNamedType,
|
||||
GraphQLFieldMap,
|
||||
GraphQLType,
|
||||
GraphQLArgument,
|
||||
} from '../type/definition';
|
||||
|
||||
import type { GraphQLDirective } from '../type/directives';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
|
||||
import type { ObjMap } from '../jsutils/ObjMap';
|
||||
import type { DirectiveLocationEnum } from '../language/directiveLocation';
|
||||
|
||||
export const BreakingChangeType = {
|
||||
FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND',
|
||||
FIELD_REMOVED: 'FIELD_REMOVED',
|
||||
TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND',
|
||||
TYPE_REMOVED: 'TYPE_REMOVED',
|
||||
TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION',
|
||||
VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM',
|
||||
ARG_REMOVED: 'ARG_REMOVED',
|
||||
ARG_CHANGED_KIND: 'ARG_CHANGED_KIND',
|
||||
REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED',
|
||||
REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED',
|
||||
INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT',
|
||||
DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED',
|
||||
DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED',
|
||||
DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED',
|
||||
REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED',
|
||||
};
|
||||
|
||||
export const DangerousChangeType = {
|
||||
ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE',
|
||||
VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM',
|
||||
INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT',
|
||||
TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION',
|
||||
OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED',
|
||||
OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED',
|
||||
};
|
||||
|
||||
export type BreakingChange = {
|
||||
type: $Keys<typeof BreakingChangeType>,
|
||||
description: string,
|
||||
};
|
||||
|
||||
export type DangerousChange = {
|
||||
type: $Keys<typeof DangerousChangeType>,
|
||||
description: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of all the types
|
||||
* of breaking changes covered by the other functions down below.
|
||||
*/
|
||||
export function findBreakingChanges(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
return [
|
||||
...findRemovedTypes(oldSchema, newSchema),
|
||||
...findTypesThatChangedKind(oldSchema, newSchema),
|
||||
...findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema),
|
||||
...findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema)
|
||||
.breakingChanges,
|
||||
...findTypesRemovedFromUnions(oldSchema, newSchema),
|
||||
...findValuesRemovedFromEnums(oldSchema, newSchema),
|
||||
...findArgChanges(oldSchema, newSchema).breakingChanges,
|
||||
...findInterfacesRemovedFromObjectTypes(oldSchema, newSchema),
|
||||
...findRemovedDirectives(oldSchema, newSchema),
|
||||
...findRemovedDirectiveArgs(oldSchema, newSchema),
|
||||
...findAddedNonNullDirectiveArgs(oldSchema, newSchema),
|
||||
...findRemovedDirectiveLocations(oldSchema, newSchema),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of all the types
|
||||
* of potentially dangerous changes covered by the other functions down below.
|
||||
*/
|
||||
export function findDangerousChanges(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<DangerousChange> {
|
||||
return [
|
||||
...findArgChanges(oldSchema, newSchema).dangerousChanges,
|
||||
...findValuesAddedToEnums(oldSchema, newSchema),
|
||||
...findInterfacesAddedToObjectTypes(oldSchema, newSchema),
|
||||
...findTypesAddedToUnions(oldSchema, newSchema),
|
||||
...findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema)
|
||||
.dangerousChanges,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of any breaking
|
||||
* changes in the newSchema related to removing an entire type.
|
||||
*/
|
||||
export function findRemovedTypes(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const breakingChanges = [];
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
if (!newTypeMap[typeName]) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.TYPE_REMOVED,
|
||||
description: `${typeName} was removed.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return breakingChanges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of any breaking
|
||||
* changes in the newSchema related to changing the type of a type.
|
||||
*/
|
||||
export function findTypesThatChangedKind(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const breakingChanges = [];
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
if (!newTypeMap[typeName]) {
|
||||
continue;
|
||||
}
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (oldType.constructor !== newType.constructor) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.TYPE_CHANGED_KIND,
|
||||
description:
|
||||
`${typeName} changed from ` +
|
||||
`${typeKindName(oldType)} to ${typeKindName(newType)}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return breakingChanges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of any
|
||||
* breaking or dangerous changes in the newSchema related to arguments
|
||||
* (such as removal or change of type of an argument, or a change in an
|
||||
* argument's default value).
|
||||
*/
|
||||
export function findArgChanges(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): {
|
||||
breakingChanges: Array<BreakingChange>,
|
||||
dangerousChanges: Array<DangerousChange>,
|
||||
} {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const breakingChanges = [];
|
||||
const dangerousChanges = [];
|
||||
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (
|
||||
!(isObjectType(oldType) || isInterfaceType(oldType)) ||
|
||||
!(isObjectType(newType) || isInterfaceType(newType)) ||
|
||||
newType.constructor !== oldType.constructor
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const oldTypeFields: GraphQLFieldMap<*, *> = oldType.getFields();
|
||||
const newTypeFields: GraphQLFieldMap<*, *> = newType.getFields();
|
||||
|
||||
for (const fieldName of Object.keys(oldTypeFields)) {
|
||||
if (!newTypeFields[fieldName]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const oldArgDef of oldTypeFields[fieldName].args) {
|
||||
const newArgs = newTypeFields[fieldName].args;
|
||||
const newArgDef = newArgs.find(arg => arg.name === oldArgDef.name);
|
||||
|
||||
// Arg not present
|
||||
if (!newArgDef) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.ARG_REMOVED,
|
||||
description:
|
||||
`${oldType.name}.${fieldName} arg ` +
|
||||
`${oldArgDef.name} was removed`,
|
||||
});
|
||||
} else {
|
||||
const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(
|
||||
oldArgDef.type,
|
||||
newArgDef.type,
|
||||
);
|
||||
if (!isSafe) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.ARG_CHANGED_KIND,
|
||||
description:
|
||||
`${oldType.name}.${fieldName} arg ` +
|
||||
`${oldArgDef.name} has changed type from ` +
|
||||
`${oldArgDef.type.toString()} to ${newArgDef.type.toString()}`,
|
||||
});
|
||||
} else if (
|
||||
oldArgDef.defaultValue !== undefined &&
|
||||
oldArgDef.defaultValue !== newArgDef.defaultValue
|
||||
) {
|
||||
dangerousChanges.push({
|
||||
type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,
|
||||
description:
|
||||
`${oldType.name}.${fieldName} arg ` +
|
||||
`${oldArgDef.name} has changed defaultValue`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check if arg was added to the field
|
||||
for (const newArgDef of newTypeFields[fieldName].args) {
|
||||
const oldArgs = oldTypeFields[fieldName].args;
|
||||
const oldArgDef = oldArgs.find(arg => arg.name === newArgDef.name);
|
||||
if (!oldArgDef) {
|
||||
const argName = newArgDef.name;
|
||||
if (isRequiredArgument(newArgDef)) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.REQUIRED_ARG_ADDED,
|
||||
description:
|
||||
`A required arg ${argName} on ` +
|
||||
`${typeName}.${fieldName} was added`,
|
||||
});
|
||||
} else {
|
||||
dangerousChanges.push({
|
||||
type: DangerousChangeType.OPTIONAL_ARG_ADDED,
|
||||
description:
|
||||
`An optional arg ${argName} on ` +
|
||||
`${typeName}.${fieldName} was added`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
breakingChanges,
|
||||
dangerousChanges,
|
||||
};
|
||||
}
|
||||
|
||||
function typeKindName(type: GraphQLNamedType): string {
|
||||
if (isScalarType(type)) {
|
||||
return 'a Scalar type';
|
||||
}
|
||||
if (isObjectType(type)) {
|
||||
return 'an Object type';
|
||||
}
|
||||
if (isInterfaceType(type)) {
|
||||
return 'an Interface type';
|
||||
}
|
||||
if (isUnionType(type)) {
|
||||
return 'a Union type';
|
||||
}
|
||||
if (isEnumType(type)) {
|
||||
return 'an Enum type';
|
||||
}
|
||||
if (isInputObjectType(type)) {
|
||||
return 'an Input type';
|
||||
}
|
||||
throw new TypeError('Unknown type ' + type.constructor.name);
|
||||
}
|
||||
|
||||
export function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const breakingChanges = [];
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (
|
||||
!(isObjectType(oldType) || isInterfaceType(oldType)) ||
|
||||
!(isObjectType(newType) || isInterfaceType(newType)) ||
|
||||
newType.constructor !== oldType.constructor
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const oldTypeFieldsDef = oldType.getFields();
|
||||
const newTypeFieldsDef = newType.getFields();
|
||||
for (const fieldName of Object.keys(oldTypeFieldsDef)) {
|
||||
// Check if the field is missing on the type in the new schema.
|
||||
if (!(fieldName in newTypeFieldsDef)) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.FIELD_REMOVED,
|
||||
description: `${typeName}.${fieldName} was removed.`,
|
||||
});
|
||||
} else {
|
||||
const oldFieldType = oldTypeFieldsDef[fieldName].type;
|
||||
const newFieldType = newTypeFieldsDef[fieldName].type;
|
||||
const isSafe = isChangeSafeForObjectOrInterfaceField(
|
||||
oldFieldType,
|
||||
newFieldType,
|
||||
);
|
||||
if (!isSafe) {
|
||||
const oldFieldTypeString = isNamedType(oldFieldType)
|
||||
? oldFieldType.name
|
||||
: oldFieldType.toString();
|
||||
const newFieldTypeString = isNamedType(newFieldType)
|
||||
? newFieldType.name
|
||||
: newFieldType.toString();
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.FIELD_CHANGED_KIND,
|
||||
description:
|
||||
`${typeName}.${fieldName} changed type from ` +
|
||||
`${oldFieldTypeString} to ${newFieldTypeString}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return breakingChanges;
|
||||
}
|
||||
|
||||
export function findFieldsThatChangedTypeOnInputObjectTypes(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): {
|
||||
breakingChanges: Array<BreakingChange>,
|
||||
dangerousChanges: Array<DangerousChange>,
|
||||
} {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const breakingChanges = [];
|
||||
const dangerousChanges = [];
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (!isInputObjectType(oldType) || !isInputObjectType(newType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const oldTypeFieldsDef = oldType.getFields();
|
||||
const newTypeFieldsDef = newType.getFields();
|
||||
for (const fieldName of Object.keys(oldTypeFieldsDef)) {
|
||||
// Check if the field is missing on the type in the new schema.
|
||||
if (!(fieldName in newTypeFieldsDef)) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.FIELD_REMOVED,
|
||||
description: `${typeName}.${fieldName} was removed.`,
|
||||
});
|
||||
} else {
|
||||
const oldFieldType = oldTypeFieldsDef[fieldName].type;
|
||||
const newFieldType = newTypeFieldsDef[fieldName].type;
|
||||
|
||||
const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(
|
||||
oldFieldType,
|
||||
newFieldType,
|
||||
);
|
||||
if (!isSafe) {
|
||||
const oldFieldTypeString = isNamedType(oldFieldType)
|
||||
? oldFieldType.name
|
||||
: oldFieldType.toString();
|
||||
const newFieldTypeString = isNamedType(newFieldType)
|
||||
? newFieldType.name
|
||||
: newFieldType.toString();
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.FIELD_CHANGED_KIND,
|
||||
description:
|
||||
`${typeName}.${fieldName} changed type from ` +
|
||||
`${oldFieldTypeString} to ${newFieldTypeString}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check if a field was added to the input object type
|
||||
for (const fieldName of Object.keys(newTypeFieldsDef)) {
|
||||
if (!(fieldName in oldTypeFieldsDef)) {
|
||||
if (isRequiredInputField(newTypeFieldsDef[fieldName])) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED,
|
||||
description:
|
||||
`A required field ${fieldName} on ` +
|
||||
`input type ${typeName} was added.`,
|
||||
});
|
||||
} else {
|
||||
dangerousChanges.push({
|
||||
type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED,
|
||||
description:
|
||||
`An optional field ${fieldName} on ` +
|
||||
`input type ${typeName} was added.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
breakingChanges,
|
||||
dangerousChanges,
|
||||
};
|
||||
}
|
||||
|
||||
function isChangeSafeForObjectOrInterfaceField(
|
||||
oldType: GraphQLType,
|
||||
newType: GraphQLType,
|
||||
): boolean {
|
||||
if (isNamedType(oldType)) {
|
||||
return (
|
||||
// if they're both named types, see if their names are equivalent
|
||||
(isNamedType(newType) && oldType.name === newType.name) ||
|
||||
// moving from nullable to non-null of the same underlying type is safe
|
||||
(isNonNullType(newType) &&
|
||||
isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType))
|
||||
);
|
||||
} else if (isListType(oldType)) {
|
||||
return (
|
||||
// if they're both lists, make sure the underlying types are compatible
|
||||
(isListType(newType) &&
|
||||
isChangeSafeForObjectOrInterfaceField(
|
||||
oldType.ofType,
|
||||
newType.ofType,
|
||||
)) ||
|
||||
// moving from nullable to non-null of the same underlying type is safe
|
||||
(isNonNullType(newType) &&
|
||||
isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType))
|
||||
);
|
||||
} else if (isNonNullType(oldType)) {
|
||||
// if they're both non-null, make sure the underlying types are compatible
|
||||
return (
|
||||
isNonNullType(newType) &&
|
||||
isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isChangeSafeForInputObjectFieldOrFieldArg(
|
||||
oldType: GraphQLType,
|
||||
newType: GraphQLType,
|
||||
): boolean {
|
||||
if (isNamedType(oldType)) {
|
||||
// if they're both named types, see if their names are equivalent
|
||||
return isNamedType(newType) && oldType.name === newType.name;
|
||||
} else if (isListType(oldType)) {
|
||||
// if they're both lists, make sure the underlying types are compatible
|
||||
return (
|
||||
isListType(newType) &&
|
||||
isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType)
|
||||
);
|
||||
} else if (isNonNullType(oldType)) {
|
||||
return (
|
||||
// if they're both non-null, make sure the underlying types are
|
||||
// compatible
|
||||
(isNonNullType(newType) &&
|
||||
isChangeSafeForInputObjectFieldOrFieldArg(
|
||||
oldType.ofType,
|
||||
newType.ofType,
|
||||
)) ||
|
||||
// moving from non-null to nullable of the same underlying type is safe
|
||||
(!isNonNullType(newType) &&
|
||||
isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType))
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of any breaking
|
||||
* changes in the newSchema related to removing types from a union type.
|
||||
*/
|
||||
export function findTypesRemovedFromUnions(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const typesRemovedFromUnion = [];
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (!isUnionType(oldType) || !isUnionType(newType)) {
|
||||
continue;
|
||||
}
|
||||
const typeNamesInNewUnion = Object.create(null);
|
||||
for (const type of newType.getTypes()) {
|
||||
typeNamesInNewUnion[type.name] = true;
|
||||
}
|
||||
for (const type of oldType.getTypes()) {
|
||||
if (!typeNamesInNewUnion[type.name]) {
|
||||
typesRemovedFromUnion.push({
|
||||
type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,
|
||||
description: `${type.name} was removed from union type ${typeName}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return typesRemovedFromUnion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of any dangerous
|
||||
* changes in the newSchema related to adding types to a union type.
|
||||
*/
|
||||
export function findTypesAddedToUnions(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<DangerousChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const typesAddedToUnion = [];
|
||||
for (const typeName of Object.keys(newTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (!isUnionType(oldType) || !isUnionType(newType)) {
|
||||
continue;
|
||||
}
|
||||
const typeNamesInOldUnion = Object.create(null);
|
||||
for (const type of oldType.getTypes()) {
|
||||
typeNamesInOldUnion[type.name] = true;
|
||||
}
|
||||
for (const type of newType.getTypes()) {
|
||||
if (!typeNamesInOldUnion[type.name]) {
|
||||
typesAddedToUnion.push({
|
||||
type: DangerousChangeType.TYPE_ADDED_TO_UNION,
|
||||
description: `${type.name} was added to union type ${typeName}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return typesAddedToUnion;
|
||||
}
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of any breaking
|
||||
* changes in the newSchema related to removing values from an enum type.
|
||||
*/
|
||||
export function findValuesRemovedFromEnums(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const valuesRemovedFromEnums = [];
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (!isEnumType(oldType) || !isEnumType(newType)) {
|
||||
continue;
|
||||
}
|
||||
const valuesInNewEnum = Object.create(null);
|
||||
for (const value of newType.getValues()) {
|
||||
valuesInNewEnum[value.name] = true;
|
||||
}
|
||||
for (const value of oldType.getValues()) {
|
||||
if (!valuesInNewEnum[value.name]) {
|
||||
valuesRemovedFromEnums.push({
|
||||
type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,
|
||||
description: `${value.name} was removed from enum type ${typeName}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return valuesRemovedFromEnums;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given two schemas, returns an Array containing descriptions of any dangerous
|
||||
* changes in the newSchema related to adding values to an enum type.
|
||||
*/
|
||||
export function findValuesAddedToEnums(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<DangerousChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
|
||||
const valuesAddedToEnums = [];
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (!isEnumType(oldType) || !isEnumType(newType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const valuesInOldEnum = Object.create(null);
|
||||
for (const value of oldType.getValues()) {
|
||||
valuesInOldEnum[value.name] = true;
|
||||
}
|
||||
for (const value of newType.getValues()) {
|
||||
if (!valuesInOldEnum[value.name]) {
|
||||
valuesAddedToEnums.push({
|
||||
type: DangerousChangeType.VALUE_ADDED_TO_ENUM,
|
||||
description: `${value.name} was added to enum type ${typeName}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return valuesAddedToEnums;
|
||||
}
|
||||
|
||||
export function findInterfacesRemovedFromObjectTypes(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
const breakingChanges = [];
|
||||
|
||||
for (const typeName of Object.keys(oldTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (!isObjectType(oldType) || !isObjectType(newType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const oldInterfaces = oldType.getInterfaces();
|
||||
const newInterfaces = newType.getInterfaces();
|
||||
for (const oldInterface of oldInterfaces) {
|
||||
if (!newInterfaces.some(int => int.name === oldInterface.name)) {
|
||||
breakingChanges.push({
|
||||
type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT,
|
||||
description:
|
||||
`${typeName} no longer implements interface ` +
|
||||
`${oldInterface.name}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return breakingChanges;
|
||||
}
|
||||
|
||||
export function findInterfacesAddedToObjectTypes(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<DangerousChange> {
|
||||
const oldTypeMap = oldSchema.getTypeMap();
|
||||
const newTypeMap = newSchema.getTypeMap();
|
||||
const interfacesAddedToObjectTypes = [];
|
||||
|
||||
for (const typeName of Object.keys(newTypeMap)) {
|
||||
const oldType = oldTypeMap[typeName];
|
||||
const newType = newTypeMap[typeName];
|
||||
if (!isObjectType(oldType) || !isObjectType(newType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const oldInterfaces = oldType.getInterfaces();
|
||||
const newInterfaces = newType.getInterfaces();
|
||||
for (const newInterface of newInterfaces) {
|
||||
if (!oldInterfaces.some(int => int.name === newInterface.name)) {
|
||||
interfacesAddedToObjectTypes.push({
|
||||
type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT,
|
||||
description:
|
||||
`${newInterface.name} added to interfaces implemented ` +
|
||||
`by ${typeName}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return interfacesAddedToObjectTypes;
|
||||
}
|
||||
|
||||
export function findRemovedDirectives(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const removedDirectives = [];
|
||||
|
||||
const newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema);
|
||||
for (const directive of oldSchema.getDirectives()) {
|
||||
if (!newSchemaDirectiveMap[directive.name]) {
|
||||
removedDirectives.push({
|
||||
type: BreakingChangeType.DIRECTIVE_REMOVED,
|
||||
description: `${directive.name} was removed`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return removedDirectives;
|
||||
}
|
||||
|
||||
function findRemovedArgsForDirective(
|
||||
oldDirective: GraphQLDirective,
|
||||
newDirective: GraphQLDirective,
|
||||
): Array<GraphQLArgument> {
|
||||
const removedArgs = [];
|
||||
const newArgMap = getArgumentMapForDirective(newDirective);
|
||||
|
||||
for (const arg of oldDirective.args) {
|
||||
if (!newArgMap[arg.name]) {
|
||||
removedArgs.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
return removedArgs;
|
||||
}
|
||||
|
||||
export function findRemovedDirectiveArgs(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const removedDirectiveArgs = [];
|
||||
const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
|
||||
|
||||
for (const newDirective of newSchema.getDirectives()) {
|
||||
const oldDirective = oldSchemaDirectiveMap[newDirective.name];
|
||||
if (!oldDirective) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const arg of findRemovedArgsForDirective(oldDirective, newDirective)) {
|
||||
removedDirectiveArgs.push({
|
||||
type: BreakingChangeType.DIRECTIVE_ARG_REMOVED,
|
||||
description: `${arg.name} was removed from ${newDirective.name}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return removedDirectiveArgs;
|
||||
}
|
||||
|
||||
function findAddedArgsForDirective(
|
||||
oldDirective: GraphQLDirective,
|
||||
newDirective: GraphQLDirective,
|
||||
): Array<GraphQLArgument> {
|
||||
const addedArgs = [];
|
||||
const oldArgMap = getArgumentMapForDirective(oldDirective);
|
||||
|
||||
for (const arg of newDirective.args) {
|
||||
if (!oldArgMap[arg.name]) {
|
||||
addedArgs.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
return addedArgs;
|
||||
}
|
||||
|
||||
export function findAddedNonNullDirectiveArgs(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const addedNonNullableArgs = [];
|
||||
const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
|
||||
|
||||
for (const newDirective of newSchema.getDirectives()) {
|
||||
const oldDirective = oldSchemaDirectiveMap[newDirective.name];
|
||||
if (!oldDirective) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const arg of findAddedArgsForDirective(oldDirective, newDirective)) {
|
||||
if (isRequiredArgument(arg)) {
|
||||
addedNonNullableArgs.push({
|
||||
type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED,
|
||||
description:
|
||||
`A required arg ${arg.name} on directive ` +
|
||||
`${newDirective.name} was added`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return addedNonNullableArgs;
|
||||
}
|
||||
|
||||
export function findRemovedLocationsForDirective(
|
||||
oldDirective: GraphQLDirective,
|
||||
newDirective: GraphQLDirective,
|
||||
): Array<DirectiveLocationEnum> {
|
||||
const removedLocations = [];
|
||||
const newLocationSet = new Set(newDirective.locations);
|
||||
|
||||
for (const oldLocation of oldDirective.locations) {
|
||||
if (!newLocationSet.has(oldLocation)) {
|
||||
removedLocations.push(oldLocation);
|
||||
}
|
||||
}
|
||||
|
||||
return removedLocations;
|
||||
}
|
||||
|
||||
export function findRemovedDirectiveLocations(
|
||||
oldSchema: GraphQLSchema,
|
||||
newSchema: GraphQLSchema,
|
||||
): Array<BreakingChange> {
|
||||
const removedLocations = [];
|
||||
const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema);
|
||||
|
||||
for (const newDirective of newSchema.getDirectives()) {
|
||||
const oldDirective = oldSchemaDirectiveMap[newDirective.name];
|
||||
if (!oldDirective) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const location of findRemovedLocationsForDirective(
|
||||
oldDirective,
|
||||
newDirective,
|
||||
)) {
|
||||
removedLocations.push({
|
||||
type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED,
|
||||
description: `${location} was removed from ${newDirective.name}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return removedLocations;
|
||||
}
|
||||
|
||||
function getDirectiveMapForSchema(
|
||||
schema: GraphQLSchema,
|
||||
): ObjMap<GraphQLDirective> {
|
||||
return keyMap(schema.getDirectives(), dir => dir.name);
|
||||
}
|
||||
|
||||
function getArgumentMapForDirective(
|
||||
directive: GraphQLDirective,
|
||||
): ObjMap<GraphQLArgument> {
|
||||
return keyMap(directive.args, arg => arg.name);
|
||||
}
|
||||
+1201
File diff suppressed because it is too large.
Load diff
+60
@@ -0,0 +1,60 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.findDeprecatedUsages = findDeprecatedUsages;
|
||||
|
||||
var _GraphQLError = require("../error/GraphQLError");
|
||||
|
||||
var _visitor = require("../language/visitor");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _TypeInfo = require("./TypeInfo");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* A validation rule which reports deprecated usages.
|
||||
*
|
||||
* Returns a list of GraphQLError instances describing each deprecated use.
|
||||
*/
|
||||
function findDeprecatedUsages(schema, ast) {
|
||||
var errors = [];
|
||||
var typeInfo = new _TypeInfo.TypeInfo(schema);
|
||||
(0, _visitor.visit)(ast, (0, _visitor.visitWithTypeInfo)(typeInfo, {
|
||||
Field: function Field(node) {
|
||||
var fieldDef = typeInfo.getFieldDef();
|
||||
|
||||
if (fieldDef && fieldDef.isDeprecated) {
|
||||
var parentType = typeInfo.getParentType();
|
||||
|
||||
if (parentType) {
|
||||
var reason = fieldDef.deprecationReason;
|
||||
errors.push(new _GraphQLError.GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node]));
|
||||
}
|
||||
}
|
||||
},
|
||||
EnumValue: function EnumValue(node) {
|
||||
var enumVal = typeInfo.getEnumValue();
|
||||
|
||||
if (enumVal && enumVal.isDeprecated) {
|
||||
var type = (0, _definition.getNamedType)(typeInfo.getInputType());
|
||||
|
||||
if (type) {
|
||||
var reason = enumVal.deprecationReason;
|
||||
errors.push(new _GraphQLError.GraphQLError("The enum value ".concat(type.name, ".").concat(enumVal.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
return errors;
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import { visit, visitWithTypeInfo } from '../language/visitor';
|
||||
import type { DocumentNode } from '../language/ast';
|
||||
import { getNamedType } from '../type/definition';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
import { TypeInfo } from './TypeInfo';
|
||||
|
||||
/**
|
||||
* A validation rule which reports deprecated usages.
|
||||
*
|
||||
* Returns a list of GraphQLError instances describing each deprecated use.
|
||||
*/
|
||||
export function findDeprecatedUsages(
|
||||
schema: GraphQLSchema,
|
||||
ast: DocumentNode,
|
||||
): Array<GraphQLError> {
|
||||
const errors = [];
|
||||
const typeInfo = new TypeInfo(schema);
|
||||
|
||||
visit(
|
||||
ast,
|
||||
visitWithTypeInfo(typeInfo, {
|
||||
Field(node) {
|
||||
const fieldDef = typeInfo.getFieldDef();
|
||||
if (fieldDef && fieldDef.isDeprecated) {
|
||||
const parentType = typeInfo.getParentType();
|
||||
if (parentType) {
|
||||
const reason = fieldDef.deprecationReason;
|
||||
errors.push(
|
||||
new GraphQLError(
|
||||
`The field ${parentType.name}.${fieldDef.name} is deprecated.` +
|
||||
(reason ? ' ' + reason : ''),
|
||||
[node],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
EnumValue(node) {
|
||||
const enumVal = typeInfo.getEnumValue();
|
||||
if (enumVal && enumVal.isDeprecated) {
|
||||
const type = getNamedType(typeInfo.getInputType());
|
||||
if (type) {
|
||||
const reason = enumVal.deprecationReason;
|
||||
errors.push(
|
||||
new GraphQLError(
|
||||
`The enum value ${type.name}.${enumVal.name} is deprecated.` +
|
||||
(reason ? ' ' + reason : ''),
|
||||
[node],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
return errors;
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import { visit, visitWithTypeInfo } from '../language/visitor';
|
||||
import { getNamedType } from '../type/definition';
|
||||
import { TypeInfo } from './TypeInfo';
|
||||
/**
|
||||
* A validation rule which reports deprecated usages.
|
||||
*
|
||||
* Returns a list of GraphQLError instances describing each deprecated use.
|
||||
*/
|
||||
|
||||
export function findDeprecatedUsages(schema, ast) {
|
||||
var errors = [];
|
||||
var typeInfo = new TypeInfo(schema);
|
||||
visit(ast, visitWithTypeInfo(typeInfo, {
|
||||
Field: function Field(node) {
|
||||
var fieldDef = typeInfo.getFieldDef();
|
||||
|
||||
if (fieldDef && fieldDef.isDeprecated) {
|
||||
var parentType = typeInfo.getParentType();
|
||||
|
||||
if (parentType) {
|
||||
var reason = fieldDef.deprecationReason;
|
||||
errors.push(new GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node]));
|
||||
}
|
||||
}
|
||||
},
|
||||
EnumValue: function EnumValue(node) {
|
||||
var enumVal = typeInfo.getEnumValue();
|
||||
|
||||
if (enumVal && enumVal.isDeprecated) {
|
||||
var type = getNamedType(typeInfo.getInputType());
|
||||
|
||||
if (type) {
|
||||
var reason = enumVal.deprecationReason;
|
||||
errors.push(new GraphQLError("The enum value ".concat(type.name, ".").concat(enumVal.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
return errors;
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.getOperationAST = getOperationAST;
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns an operation AST given a document AST and optionally an operation
|
||||
* name. If a name is not provided, an operation is only returned if only one is
|
||||
* provided in the document.
|
||||
*/
|
||||
function getOperationAST(documentAST, operationName) {
|
||||
var operation = null;
|
||||
|
||||
for (var i = 0; i < documentAST.definitions.length; i++) {
|
||||
var definition = documentAST.definitions[i];
|
||||
|
||||
if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) {
|
||||
if (!operationName) {
|
||||
// If no operation name was provided, only return an Operation if there
|
||||
// is one defined in the document. Upon encountering the second, return
|
||||
// null.
|
||||
if (operation) {
|
||||
return null;
|
||||
}
|
||||
|
||||
operation = definition;
|
||||
} else if (definition.name && definition.name.value === operationName) {
|
||||
return definition;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return operation;
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { Kind } from '../language/kinds';
|
||||
import type { DocumentNode, OperationDefinitionNode } from '../language/ast';
|
||||
|
||||
/**
|
||||
* Returns an operation AST given a document AST and optionally an operation
|
||||
* name. If a name is not provided, an operation is only returned if only one is
|
||||
* provided in the document.
|
||||
*/
|
||||
export function getOperationAST(
|
||||
documentAST: DocumentNode,
|
||||
operationName: ?string,
|
||||
): ?OperationDefinitionNode {
|
||||
let operation = null;
|
||||
for (let i = 0; i < documentAST.definitions.length; i++) {
|
||||
const definition = documentAST.definitions[i];
|
||||
if (definition.kind === Kind.OPERATION_DEFINITION) {
|
||||
if (!operationName) {
|
||||
// If no operation name was provided, only return an Operation if there
|
||||
// is one defined in the document. Upon encountering the second, return
|
||||
// null.
|
||||
if (operation) {
|
||||
return null;
|
||||
}
|
||||
operation = definition;
|
||||
} else if (definition.name && definition.name.value === operationName) {
|
||||
return definition;
|
||||
}
|
||||
}
|
||||
}
|
||||
return operation;
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { Kind } from '../language/kinds';
|
||||
|
||||
/**
|
||||
* Returns an operation AST given a document AST and optionally an operation
|
||||
* name. If a name is not provided, an operation is only returned if only one is
|
||||
* provided in the document.
|
||||
*/
|
||||
export function getOperationAST(documentAST, operationName) {
|
||||
var operation = null;
|
||||
|
||||
for (var i = 0; i < documentAST.definitions.length; i++) {
|
||||
var definition = documentAST.definitions[i];
|
||||
|
||||
if (definition.kind === Kind.OPERATION_DEFINITION) {
|
||||
if (!operationName) {
|
||||
// If no operation name was provided, only return an Operation if there
|
||||
// is one defined in the document. Upon encountering the second, return
|
||||
// null.
|
||||
if (operation) {
|
||||
return null;
|
||||
}
|
||||
|
||||
operation = definition;
|
||||
} else if (definition.name && definition.name.value === operationName) {
|
||||
return definition;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return operation;
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.getOperationRootType = getOperationRootType;
|
||||
|
||||
var _GraphQLError = require("../error/GraphQLError");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Extracts the root type of the operation from the schema.
|
||||
*/
|
||||
function getOperationRootType(schema, operation) {
|
||||
switch (operation.operation) {
|
||||
case 'query':
|
||||
var queryType = schema.getQueryType();
|
||||
|
||||
if (!queryType) {
|
||||
throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', [operation]);
|
||||
}
|
||||
|
||||
return queryType;
|
||||
|
||||
case 'mutation':
|
||||
var mutationType = schema.getMutationType();
|
||||
|
||||
if (!mutationType) {
|
||||
throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', [operation]);
|
||||
}
|
||||
|
||||
return mutationType;
|
||||
|
||||
case 'subscription':
|
||||
var subscriptionType = schema.getSubscriptionType();
|
||||
|
||||
if (!subscriptionType) {
|
||||
throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', [operation]);
|
||||
}
|
||||
|
||||
return subscriptionType;
|
||||
|
||||
default:
|
||||
throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', [operation]);
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
import type {
|
||||
OperationDefinitionNode,
|
||||
OperationTypeDefinitionNode,
|
||||
} from '../language/ast';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
import type { GraphQLObjectType } from '../type/definition';
|
||||
|
||||
/**
|
||||
* Extracts the root type of the operation from the schema.
|
||||
*/
|
||||
export function getOperationRootType(
|
||||
schema: GraphQLSchema,
|
||||
operation: OperationDefinitionNode | OperationTypeDefinitionNode,
|
||||
): GraphQLObjectType {
|
||||
switch (operation.operation) {
|
||||
case 'query':
|
||||
const queryType = schema.getQueryType();
|
||||
if (!queryType) {
|
||||
throw new GraphQLError(
|
||||
'Schema does not define the required query root type.',
|
||||
[operation],
|
||||
);
|
||||
}
|
||||
return queryType;
|
||||
case 'mutation':
|
||||
const mutationType = schema.getMutationType();
|
||||
if (!mutationType) {
|
||||
throw new GraphQLError('Schema is not configured for mutations.', [
|
||||
operation,
|
||||
]);
|
||||
}
|
||||
return mutationType;
|
||||
case 'subscription':
|
||||
const subscriptionType = schema.getSubscriptionType();
|
||||
if (!subscriptionType) {
|
||||
throw new GraphQLError('Schema is not configured for subscriptions.', [
|
||||
operation,
|
||||
]);
|
||||
}
|
||||
return subscriptionType;
|
||||
default:
|
||||
throw new GraphQLError(
|
||||
'Can only have query, mutation and subscription operations.',
|
||||
[operation],
|
||||
);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { GraphQLError } from '../error/GraphQLError';
|
||||
|
||||
/**
|
||||
* Extracts the root type of the operation from the schema.
|
||||
*/
|
||||
export function getOperationRootType(schema, operation) {
|
||||
switch (operation.operation) {
|
||||
case 'query':
|
||||
var queryType = schema.getQueryType();
|
||||
|
||||
if (!queryType) {
|
||||
throw new GraphQLError('Schema does not define the required query root type.', [operation]);
|
||||
}
|
||||
|
||||
return queryType;
|
||||
|
||||
case 'mutation':
|
||||
var mutationType = schema.getMutationType();
|
||||
|
||||
if (!mutationType) {
|
||||
throw new GraphQLError('Schema is not configured for mutations.', [operation]);
|
||||
}
|
||||
|
||||
return mutationType;
|
||||
|
||||
case 'subscription':
|
||||
var subscriptionType = schema.getSubscriptionType();
|
||||
|
||||
if (!subscriptionType) {
|
||||
throw new GraphQLError('Schema is not configured for subscriptions.', [operation]);
|
||||
}
|
||||
|
||||
return subscriptionType;
|
||||
|
||||
default:
|
||||
throw new GraphQLError('Can only have query, mutation and subscription operations.', [operation]);
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "getIntrospectionQuery", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _introspectionQuery.getIntrospectionQuery;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "introspectionQuery", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _introspectionQuery.introspectionQuery;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "getOperationAST", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _getOperationAST.getOperationAST;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "getOperationRootType", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _getOperationRootType.getOperationRootType;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "introspectionFromSchema", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _introspectionFromSchema.introspectionFromSchema;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "buildClientSchema", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _buildClientSchema.buildClientSchema;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "buildASTSchema", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _buildASTSchema.buildASTSchema;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "buildSchema", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _buildASTSchema.buildSchema;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "getDescription", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _buildASTSchema.getDescription;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "extendSchema", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _extendSchema.extendSchema;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "lexicographicSortSchema", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _lexicographicSortSchema.lexicographicSortSchema;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "printSchema", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _schemaPrinter.printSchema;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "printType", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _schemaPrinter.printType;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "printIntrospectionSchema", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _schemaPrinter.printIntrospectionSchema;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "typeFromAST", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _typeFromAST.typeFromAST;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "valueFromAST", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _valueFromAST.valueFromAST;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "valueFromASTUntyped", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _valueFromASTUntyped.valueFromASTUntyped;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "astFromValue", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _astFromValue.astFromValue;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "TypeInfo", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _TypeInfo.TypeInfo;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "coerceValue", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _coerceValue.coerceValue;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "isValidJSValue", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _isValidJSValue.isValidJSValue;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "isValidLiteralValue", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _isValidLiteralValue.isValidLiteralValue;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "concatAST", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _concatAST.concatAST;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "separateOperations", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _separateOperations.separateOperations;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "isEqualType", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _typeComparators.isEqualType;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "isTypeSubTypeOf", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _typeComparators.isTypeSubTypeOf;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "doTypesOverlap", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _typeComparators.doTypesOverlap;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "assertValidName", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _assertValidName.assertValidName;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "isValidNameError", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _assertValidName.isValidNameError;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "BreakingChangeType", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _findBreakingChanges.BreakingChangeType;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "DangerousChangeType", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _findBreakingChanges.DangerousChangeType;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "findBreakingChanges", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _findBreakingChanges.findBreakingChanges;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "findDangerousChanges", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _findBreakingChanges.findDangerousChanges;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, "findDeprecatedUsages", {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
return _findDeprecatedUsages.findDeprecatedUsages;
|
||||
}
|
||||
});
|
||||
|
||||
var _introspectionQuery = require("./introspectionQuery");
|
||||
|
||||
var _getOperationAST = require("./getOperationAST");
|
||||
|
||||
var _getOperationRootType = require("./getOperationRootType");
|
||||
|
||||
var _introspectionFromSchema = require("./introspectionFromSchema");
|
||||
|
||||
var _buildClientSchema = require("./buildClientSchema");
|
||||
|
||||
var _buildASTSchema = require("./buildASTSchema");
|
||||
|
||||
var _extendSchema = require("./extendSchema");
|
||||
|
||||
var _lexicographicSortSchema = require("./lexicographicSortSchema");
|
||||
|
||||
var _schemaPrinter = require("./schemaPrinter");
|
||||
|
||||
var _typeFromAST = require("./typeFromAST");
|
||||
|
||||
var _valueFromAST = require("./valueFromAST");
|
||||
|
||||
var _valueFromASTUntyped = require("./valueFromASTUntyped");
|
||||
|
||||
var _astFromValue = require("./astFromValue");
|
||||
|
||||
var _TypeInfo = require("./TypeInfo");
|
||||
|
||||
var _coerceValue = require("./coerceValue");
|
||||
|
||||
var _isValidJSValue = require("./isValidJSValue");
|
||||
|
||||
var _isValidLiteralValue = require("./isValidLiteralValue");
|
||||
|
||||
var _concatAST = require("./concatAST");
|
||||
|
||||
var _separateOperations = require("./separateOperations");
|
||||
|
||||
var _typeComparators = require("./typeComparators");
|
||||
|
||||
var _assertValidName = require("./assertValidName");
|
||||
|
||||
var _findBreakingChanges = require("./findBreakingChanges");
|
||||
|
||||
var _findDeprecatedUsages = require("./findDeprecatedUsages");
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
// The GraphQL query recommended for a full schema introspection.
|
||||
export {
|
||||
getIntrospectionQuery,
|
||||
// @deprecated, use getIntrospectionQuery() - will be removed in v15
|
||||
introspectionQuery,
|
||||
} from './introspectionQuery';
|
||||
export type {
|
||||
IntrospectionOptions,
|
||||
IntrospectionQuery,
|
||||
IntrospectionSchema,
|
||||
IntrospectionType,
|
||||
IntrospectionInputType,
|
||||
IntrospectionOutputType,
|
||||
IntrospectionScalarType,
|
||||
IntrospectionObjectType,
|
||||
IntrospectionInterfaceType,
|
||||
IntrospectionUnionType,
|
||||
IntrospectionEnumType,
|
||||
IntrospectionInputObjectType,
|
||||
IntrospectionTypeRef,
|
||||
IntrospectionInputTypeRef,
|
||||
IntrospectionOutputTypeRef,
|
||||
IntrospectionNamedTypeRef,
|
||||
IntrospectionListTypeRef,
|
||||
IntrospectionNonNullTypeRef,
|
||||
IntrospectionField,
|
||||
IntrospectionInputValue,
|
||||
IntrospectionEnumValue,
|
||||
IntrospectionDirective,
|
||||
} from './introspectionQuery';
|
||||
|
||||
// Gets the target Operation from a Document
|
||||
export { getOperationAST } from './getOperationAST';
|
||||
|
||||
// Gets the Type for the target Operation AST.
|
||||
export { getOperationRootType } from './getOperationRootType';
|
||||
|
||||
// Convert a GraphQLSchema to an IntrospectionQuery
|
||||
export { introspectionFromSchema } from './introspectionFromSchema';
|
||||
|
||||
// Build a GraphQLSchema from an introspection result.
|
||||
export { buildClientSchema } from './buildClientSchema';
|
||||
|
||||
// Build a GraphQLSchema from GraphQL Schema language.
|
||||
export {
|
||||
buildASTSchema,
|
||||
buildSchema,
|
||||
// @deprecated: Get the description from a schema AST node and supports legacy
|
||||
// syntax for specifying descriptions - will be removed in v16
|
||||
getDescription,
|
||||
} from './buildASTSchema';
|
||||
export type { BuildSchemaOptions } from './buildASTSchema';
|
||||
|
||||
// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST.
|
||||
export { extendSchema } from './extendSchema';
|
||||
|
||||
// Sort a GraphQLSchema.
|
||||
export { lexicographicSortSchema } from './lexicographicSortSchema';
|
||||
|
||||
// Print a GraphQLSchema to GraphQL Schema language.
|
||||
export {
|
||||
printSchema,
|
||||
printType,
|
||||
printIntrospectionSchema,
|
||||
} from './schemaPrinter';
|
||||
|
||||
// Create a GraphQLType from a GraphQL language AST.
|
||||
export { typeFromAST } from './typeFromAST';
|
||||
|
||||
// Create a JavaScript value from a GraphQL language AST with a type.
|
||||
export { valueFromAST } from './valueFromAST';
|
||||
|
||||
// Create a JavaScript value from a GraphQL language AST without a type.
|
||||
export { valueFromASTUntyped } from './valueFromASTUntyped';
|
||||
|
||||
// Create a GraphQL language AST from a JavaScript value.
|
||||
export { astFromValue } from './astFromValue';
|
||||
|
||||
// A helper to use within recursive-descent visitors which need to be aware of
|
||||
// the GraphQL type system.
|
||||
export { TypeInfo } from './TypeInfo';
|
||||
|
||||
// Coerces a JavaScript value to a GraphQL type, or produces errors.
|
||||
export { coerceValue } from './coerceValue';
|
||||
|
||||
// @deprecated use coerceValue - will be removed in v15
|
||||
export { isValidJSValue } from './isValidJSValue';
|
||||
|
||||
// @deprecated use validation - will be removed in v15
|
||||
export { isValidLiteralValue } from './isValidLiteralValue';
|
||||
|
||||
// Concatenates multiple AST together.
|
||||
export { concatAST } from './concatAST';
|
||||
|
||||
// Separates an AST into an AST per Operation.
|
||||
export { separateOperations } from './separateOperations';
|
||||
|
||||
// Comparators for types
|
||||
export {
|
||||
isEqualType,
|
||||
isTypeSubTypeOf,
|
||||
doTypesOverlap,
|
||||
} from './typeComparators';
|
||||
|
||||
// Asserts that a string is a valid GraphQL name
|
||||
export { assertValidName, isValidNameError } from './assertValidName';
|
||||
|
||||
// Compares two GraphQLSchemas and detects breaking changes.
|
||||
export {
|
||||
BreakingChangeType,
|
||||
DangerousChangeType,
|
||||
findBreakingChanges,
|
||||
findDangerousChanges,
|
||||
} from './findBreakingChanges';
|
||||
export type { BreakingChange, DangerousChange } from './findBreakingChanges';
|
||||
|
||||
// Report all deprecated usage within a GraphQL document.
|
||||
export { findDeprecatedUsages } from './findDeprecatedUsages';
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
// The GraphQL query recommended for a full schema introspection.
|
||||
export { getIntrospectionQuery, // @deprecated, use getIntrospectionQuery() - will be removed in v15
|
||||
introspectionQuery } from './introspectionQuery';
|
||||
// Gets the target Operation from a Document
|
||||
export { getOperationAST } from './getOperationAST'; // Gets the Type for the target Operation AST.
|
||||
|
||||
export { getOperationRootType } from './getOperationRootType'; // Convert a GraphQLSchema to an IntrospectionQuery
|
||||
|
||||
export { introspectionFromSchema } from './introspectionFromSchema'; // Build a GraphQLSchema from an introspection result.
|
||||
|
||||
export { buildClientSchema } from './buildClientSchema'; // Build a GraphQLSchema from GraphQL Schema language.
|
||||
|
||||
export { buildASTSchema, buildSchema, // @deprecated: Get the description from a schema AST node and supports legacy
|
||||
// syntax for specifying descriptions - will be removed in v16
|
||||
getDescription } from './buildASTSchema';
|
||||
// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST.
|
||||
export { extendSchema } from './extendSchema'; // Sort a GraphQLSchema.
|
||||
|
||||
export { lexicographicSortSchema } from './lexicographicSortSchema'; // Print a GraphQLSchema to GraphQL Schema language.
|
||||
|
||||
export { printSchema, printType, printIntrospectionSchema } from './schemaPrinter'; // Create a GraphQLType from a GraphQL language AST.
|
||||
|
||||
export { typeFromAST } from './typeFromAST'; // Create a JavaScript value from a GraphQL language AST with a type.
|
||||
|
||||
export { valueFromAST } from './valueFromAST'; // Create a JavaScript value from a GraphQL language AST without a type.
|
||||
|
||||
export { valueFromASTUntyped } from './valueFromASTUntyped'; // Create a GraphQL language AST from a JavaScript value.
|
||||
|
||||
export { astFromValue } from './astFromValue'; // A helper to use within recursive-descent visitors which need to be aware of
|
||||
// the GraphQL type system.
|
||||
|
||||
export { TypeInfo } from './TypeInfo'; // Coerces a JavaScript value to a GraphQL type, or produces errors.
|
||||
|
||||
export { coerceValue } from './coerceValue'; // @deprecated use coerceValue - will be removed in v15
|
||||
|
||||
export { isValidJSValue } from './isValidJSValue'; // @deprecated use validation - will be removed in v15
|
||||
|
||||
export { isValidLiteralValue } from './isValidLiteralValue'; // Concatenates multiple AST together.
|
||||
|
||||
export { concatAST } from './concatAST'; // Separates an AST into an AST per Operation.
|
||||
|
||||
export { separateOperations } from './separateOperations'; // Comparators for types
|
||||
|
||||
export { isEqualType, isTypeSubTypeOf, doTypesOverlap } from './typeComparators'; // Asserts that a string is a valid GraphQL name
|
||||
|
||||
export { assertValidName, isValidNameError } from './assertValidName'; // Compares two GraphQLSchemas and detects breaking changes.
|
||||
|
||||
export { BreakingChangeType, DangerousChangeType, findBreakingChanges, findDangerousChanges } from './findBreakingChanges';
|
||||
// Report all deprecated usage within a GraphQL document.
|
||||
export { findDeprecatedUsages } from './findDeprecatedUsages';
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.introspectionFromSchema = introspectionFromSchema;
|
||||
|
||||
var _invariant = _interopRequireDefault(require("../jsutils/invariant"));
|
||||
|
||||
var _introspectionQuery = require("./introspectionQuery");
|
||||
|
||||
var _execute = require("../execution/execute");
|
||||
|
||||
var _parser = require("../language/parser");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Build an IntrospectionQuery from a GraphQLSchema
|
||||
*
|
||||
* IntrospectionQuery is useful for utilities that care about type and field
|
||||
* relationships, but do not need to traverse through those relationships.
|
||||
*
|
||||
* This is the inverse of buildClientSchema. The primary use case is outside
|
||||
* of the server context, for instance when doing schema comparisons.
|
||||
*/
|
||||
function introspectionFromSchema(schema, options) {
|
||||
var queryAST = (0, _parser.parse)((0, _introspectionQuery.getIntrospectionQuery)(options));
|
||||
var result = (0, _execute.execute)(schema, queryAST);
|
||||
!(!result.then && !result.errors && result.data) ? (0, _invariant.default)(0) : void 0;
|
||||
return result.data;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import invariant from '../jsutils/invariant';
|
||||
import { getIntrospectionQuery } from './introspectionQuery';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
import { execute } from '../execution/execute';
|
||||
import { parse } from '../language/parser';
|
||||
import type {
|
||||
IntrospectionQuery,
|
||||
IntrospectionOptions,
|
||||
} from './introspectionQuery';
|
||||
|
||||
/**
|
||||
* Build an IntrospectionQuery from a GraphQLSchema
|
||||
*
|
||||
* IntrospectionQuery is useful for utilities that care about type and field
|
||||
* relationships, but do not need to traverse through those relationships.
|
||||
*
|
||||
* This is the inverse of buildClientSchema. The primary use case is outside
|
||||
* of the server context, for instance when doing schema comparisons.
|
||||
*/
|
||||
export function introspectionFromSchema(
|
||||
schema: GraphQLSchema,
|
||||
options?: IntrospectionOptions,
|
||||
): IntrospectionQuery {
|
||||
const queryAST = parse(getIntrospectionQuery(options));
|
||||
const result = execute(schema, queryAST);
|
||||
invariant(!result.then && !result.errors && result.data);
|
||||
return (result.data: any);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import invariant from '../jsutils/invariant';
|
||||
import { getIntrospectionQuery } from './introspectionQuery';
|
||||
import { execute } from '../execution/execute';
|
||||
import { parse } from '../language/parser';
|
||||
|
||||
/**
|
||||
* Build an IntrospectionQuery from a GraphQLSchema
|
||||
*
|
||||
* IntrospectionQuery is useful for utilities that care about type and field
|
||||
* relationships, but do not need to traverse through those relationships.
|
||||
*
|
||||
* This is the inverse of buildClientSchema. The primary use case is outside
|
||||
* of the server context, for instance when doing schema comparisons.
|
||||
*/
|
||||
export function introspectionFromSchema(schema, options) {
|
||||
var queryAST = parse(getIntrospectionQuery(options));
|
||||
var result = execute(schema, queryAST);
|
||||
!(!result.then && !result.errors && result.data) ? invariant(0) : void 0;
|
||||
return result.data;
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.getIntrospectionQuery = getIntrospectionQuery;
|
||||
exports.introspectionQuery = void 0;
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
function getIntrospectionQuery(options) {
|
||||
var descriptions = !(options && options.descriptions === false);
|
||||
return "\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ".concat(descriptions ? 'description' : '', "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions ? 'description' : '', "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions ? 'description' : '', "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n ");
|
||||
}
|
||||
/**
|
||||
* Deprecated, call getIntrospectionQuery directly.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
|
||||
|
||||
var introspectionQuery = getIntrospectionQuery();
|
||||
exports.introspectionQuery = introspectionQuery;
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import type { DirectiveLocationEnum } from '../language/directiveLocation';
|
||||
|
||||
export type IntrospectionOptions = {|
|
||||
// Whether to include descriptions in the introspection result.
|
||||
// Default: true
|
||||
descriptions: boolean,
|
||||
|};
|
||||
|
||||
export function getIntrospectionQuery(options?: IntrospectionOptions): string {
|
||||
const descriptions = !(options && options.descriptions === false);
|
||||
return `
|
||||
query IntrospectionQuery {
|
||||
__schema {
|
||||
queryType { name }
|
||||
mutationType { name }
|
||||
subscriptionType { name }
|
||||
types {
|
||||
...FullType
|
||||
}
|
||||
directives {
|
||||
name
|
||||
${descriptions ? 'description' : ''}
|
||||
locations
|
||||
args {
|
||||
...InputValue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fragment FullType on __Type {
|
||||
kind
|
||||
name
|
||||
${descriptions ? 'description' : ''}
|
||||
fields(includeDeprecated: true) {
|
||||
name
|
||||
${descriptions ? 'description' : ''}
|
||||
args {
|
||||
...InputValue
|
||||
}
|
||||
type {
|
||||
...TypeRef
|
||||
}
|
||||
isDeprecated
|
||||
deprecationReason
|
||||
}
|
||||
inputFields {
|
||||
...InputValue
|
||||
}
|
||||
interfaces {
|
||||
...TypeRef
|
||||
}
|
||||
enumValues(includeDeprecated: true) {
|
||||
name
|
||||
${descriptions ? 'description' : ''}
|
||||
isDeprecated
|
||||
deprecationReason
|
||||
}
|
||||
possibleTypes {
|
||||
...TypeRef
|
||||
}
|
||||
}
|
||||
|
||||
fragment InputValue on __InputValue {
|
||||
name
|
||||
${descriptions ? 'description' : ''}
|
||||
type { ...TypeRef }
|
||||
defaultValue
|
||||
}
|
||||
|
||||
fragment TypeRef on __Type {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
ofType {
|
||||
kind
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deprecated, call getIntrospectionQuery directly.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
export const introspectionQuery = getIntrospectionQuery();
|
||||
|
||||
export type IntrospectionQuery = {|
|
||||
+__schema: IntrospectionSchema,
|
||||
|};
|
||||
|
||||
export type IntrospectionSchema = {|
|
||||
+queryType: IntrospectionNamedTypeRef<IntrospectionObjectType>,
|
||||
+mutationType: ?IntrospectionNamedTypeRef<IntrospectionObjectType>,
|
||||
+subscriptionType: ?IntrospectionNamedTypeRef<IntrospectionObjectType>,
|
||||
+types: $ReadOnlyArray<IntrospectionType>,
|
||||
+directives: $ReadOnlyArray<IntrospectionDirective>,
|
||||
|};
|
||||
|
||||
export type IntrospectionType =
|
||||
| IntrospectionScalarType
|
||||
| IntrospectionObjectType
|
||||
| IntrospectionInterfaceType
|
||||
| IntrospectionUnionType
|
||||
| IntrospectionEnumType
|
||||
| IntrospectionInputObjectType;
|
||||
|
||||
export type IntrospectionOutputType =
|
||||
| IntrospectionScalarType
|
||||
| IntrospectionObjectType
|
||||
| IntrospectionInterfaceType
|
||||
| IntrospectionUnionType
|
||||
| IntrospectionEnumType;
|
||||
|
||||
export type IntrospectionInputType =
|
||||
| IntrospectionScalarType
|
||||
| IntrospectionEnumType
|
||||
| IntrospectionInputObjectType;
|
||||
|
||||
export type IntrospectionScalarType = {
|
||||
+kind: 'SCALAR',
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
};
|
||||
|
||||
export type IntrospectionObjectType = {
|
||||
+kind: 'OBJECT',
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+fields: $ReadOnlyArray<IntrospectionField>,
|
||||
+interfaces: $ReadOnlyArray<
|
||||
IntrospectionNamedTypeRef<IntrospectionInterfaceType>,
|
||||
>,
|
||||
};
|
||||
|
||||
export type IntrospectionInterfaceType = {
|
||||
+kind: 'INTERFACE',
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+fields: $ReadOnlyArray<IntrospectionField>,
|
||||
+possibleTypes: $ReadOnlyArray<
|
||||
IntrospectionNamedTypeRef<IntrospectionObjectType>,
|
||||
>,
|
||||
};
|
||||
|
||||
export type IntrospectionUnionType = {
|
||||
+kind: 'UNION',
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+possibleTypes: $ReadOnlyArray<
|
||||
IntrospectionNamedTypeRef<IntrospectionObjectType>,
|
||||
>,
|
||||
};
|
||||
|
||||
export type IntrospectionEnumType = {
|
||||
+kind: 'ENUM',
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+enumValues: $ReadOnlyArray<IntrospectionEnumValue>,
|
||||
};
|
||||
|
||||
export type IntrospectionInputObjectType = {
|
||||
+kind: 'INPUT_OBJECT',
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+inputFields: $ReadOnlyArray<IntrospectionInputValue>,
|
||||
};
|
||||
|
||||
export type IntrospectionListTypeRef<
|
||||
T: IntrospectionTypeRef = IntrospectionTypeRef,
|
||||
> = {
|
||||
+kind: 'LIST',
|
||||
+ofType: T,
|
||||
};
|
||||
|
||||
export type IntrospectionNonNullTypeRef<
|
||||
T: IntrospectionTypeRef = IntrospectionTypeRef,
|
||||
> = {
|
||||
+kind: 'NON_NULL',
|
||||
+ofType: T,
|
||||
};
|
||||
|
||||
export type IntrospectionTypeRef =
|
||||
| IntrospectionNamedTypeRef<IntrospectionType>
|
||||
| IntrospectionListTypeRef<IntrospectionTypeRef>
|
||||
| IntrospectionNonNullTypeRef<
|
||||
| IntrospectionNamedTypeRef<IntrospectionType>
|
||||
| IntrospectionListTypeRef<IntrospectionTypeRef>,
|
||||
>;
|
||||
|
||||
export type IntrospectionOutputTypeRef =
|
||||
| IntrospectionNamedTypeRef<IntrospectionOutputType>
|
||||
| IntrospectionListTypeRef<IntrospectionOutputTypeRef>
|
||||
| IntrospectionNonNullTypeRef<
|
||||
| IntrospectionNamedTypeRef<IntrospectionOutputType>
|
||||
| IntrospectionListTypeRef<IntrospectionOutputTypeRef>,
|
||||
>;
|
||||
|
||||
export type IntrospectionInputTypeRef =
|
||||
| IntrospectionNamedTypeRef<IntrospectionInputType>
|
||||
| IntrospectionListTypeRef<IntrospectionInputTypeRef>
|
||||
| IntrospectionNonNullTypeRef<
|
||||
| IntrospectionNamedTypeRef<IntrospectionInputType>
|
||||
| IntrospectionListTypeRef<IntrospectionInputTypeRef>,
|
||||
>;
|
||||
|
||||
export type IntrospectionNamedTypeRef<
|
||||
T: IntrospectionType = IntrospectionType,
|
||||
> = {
|
||||
+kind: $PropertyType<T, 'kind'>,
|
||||
+name: string,
|
||||
};
|
||||
|
||||
export type IntrospectionField = {|
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+args: $ReadOnlyArray<IntrospectionInputValue>,
|
||||
+type: IntrospectionOutputTypeRef,
|
||||
+isDeprecated: boolean,
|
||||
+deprecationReason: ?string,
|
||||
|};
|
||||
|
||||
export type IntrospectionInputValue = {|
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+type: IntrospectionInputTypeRef,
|
||||
+defaultValue: ?string,
|
||||
|};
|
||||
|
||||
export type IntrospectionEnumValue = {|
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+isDeprecated: boolean,
|
||||
+deprecationReason: ?string,
|
||||
|};
|
||||
|
||||
export type IntrospectionDirective = {|
|
||||
+name: string,
|
||||
+description?: ?string,
|
||||
+locations: $ReadOnlyArray<DirectiveLocationEnum>,
|
||||
+args: $ReadOnlyArray<IntrospectionInputValue>,
|
||||
|};
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
export function getIntrospectionQuery(options) {
|
||||
var descriptions = !(options && options.descriptions === false);
|
||||
return "\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ".concat(descriptions ? 'description' : '', "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions ? 'description' : '', "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions ? 'description' : '', "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n ");
|
||||
}
|
||||
/**
|
||||
* Deprecated, call getIntrospectionQuery directly.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
|
||||
export var introspectionQuery = getIntrospectionQuery();
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.isValidJSValue = isValidJSValue;
|
||||
|
||||
var _coerceValue = require("./coerceValue");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Deprecated. Use coerceValue() directly for richer information.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
function isValidJSValue(value, type) {
|
||||
var errors = (0, _coerceValue.coerceValue)(value, type).errors;
|
||||
return errors ? errors.map(function (error) {
|
||||
return error.message;
|
||||
}) : [];
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { coerceValue } from './coerceValue';
|
||||
import type { GraphQLInputType } from '../type/definition';
|
||||
|
||||
/**
|
||||
* Deprecated. Use coerceValue() directly for richer information.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
export function isValidJSValue(
|
||||
value: mixed,
|
||||
type: GraphQLInputType,
|
||||
): Array<string> {
|
||||
const errors = coerceValue(value, type).errors;
|
||||
return errors ? errors.map(error => error.message) : [];
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { coerceValue } from './coerceValue';
|
||||
|
||||
/**
|
||||
* Deprecated. Use coerceValue() directly for richer information.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
export function isValidJSValue(value, type) {
|
||||
var errors = coerceValue(value, type).errors;
|
||||
return errors ? errors.map(function (error) {
|
||||
return error.message;
|
||||
}) : [];
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.isValidLiteralValue = isValidLiteralValue;
|
||||
|
||||
var _TypeInfo = require("./TypeInfo");
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _visitor = require("../language/visitor");
|
||||
|
||||
var _schema = require("../type/schema");
|
||||
|
||||
var _ValuesOfCorrectType = require("../validation/rules/ValuesOfCorrectType");
|
||||
|
||||
var _ValidationContext = require("../validation/ValidationContext");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Utility which determines if a value literal node is valid for an input type.
|
||||
*
|
||||
* Deprecated. Rely on validation for documents containing literal values.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
function isValidLiteralValue(type, valueNode) {
|
||||
var emptySchema = new _schema.GraphQLSchema({});
|
||||
var emptyDoc = {
|
||||
kind: _kinds.Kind.DOCUMENT,
|
||||
definitions: []
|
||||
};
|
||||
var typeInfo = new _TypeInfo.TypeInfo(emptySchema, undefined, type);
|
||||
var context = new _ValidationContext.ValidationContext(emptySchema, emptyDoc, typeInfo);
|
||||
var visitor = (0, _ValuesOfCorrectType.ValuesOfCorrectType)(context);
|
||||
(0, _visitor.visit)(valueNode, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor));
|
||||
return context.getErrors();
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { TypeInfo } from './TypeInfo';
|
||||
import type { GraphQLError } from '../error/GraphQLError';
|
||||
import type { ValueNode } from '../language/ast';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { visit, visitWithTypeInfo } from '../language/visitor';
|
||||
import type { GraphQLInputType } from '../type/definition';
|
||||
import { GraphQLSchema } from '../type/schema';
|
||||
import { ValuesOfCorrectType } from '../validation/rules/ValuesOfCorrectType';
|
||||
import { ValidationContext } from '../validation/ValidationContext';
|
||||
|
||||
/**
|
||||
* Utility which determines if a value literal node is valid for an input type.
|
||||
*
|
||||
* Deprecated. Rely on validation for documents containing literal values.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
export function isValidLiteralValue(
|
||||
type: GraphQLInputType,
|
||||
valueNode: ValueNode,
|
||||
): $ReadOnlyArray<GraphQLError> {
|
||||
const emptySchema = new GraphQLSchema({});
|
||||
const emptyDoc = { kind: Kind.DOCUMENT, definitions: [] };
|
||||
const typeInfo = new TypeInfo(emptySchema, undefined, type);
|
||||
const context = new ValidationContext(emptySchema, emptyDoc, typeInfo);
|
||||
const visitor = ValuesOfCorrectType(context);
|
||||
visit(valueNode, visitWithTypeInfo(typeInfo, visitor));
|
||||
return context.getErrors();
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { TypeInfo } from './TypeInfo';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { visit, visitWithTypeInfo } from '../language/visitor';
|
||||
import { GraphQLSchema } from '../type/schema';
|
||||
import { ValuesOfCorrectType } from '../validation/rules/ValuesOfCorrectType';
|
||||
import { ValidationContext } from '../validation/ValidationContext';
|
||||
/**
|
||||
* Utility which determines if a value literal node is valid for an input type.
|
||||
*
|
||||
* Deprecated. Rely on validation for documents containing literal values.
|
||||
*
|
||||
* This function will be removed in v15
|
||||
*/
|
||||
|
||||
export function isValidLiteralValue(type, valueNode) {
|
||||
var emptySchema = new GraphQLSchema({});
|
||||
var emptyDoc = {
|
||||
kind: Kind.DOCUMENT,
|
||||
definitions: []
|
||||
};
|
||||
var typeInfo = new TypeInfo(emptySchema, undefined, type);
|
||||
var context = new ValidationContext(emptySchema, emptyDoc, typeInfo);
|
||||
var visitor = ValuesOfCorrectType(context);
|
||||
visit(valueNode, visitWithTypeInfo(typeInfo, visitor));
|
||||
return context.getErrors();
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.lexicographicSortSchema = lexicographicSortSchema;
|
||||
|
||||
var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
|
||||
|
||||
var _objectValues = _interopRequireDefault(require("../jsutils/objectValues"));
|
||||
|
||||
var _schema = require("../type/schema");
|
||||
|
||||
var _directives = require("../type/directives");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _scalars = require("../type/scalars");
|
||||
|
||||
var _introspection = require("../type/introspection");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
|
||||
|
||||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
||||
|
||||
/**
|
||||
* Sort GraphQLSchema.
|
||||
*/
|
||||
function lexicographicSortSchema(schema) {
|
||||
var cache = Object.create(null);
|
||||
|
||||
var sortMaybeType = function sortMaybeType(maybeType) {
|
||||
return maybeType && sortNamedType(maybeType);
|
||||
};
|
||||
|
||||
return new _schema.GraphQLSchema({
|
||||
types: sortTypes((0, _objectValues.default)(schema.getTypeMap())),
|
||||
directives: sortByName(schema.getDirectives()).map(sortDirective),
|
||||
query: sortMaybeType(schema.getQueryType()),
|
||||
mutation: sortMaybeType(schema.getMutationType()),
|
||||
subscription: sortMaybeType(schema.getSubscriptionType()),
|
||||
astNode: schema.astNode
|
||||
});
|
||||
|
||||
function sortDirective(directive) {
|
||||
return new _directives.GraphQLDirective({
|
||||
name: directive.name,
|
||||
description: directive.description,
|
||||
locations: sortBy(directive.locations, function (x) {
|
||||
return x;
|
||||
}),
|
||||
args: sortArgs(directive.args),
|
||||
astNode: directive.astNode
|
||||
});
|
||||
}
|
||||
|
||||
function sortArgs(args) {
|
||||
return (0, _keyValMap.default)(sortByName(args), function (arg) {
|
||||
return arg.name;
|
||||
}, function (arg) {
|
||||
return _objectSpread({}, arg, {
|
||||
type: sortType(arg.type)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function sortFields(fieldsMap) {
|
||||
return sortObjMap(fieldsMap, function (field) {
|
||||
return {
|
||||
type: sortType(field.type),
|
||||
args: sortArgs(field.args),
|
||||
resolve: field.resolve,
|
||||
subscribe: field.subscribe,
|
||||
deprecationReason: field.deprecationReason,
|
||||
description: field.description,
|
||||
astNode: field.astNode
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function sortInputFields(fieldsMap) {
|
||||
return sortObjMap(fieldsMap, function (field) {
|
||||
return {
|
||||
type: sortType(field.type),
|
||||
defaultValue: field.defaultValue,
|
||||
description: field.description,
|
||||
astNode: field.astNode
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function sortType(type) {
|
||||
if ((0, _definition.isListType)(type)) {
|
||||
return new _definition.GraphQLList(sortType(type.ofType));
|
||||
} else if ((0, _definition.isNonNullType)(type)) {
|
||||
return new _definition.GraphQLNonNull(sortType(type.ofType));
|
||||
}
|
||||
|
||||
return sortNamedType(type);
|
||||
}
|
||||
|
||||
function sortTypes(arr) {
|
||||
return sortByName(arr).map(sortNamedType);
|
||||
}
|
||||
|
||||
function sortNamedType(type) {
|
||||
if ((0, _scalars.isSpecifiedScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) {
|
||||
return type;
|
||||
}
|
||||
|
||||
var sortedType = cache[type.name];
|
||||
|
||||
if (!sortedType) {
|
||||
sortedType = sortNamedTypeImpl(type);
|
||||
cache[type.name] = sortedType;
|
||||
}
|
||||
|
||||
return sortedType;
|
||||
}
|
||||
|
||||
function sortNamedTypeImpl(type) {
|
||||
if ((0, _definition.isScalarType)(type)) {
|
||||
return type;
|
||||
} else if ((0, _definition.isObjectType)(type)) {
|
||||
return new _definition.GraphQLObjectType({
|
||||
name: type.name,
|
||||
interfaces: function interfaces() {
|
||||
return sortTypes(type.getInterfaces());
|
||||
},
|
||||
fields: function fields() {
|
||||
return sortFields(type.getFields());
|
||||
},
|
||||
isTypeOf: type.isTypeOf,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: type.extensionASTNodes
|
||||
});
|
||||
} else if ((0, _definition.isInterfaceType)(type)) {
|
||||
return new _definition.GraphQLInterfaceType({
|
||||
name: type.name,
|
||||
fields: function fields() {
|
||||
return sortFields(type.getFields());
|
||||
},
|
||||
resolveType: type.resolveType,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: type.extensionASTNodes
|
||||
});
|
||||
} else if ((0, _definition.isUnionType)(type)) {
|
||||
return new _definition.GraphQLUnionType({
|
||||
name: type.name,
|
||||
types: function types() {
|
||||
return sortTypes(type.getTypes());
|
||||
},
|
||||
resolveType: type.resolveType,
|
||||
description: type.description,
|
||||
astNode: type.astNode
|
||||
});
|
||||
} else if ((0, _definition.isEnumType)(type)) {
|
||||
return new _definition.GraphQLEnumType({
|
||||
name: type.name,
|
||||
values: (0, _keyValMap.default)(sortByName(type.getValues()), function (val) {
|
||||
return val.name;
|
||||
}, function (val) {
|
||||
return {
|
||||
value: val.value,
|
||||
deprecationReason: val.deprecationReason,
|
||||
description: val.description,
|
||||
astNode: val.astNode
|
||||
};
|
||||
}),
|
||||
description: type.description,
|
||||
astNode: type.astNode
|
||||
});
|
||||
} else if ((0, _definition.isInputObjectType)(type)) {
|
||||
return new _definition.GraphQLInputObjectType({
|
||||
name: type.name,
|
||||
fields: function fields() {
|
||||
return sortInputFields(type.getFields());
|
||||
},
|
||||
description: type.description,
|
||||
astNode: type.astNode
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error("Unknown type: \"".concat(type, "\""));
|
||||
}
|
||||
}
|
||||
|
||||
function sortObjMap(map, sortValueFn) {
|
||||
var sortedMap = Object.create(null);
|
||||
var sortedKeys = sortBy(Object.keys(map), function (x) {
|
||||
return x;
|
||||
});
|
||||
|
||||
for (var _i = 0; _i < sortedKeys.length; _i++) {
|
||||
var key = sortedKeys[_i];
|
||||
var value = map[key];
|
||||
sortedMap[key] = sortValueFn ? sortValueFn(value) : value;
|
||||
}
|
||||
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
function sortByName(array) {
|
||||
return sortBy(array, function (obj) {
|
||||
return obj.name;
|
||||
});
|
||||
}
|
||||
|
||||
function sortBy(array, mapToKey) {
|
||||
return array.slice().sort(function (obj1, obj2) {
|
||||
var key1 = mapToKey(obj1);
|
||||
var key2 = mapToKey(obj2);
|
||||
return key1.localeCompare(key2);
|
||||
});
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import type { ObjMap } from '../jsutils/ObjMap';
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import { GraphQLSchema } from '../type/schema';
|
||||
import { GraphQLDirective } from '../type/directives';
|
||||
import type { GraphQLNamedType } from '../type/definition';
|
||||
import {
|
||||
GraphQLObjectType,
|
||||
GraphQLInterfaceType,
|
||||
GraphQLUnionType,
|
||||
GraphQLEnumType,
|
||||
GraphQLInputObjectType,
|
||||
GraphQLList,
|
||||
GraphQLNonNull,
|
||||
isListType,
|
||||
isNonNullType,
|
||||
isScalarType,
|
||||
isObjectType,
|
||||
isInterfaceType,
|
||||
isUnionType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
} from '../type/definition';
|
||||
import { isSpecifiedScalarType } from '../type/scalars';
|
||||
import { isIntrospectionType } from '../type/introspection';
|
||||
|
||||
/**
|
||||
* Sort GraphQLSchema.
|
||||
*/
|
||||
export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema {
|
||||
const cache = Object.create(null);
|
||||
|
||||
const sortMaybeType = maybeType => maybeType && sortNamedType(maybeType);
|
||||
return new GraphQLSchema({
|
||||
types: sortTypes(objectValues(schema.getTypeMap())),
|
||||
directives: sortByName(schema.getDirectives()).map(sortDirective),
|
||||
query: sortMaybeType(schema.getQueryType()),
|
||||
mutation: sortMaybeType(schema.getMutationType()),
|
||||
subscription: sortMaybeType(schema.getSubscriptionType()),
|
||||
astNode: schema.astNode,
|
||||
});
|
||||
|
||||
function sortDirective(directive) {
|
||||
return new GraphQLDirective({
|
||||
name: directive.name,
|
||||
description: directive.description,
|
||||
locations: sortBy(directive.locations, x => x),
|
||||
args: sortArgs(directive.args),
|
||||
astNode: directive.astNode,
|
||||
});
|
||||
}
|
||||
|
||||
function sortArgs(args) {
|
||||
return keyValMap(
|
||||
sortByName(args),
|
||||
arg => arg.name,
|
||||
arg => ({
|
||||
...arg,
|
||||
type: sortType(arg.type),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function sortFields(fieldsMap) {
|
||||
return sortObjMap(fieldsMap, field => ({
|
||||
type: sortType(field.type),
|
||||
args: sortArgs(field.args),
|
||||
resolve: field.resolve,
|
||||
subscribe: field.subscribe,
|
||||
deprecationReason: field.deprecationReason,
|
||||
description: field.description,
|
||||
astNode: field.astNode,
|
||||
}));
|
||||
}
|
||||
|
||||
function sortInputFields(fieldsMap) {
|
||||
return sortObjMap(fieldsMap, field => ({
|
||||
type: sortType(field.type),
|
||||
defaultValue: field.defaultValue,
|
||||
description: field.description,
|
||||
astNode: field.astNode,
|
||||
}));
|
||||
}
|
||||
|
||||
function sortType(type) {
|
||||
if (isListType(type)) {
|
||||
return new GraphQLList(sortType(type.ofType));
|
||||
} else if (isNonNullType(type)) {
|
||||
return new GraphQLNonNull(sortType(type.ofType));
|
||||
}
|
||||
return sortNamedType(type);
|
||||
}
|
||||
|
||||
function sortTypes<T: GraphQLNamedType>(arr: Array<T>): Array<T> {
|
||||
return sortByName(arr).map(sortNamedType);
|
||||
}
|
||||
|
||||
function sortNamedType<T: GraphQLNamedType>(type: T): T {
|
||||
if (isSpecifiedScalarType(type) || isIntrospectionType(type)) {
|
||||
return type;
|
||||
}
|
||||
|
||||
let sortedType = cache[type.name];
|
||||
if (!sortedType) {
|
||||
sortedType = sortNamedTypeImpl(type);
|
||||
cache[type.name] = sortedType;
|
||||
}
|
||||
return ((sortedType: any): T);
|
||||
}
|
||||
|
||||
function sortNamedTypeImpl(type) {
|
||||
if (isScalarType(type)) {
|
||||
return type;
|
||||
} else if (isObjectType(type)) {
|
||||
return new GraphQLObjectType({
|
||||
name: type.name,
|
||||
interfaces: () => sortTypes(type.getInterfaces()),
|
||||
fields: () => sortFields(type.getFields()),
|
||||
isTypeOf: type.isTypeOf,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: type.extensionASTNodes,
|
||||
});
|
||||
} else if (isInterfaceType(type)) {
|
||||
return new GraphQLInterfaceType({
|
||||
name: type.name,
|
||||
fields: () => sortFields(type.getFields()),
|
||||
resolveType: type.resolveType,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: type.extensionASTNodes,
|
||||
});
|
||||
} else if (isUnionType(type)) {
|
||||
return new GraphQLUnionType({
|
||||
name: type.name,
|
||||
types: () => sortTypes(type.getTypes()),
|
||||
resolveType: type.resolveType,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
});
|
||||
} else if (isEnumType(type)) {
|
||||
return new GraphQLEnumType({
|
||||
name: type.name,
|
||||
values: keyValMap(
|
||||
sortByName(type.getValues()),
|
||||
val => val.name,
|
||||
val => ({
|
||||
value: val.value,
|
||||
deprecationReason: val.deprecationReason,
|
||||
description: val.description,
|
||||
astNode: val.astNode,
|
||||
}),
|
||||
),
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
});
|
||||
} else if (isInputObjectType(type)) {
|
||||
return new GraphQLInputObjectType({
|
||||
name: type.name,
|
||||
fields: () => sortInputFields(type.getFields()),
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
});
|
||||
}
|
||||
throw new Error(`Unknown type: "${type}"`);
|
||||
}
|
||||
}
|
||||
|
||||
function sortObjMap<T, R>(map: ObjMap<T>, sortValueFn?: T => R): ObjMap<R> {
|
||||
const sortedMap = Object.create(null);
|
||||
const sortedKeys = sortBy(Object.keys(map), x => x);
|
||||
for (const key of sortedKeys) {
|
||||
const value = map[key];
|
||||
sortedMap[key] = sortValueFn ? sortValueFn(value) : value;
|
||||
}
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
function sortByName<T: { +name: string }>(array: $ReadOnlyArray<T>): Array<T> {
|
||||
return sortBy(array, obj => obj.name);
|
||||
}
|
||||
|
||||
function sortBy<T>(array: $ReadOnlyArray<T>, mapToKey: T => string): Array<T> {
|
||||
return array.slice().sort((obj1, obj2) => {
|
||||
const key1 = mapToKey(obj1);
|
||||
const key2 = mapToKey(obj2);
|
||||
return key1.localeCompare(key2);
|
||||
});
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
|
||||
|
||||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import { GraphQLSchema } from '../type/schema';
|
||||
import { GraphQLDirective } from '../type/directives';
|
||||
import { GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, isListType, isNonNullType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from '../type/definition';
|
||||
import { isSpecifiedScalarType } from '../type/scalars';
|
||||
import { isIntrospectionType } from '../type/introspection';
|
||||
/**
|
||||
* Sort GraphQLSchema.
|
||||
*/
|
||||
|
||||
export function lexicographicSortSchema(schema) {
|
||||
var cache = Object.create(null);
|
||||
|
||||
var sortMaybeType = function sortMaybeType(maybeType) {
|
||||
return maybeType && sortNamedType(maybeType);
|
||||
};
|
||||
|
||||
return new GraphQLSchema({
|
||||
types: sortTypes(objectValues(schema.getTypeMap())),
|
||||
directives: sortByName(schema.getDirectives()).map(sortDirective),
|
||||
query: sortMaybeType(schema.getQueryType()),
|
||||
mutation: sortMaybeType(schema.getMutationType()),
|
||||
subscription: sortMaybeType(schema.getSubscriptionType()),
|
||||
astNode: schema.astNode
|
||||
});
|
||||
|
||||
function sortDirective(directive) {
|
||||
return new GraphQLDirective({
|
||||
name: directive.name,
|
||||
description: directive.description,
|
||||
locations: sortBy(directive.locations, function (x) {
|
||||
return x;
|
||||
}),
|
||||
args: sortArgs(directive.args),
|
||||
astNode: directive.astNode
|
||||
});
|
||||
}
|
||||
|
||||
function sortArgs(args) {
|
||||
return keyValMap(sortByName(args), function (arg) {
|
||||
return arg.name;
|
||||
}, function (arg) {
|
||||
return _objectSpread({}, arg, {
|
||||
type: sortType(arg.type)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function sortFields(fieldsMap) {
|
||||
return sortObjMap(fieldsMap, function (field) {
|
||||
return {
|
||||
type: sortType(field.type),
|
||||
args: sortArgs(field.args),
|
||||
resolve: field.resolve,
|
||||
subscribe: field.subscribe,
|
||||
deprecationReason: field.deprecationReason,
|
||||
description: field.description,
|
||||
astNode: field.astNode
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function sortInputFields(fieldsMap) {
|
||||
return sortObjMap(fieldsMap, function (field) {
|
||||
return {
|
||||
type: sortType(field.type),
|
||||
defaultValue: field.defaultValue,
|
||||
description: field.description,
|
||||
astNode: field.astNode
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function sortType(type) {
|
||||
if (isListType(type)) {
|
||||
return new GraphQLList(sortType(type.ofType));
|
||||
} else if (isNonNullType(type)) {
|
||||
return new GraphQLNonNull(sortType(type.ofType));
|
||||
}
|
||||
|
||||
return sortNamedType(type);
|
||||
}
|
||||
|
||||
function sortTypes(arr) {
|
||||
return sortByName(arr).map(sortNamedType);
|
||||
}
|
||||
|
||||
function sortNamedType(type) {
|
||||
if (isSpecifiedScalarType(type) || isIntrospectionType(type)) {
|
||||
return type;
|
||||
}
|
||||
|
||||
var sortedType = cache[type.name];
|
||||
|
||||
if (!sortedType) {
|
||||
sortedType = sortNamedTypeImpl(type);
|
||||
cache[type.name] = sortedType;
|
||||
}
|
||||
|
||||
return sortedType;
|
||||
}
|
||||
|
||||
function sortNamedTypeImpl(type) {
|
||||
if (isScalarType(type)) {
|
||||
return type;
|
||||
} else if (isObjectType(type)) {
|
||||
return new GraphQLObjectType({
|
||||
name: type.name,
|
||||
interfaces: function interfaces() {
|
||||
return sortTypes(type.getInterfaces());
|
||||
},
|
||||
fields: function fields() {
|
||||
return sortFields(type.getFields());
|
||||
},
|
||||
isTypeOf: type.isTypeOf,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: type.extensionASTNodes
|
||||
});
|
||||
} else if (isInterfaceType(type)) {
|
||||
return new GraphQLInterfaceType({
|
||||
name: type.name,
|
||||
fields: function fields() {
|
||||
return sortFields(type.getFields());
|
||||
},
|
||||
resolveType: type.resolveType,
|
||||
description: type.description,
|
||||
astNode: type.astNode,
|
||||
extensionASTNodes: type.extensionASTNodes
|
||||
});
|
||||
} else if (isUnionType(type)) {
|
||||
return new GraphQLUnionType({
|
||||
name: type.name,
|
||||
types: function types() {
|
||||
return sortTypes(type.getTypes());
|
||||
},
|
||||
resolveType: type.resolveType,
|
||||
description: type.description,
|
||||
astNode: type.astNode
|
||||
});
|
||||
} else if (isEnumType(type)) {
|
||||
return new GraphQLEnumType({
|
||||
name: type.name,
|
||||
values: keyValMap(sortByName(type.getValues()), function (val) {
|
||||
return val.name;
|
||||
}, function (val) {
|
||||
return {
|
||||
value: val.value,
|
||||
deprecationReason: val.deprecationReason,
|
||||
description: val.description,
|
||||
astNode: val.astNode
|
||||
};
|
||||
}),
|
||||
description: type.description,
|
||||
astNode: type.astNode
|
||||
});
|
||||
} else if (isInputObjectType(type)) {
|
||||
return new GraphQLInputObjectType({
|
||||
name: type.name,
|
||||
fields: function fields() {
|
||||
return sortInputFields(type.getFields());
|
||||
},
|
||||
description: type.description,
|
||||
astNode: type.astNode
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error("Unknown type: \"".concat(type, "\""));
|
||||
}
|
||||
}
|
||||
|
||||
function sortObjMap(map, sortValueFn) {
|
||||
var sortedMap = Object.create(null);
|
||||
var sortedKeys = sortBy(Object.keys(map), function (x) {
|
||||
return x;
|
||||
});
|
||||
|
||||
for (var _i = 0; _i < sortedKeys.length; _i++) {
|
||||
var key = sortedKeys[_i];
|
||||
var value = map[key];
|
||||
sortedMap[key] = sortValueFn ? sortValueFn(value) : value;
|
||||
}
|
||||
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
function sortByName(array) {
|
||||
return sortBy(array, function (obj) {
|
||||
return obj.name;
|
||||
});
|
||||
}
|
||||
|
||||
function sortBy(array, mapToKey) {
|
||||
return array.slice().sort(function (obj1, obj2) {
|
||||
var key1 = mapToKey(obj1);
|
||||
var key2 = mapToKey(obj2);
|
||||
return key1.localeCompare(key2);
|
||||
});
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.printSchema = printSchema;
|
||||
exports.printIntrospectionSchema = printIntrospectionSchema;
|
||||
exports.printType = printType;
|
||||
|
||||
var _isNullish = _interopRequireDefault(require("../jsutils/isNullish"));
|
||||
|
||||
var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
|
||||
|
||||
var _objectValues = _interopRequireDefault(require("../jsutils/objectValues"));
|
||||
|
||||
var _astFromValue = require("../utilities/astFromValue");
|
||||
|
||||
var _printer = require("../language/printer");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
var _scalars = require("../type/scalars");
|
||||
|
||||
var _directives = require("../type/directives");
|
||||
|
||||
var _introspection = require("../type/introspection");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
function printSchema(schema, options) {
|
||||
return printFilteredSchema(schema, function (n) {
|
||||
return !(0, _directives.isSpecifiedDirective)(n);
|
||||
}, isDefinedType, options);
|
||||
}
|
||||
|
||||
function printIntrospectionSchema(schema, options) {
|
||||
return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType, options);
|
||||
}
|
||||
|
||||
function isDefinedType(type) {
|
||||
return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type);
|
||||
}
|
||||
|
||||
function printFilteredSchema(schema, directiveFilter, typeFilter, options) {
|
||||
var directives = schema.getDirectives().filter(directiveFilter);
|
||||
var typeMap = schema.getTypeMap();
|
||||
var types = (0, _objectValues.default)(typeMap).sort(function (type1, type2) {
|
||||
return type1.name.localeCompare(type2.name);
|
||||
}).filter(typeFilter);
|
||||
return [printSchemaDefinition(schema)].concat(directives.map(function (directive) {
|
||||
return printDirective(directive, options);
|
||||
}), types.map(function (type) {
|
||||
return printType(type, options);
|
||||
})).filter(Boolean).join('\n\n') + '\n';
|
||||
}
|
||||
|
||||
function printSchemaDefinition(schema) {
|
||||
if (isSchemaOfCommonNames(schema)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var operationTypes = [];
|
||||
var queryType = schema.getQueryType();
|
||||
|
||||
if (queryType) {
|
||||
operationTypes.push(" query: ".concat(queryType.name));
|
||||
}
|
||||
|
||||
var mutationType = schema.getMutationType();
|
||||
|
||||
if (mutationType) {
|
||||
operationTypes.push(" mutation: ".concat(mutationType.name));
|
||||
}
|
||||
|
||||
var subscriptionType = schema.getSubscriptionType();
|
||||
|
||||
if (subscriptionType) {
|
||||
operationTypes.push(" subscription: ".concat(subscriptionType.name));
|
||||
}
|
||||
|
||||
return "schema {\n".concat(operationTypes.join('\n'), "\n}");
|
||||
}
|
||||
/**
|
||||
* GraphQL schema define root types for each type of operation. These types are
|
||||
* the same as any other type and can be named in any manner, however there is
|
||||
* a common naming convention:
|
||||
*
|
||||
* schema {
|
||||
* query: Query
|
||||
* mutation: Mutation
|
||||
* }
|
||||
*
|
||||
* When using this naming convention, the schema description can be omitted.
|
||||
*/
|
||||
|
||||
|
||||
function isSchemaOfCommonNames(schema) {
|
||||
var queryType = schema.getQueryType();
|
||||
|
||||
if (queryType && queryType.name !== 'Query') {
|
||||
return false;
|
||||
}
|
||||
|
||||
var mutationType = schema.getMutationType();
|
||||
|
||||
if (mutationType && mutationType.name !== 'Mutation') {
|
||||
return false;
|
||||
}
|
||||
|
||||
var subscriptionType = schema.getSubscriptionType();
|
||||
|
||||
if (subscriptionType && subscriptionType.name !== 'Subscription') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function printType(type, options) {
|
||||
if ((0, _definition.isScalarType)(type)) {
|
||||
return printScalar(type, options);
|
||||
} else if ((0, _definition.isObjectType)(type)) {
|
||||
return printObject(type, options);
|
||||
} else if ((0, _definition.isInterfaceType)(type)) {
|
||||
return printInterface(type, options);
|
||||
} else if ((0, _definition.isUnionType)(type)) {
|
||||
return printUnion(type, options);
|
||||
} else if ((0, _definition.isEnumType)(type)) {
|
||||
return printEnum(type, options);
|
||||
} else if ((0, _definition.isInputObjectType)(type)) {
|
||||
return printInputObject(type, options);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unknown type: ".concat(type, "."));
|
||||
}
|
||||
|
||||
function printScalar(type, options) {
|
||||
return printDescription(options, type) + "scalar ".concat(type.name);
|
||||
}
|
||||
|
||||
function printObject(type, options) {
|
||||
var interfaces = type.getInterfaces();
|
||||
var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) {
|
||||
return i.name;
|
||||
}).join(' & ') : '';
|
||||
return printDescription(options, type) + "type ".concat(type.name).concat(implementedInterfaces, " {\n") + printFields(options, type) + '\n' + '}';
|
||||
}
|
||||
|
||||
function printInterface(type, options) {
|
||||
return printDescription(options, type) + "interface ".concat(type.name, " {\n") + printFields(options, type) + '\n' + '}';
|
||||
}
|
||||
|
||||
function printUnion(type, options) {
|
||||
return printDescription(options, type) + "union ".concat(type.name, " = ").concat(type.getTypes().join(' | '));
|
||||
}
|
||||
|
||||
function printEnum(type, options) {
|
||||
return printDescription(options, type) + "enum ".concat(type.name, " {\n") + printEnumValues(type.getValues(), options) + '\n' + '}';
|
||||
}
|
||||
|
||||
function printEnumValues(values, options) {
|
||||
return values.map(function (value, i) {
|
||||
return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
function printInputObject(type, options) {
|
||||
var fields = (0, _objectValues.default)(type.getFields());
|
||||
return printDescription(options, type) + "input ".concat(type.name, " {\n") + fields.map(function (f, i) {
|
||||
return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f);
|
||||
}).join('\n') + '\n' + '}';
|
||||
}
|
||||
|
||||
function printFields(options, type) {
|
||||
var fields = (0, _objectValues.default)(type.getFields());
|
||||
return fields.map(function (f, i) {
|
||||
return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
function printArgs(options, args) {
|
||||
var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
|
||||
|
||||
if (args.length === 0) {
|
||||
return '';
|
||||
} // If every arg does not have a description, print them on one line.
|
||||
|
||||
|
||||
if (args.every(function (arg) {
|
||||
return !arg.description;
|
||||
})) {
|
||||
return '(' + args.map(printInputValue).join(', ') + ')';
|
||||
}
|
||||
|
||||
return '(\n' + args.map(function (arg, i) {
|
||||
return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg);
|
||||
}).join('\n') + '\n' + indentation + ')';
|
||||
}
|
||||
|
||||
function printInputValue(arg) {
|
||||
var argDecl = arg.name + ': ' + String(arg.type);
|
||||
|
||||
if (!(0, _isInvalid.default)(arg.defaultValue)) {
|
||||
argDecl += " = ".concat((0, _printer.print)((0, _astFromValue.astFromValue)(arg.defaultValue, arg.type)));
|
||||
}
|
||||
|
||||
return argDecl;
|
||||
}
|
||||
|
||||
function printDirective(directive, options) {
|
||||
return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + ' on ' + directive.locations.join(' | ');
|
||||
}
|
||||
|
||||
function printDeprecated(fieldOrEnumVal) {
|
||||
if (!fieldOrEnumVal.isDeprecated) {
|
||||
return '';
|
||||
}
|
||||
|
||||
var reason = fieldOrEnumVal.deprecationReason;
|
||||
|
||||
if ((0, _isNullish.default)(reason) || reason === '' || reason === _directives.DEFAULT_DEPRECATION_REASON) {
|
||||
return ' @deprecated';
|
||||
}
|
||||
|
||||
return ' @deprecated(reason: ' + (0, _printer.print)((0, _astFromValue.astFromValue)(reason, _scalars.GraphQLString)) + ')';
|
||||
}
|
||||
|
||||
function printDescription(options, def) {
|
||||
var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
|
||||
var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
|
||||
|
||||
if (!def.description) {
|
||||
return '';
|
||||
}
|
||||
|
||||
var lines = descriptionLines(def.description, 120 - indentation.length);
|
||||
|
||||
if (options && options.commentDescriptions) {
|
||||
return printDescriptionWithComments(lines, indentation, firstInBlock);
|
||||
}
|
||||
|
||||
var description = indentation && !firstInBlock ? '\n' + indentation + '"""' : indentation + '"""'; // In some circumstances, a single line can be used for the description.
|
||||
|
||||
if (lines.length === 1 && lines[0].length < 70 && lines[0][lines[0].length - 1] !== '"') {
|
||||
return description + escapeQuote(lines[0]) + '"""\n';
|
||||
} // Format a multi-line block quote to account for leading space.
|
||||
|
||||
|
||||
var hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t';
|
||||
|
||||
if (!hasLeadingSpace) {
|
||||
description += '\n';
|
||||
}
|
||||
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
if (i !== 0 || !hasLeadingSpace) {
|
||||
description += indentation;
|
||||
}
|
||||
|
||||
description += escapeQuote(lines[i]) + '\n';
|
||||
}
|
||||
|
||||
description += indentation + '"""\n';
|
||||
return description;
|
||||
}
|
||||
|
||||
function escapeQuote(line) {
|
||||
return line.replace(/"""/g, '\\"""');
|
||||
}
|
||||
|
||||
function printDescriptionWithComments(lines, indentation, firstInBlock) {
|
||||
var description = indentation && !firstInBlock ? '\n' : '';
|
||||
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
if (lines[i] === '') {
|
||||
description += indentation + '#\n';
|
||||
} else {
|
||||
description += indentation + '# ' + lines[i] + '\n';
|
||||
}
|
||||
}
|
||||
|
||||
return description;
|
||||
}
|
||||
|
||||
function descriptionLines(description, maxLen) {
|
||||
var lines = [];
|
||||
var rawLines = description.split('\n');
|
||||
|
||||
for (var i = 0; i < rawLines.length; i++) {
|
||||
if (rawLines[i] === '') {
|
||||
lines.push(rawLines[i]);
|
||||
} else {
|
||||
// For > 120 character long lines, cut at space boundaries into sublines
|
||||
// of ~80 chars.
|
||||
var sublines = breakLine(rawLines[i], maxLen);
|
||||
|
||||
for (var j = 0; j < sublines.length; j++) {
|
||||
lines.push(sublines[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
function breakLine(line, maxLen) {
|
||||
if (line.length < maxLen + 5) {
|
||||
return [line];
|
||||
}
|
||||
|
||||
var parts = line.split(new RegExp("((?: |^).{15,".concat(maxLen - 40, "}(?= |$))")));
|
||||
|
||||
if (parts.length < 4) {
|
||||
return [line];
|
||||
}
|
||||
|
||||
var sublines = [parts[0] + parts[1] + parts[2]];
|
||||
|
||||
for (var i = 3; i < parts.length; i += 2) {
|
||||
sublines.push(parts[i].slice(1) + parts[i + 1]);
|
||||
}
|
||||
|
||||
return sublines;
|
||||
}
|
||||
+425
@@ -0,0 +1,425 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import isNullish from '../jsutils/isNullish';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import { astFromValue } from '../utilities/astFromValue';
|
||||
import { print } from '../language/printer';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
import {
|
||||
isScalarType,
|
||||
isObjectType,
|
||||
isInterfaceType,
|
||||
isUnionType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
} from '../type/definition';
|
||||
import type {
|
||||
GraphQLNamedType,
|
||||
GraphQLScalarType,
|
||||
GraphQLEnumType,
|
||||
GraphQLObjectType,
|
||||
GraphQLInterfaceType,
|
||||
GraphQLUnionType,
|
||||
GraphQLInputObjectType,
|
||||
} from '../type/definition';
|
||||
import { GraphQLString, isSpecifiedScalarType } from '../type/scalars';
|
||||
import {
|
||||
GraphQLDirective,
|
||||
DEFAULT_DEPRECATION_REASON,
|
||||
isSpecifiedDirective,
|
||||
} from '../type/directives';
|
||||
import { isIntrospectionType } from '../type/introspection';
|
||||
|
||||
type Options = {|
|
||||
/**
|
||||
* Descriptions are defined as preceding string literals, however an older
|
||||
* experimental version of the SDL supported preceding comments as
|
||||
* descriptions. Set to true to enable this deprecated behavior.
|
||||
* This option is provided to ease adoption and will be removed in v16.
|
||||
*
|
||||
* Default: false
|
||||
*/
|
||||
commentDescriptions?: boolean,
|
||||
|};
|
||||
|
||||
/**
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
export function printSchema(schema: GraphQLSchema, options?: Options): string {
|
||||
return printFilteredSchema(
|
||||
schema,
|
||||
n => !isSpecifiedDirective(n),
|
||||
isDefinedType,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
export function printIntrospectionSchema(
|
||||
schema: GraphQLSchema,
|
||||
options?: Options,
|
||||
): string {
|
||||
return printFilteredSchema(
|
||||
schema,
|
||||
isSpecifiedDirective,
|
||||
isIntrospectionType,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
function isDefinedType(type: GraphQLNamedType): boolean {
|
||||
return !isSpecifiedScalarType(type) && !isIntrospectionType(type);
|
||||
}
|
||||
|
||||
function printFilteredSchema(
|
||||
schema: GraphQLSchema,
|
||||
directiveFilter: (type: GraphQLDirective) => boolean,
|
||||
typeFilter: (type: GraphQLNamedType) => boolean,
|
||||
options,
|
||||
): string {
|
||||
const directives = schema.getDirectives().filter(directiveFilter);
|
||||
const typeMap = schema.getTypeMap();
|
||||
const types = objectValues(typeMap)
|
||||
.sort((type1, type2) => type1.name.localeCompare(type2.name))
|
||||
.filter(typeFilter);
|
||||
|
||||
return (
|
||||
[printSchemaDefinition(schema)]
|
||||
.concat(
|
||||
directives.map(directive => printDirective(directive, options)),
|
||||
types.map(type => printType(type, options)),
|
||||
)
|
||||
.filter(Boolean)
|
||||
.join('\n\n') + '\n'
|
||||
);
|
||||
}
|
||||
|
||||
function printSchemaDefinition(schema: GraphQLSchema): ?string {
|
||||
if (isSchemaOfCommonNames(schema)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const operationTypes = [];
|
||||
|
||||
const queryType = schema.getQueryType();
|
||||
if (queryType) {
|
||||
operationTypes.push(` query: ${queryType.name}`);
|
||||
}
|
||||
|
||||
const mutationType = schema.getMutationType();
|
||||
if (mutationType) {
|
||||
operationTypes.push(` mutation: ${mutationType.name}`);
|
||||
}
|
||||
|
||||
const subscriptionType = schema.getSubscriptionType();
|
||||
if (subscriptionType) {
|
||||
operationTypes.push(` subscription: ${subscriptionType.name}`);
|
||||
}
|
||||
|
||||
return `schema {\n${operationTypes.join('\n')}\n}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* GraphQL schema define root types for each type of operation. These types are
|
||||
* the same as any other type and can be named in any manner, however there is
|
||||
* a common naming convention:
|
||||
*
|
||||
* schema {
|
||||
* query: Query
|
||||
* mutation: Mutation
|
||||
* }
|
||||
*
|
||||
* When using this naming convention, the schema description can be omitted.
|
||||
*/
|
||||
function isSchemaOfCommonNames(schema: GraphQLSchema): boolean {
|
||||
const queryType = schema.getQueryType();
|
||||
if (queryType && queryType.name !== 'Query') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const mutationType = schema.getMutationType();
|
||||
if (mutationType && mutationType.name !== 'Mutation') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const subscriptionType = schema.getSubscriptionType();
|
||||
if (subscriptionType && subscriptionType.name !== 'Subscription') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function printType(type: GraphQLNamedType, options?: Options): string {
|
||||
if (isScalarType(type)) {
|
||||
return printScalar(type, options);
|
||||
} else if (isObjectType(type)) {
|
||||
return printObject(type, options);
|
||||
} else if (isInterfaceType(type)) {
|
||||
return printInterface(type, options);
|
||||
} else if (isUnionType(type)) {
|
||||
return printUnion(type, options);
|
||||
} else if (isEnumType(type)) {
|
||||
return printEnum(type, options);
|
||||
} else if (isInputObjectType(type)) {
|
||||
return printInputObject(type, options);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
throw new Error(`Unknown type: ${(type: empty)}.`);
|
||||
}
|
||||
|
||||
function printScalar(type: GraphQLScalarType, options): string {
|
||||
return printDescription(options, type) + `scalar ${type.name}`;
|
||||
}
|
||||
|
||||
function printObject(type: GraphQLObjectType, options): string {
|
||||
const interfaces = type.getInterfaces();
|
||||
const implementedInterfaces = interfaces.length
|
||||
? ' implements ' + interfaces.map(i => i.name).join(' & ')
|
||||
: '';
|
||||
return (
|
||||
printDescription(options, type) +
|
||||
`type ${type.name}${implementedInterfaces} {\n` +
|
||||
printFields(options, type) +
|
||||
'\n' +
|
||||
'}'
|
||||
);
|
||||
}
|
||||
|
||||
function printInterface(type: GraphQLInterfaceType, options): string {
|
||||
return (
|
||||
printDescription(options, type) +
|
||||
`interface ${type.name} {\n` +
|
||||
printFields(options, type) +
|
||||
'\n' +
|
||||
'}'
|
||||
);
|
||||
}
|
||||
|
||||
function printUnion(type: GraphQLUnionType, options): string {
|
||||
return (
|
||||
printDescription(options, type) +
|
||||
`union ${type.name} = ${type.getTypes().join(' | ')}`
|
||||
);
|
||||
}
|
||||
|
||||
function printEnum(type: GraphQLEnumType, options): string {
|
||||
return (
|
||||
printDescription(options, type) +
|
||||
`enum ${type.name} {\n` +
|
||||
printEnumValues(type.getValues(), options) +
|
||||
'\n' +
|
||||
'}'
|
||||
);
|
||||
}
|
||||
|
||||
function printEnumValues(values, options): string {
|
||||
return values
|
||||
.map(
|
||||
(value, i) =>
|
||||
printDescription(options, value, ' ', !i) +
|
||||
' ' +
|
||||
value.name +
|
||||
printDeprecated(value),
|
||||
)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function printInputObject(type: GraphQLInputObjectType, options): string {
|
||||
const fields = objectValues(type.getFields());
|
||||
return (
|
||||
printDescription(options, type) +
|
||||
`input ${type.name} {\n` +
|
||||
fields
|
||||
.map(
|
||||
(f, i) =>
|
||||
printDescription(options, f, ' ', !i) + ' ' + printInputValue(f),
|
||||
)
|
||||
.join('\n') +
|
||||
'\n' +
|
||||
'}'
|
||||
);
|
||||
}
|
||||
|
||||
function printFields(options, type) {
|
||||
const fields = objectValues(type.getFields());
|
||||
return fields
|
||||
.map(
|
||||
(f, i) =>
|
||||
printDescription(options, f, ' ', !i) +
|
||||
' ' +
|
||||
f.name +
|
||||
printArgs(options, f.args, ' ') +
|
||||
': ' +
|
||||
String(f.type) +
|
||||
printDeprecated(f),
|
||||
)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function printArgs(options, args, indentation = '') {
|
||||
if (args.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// If every arg does not have a description, print them on one line.
|
||||
if (args.every(arg => !arg.description)) {
|
||||
return '(' + args.map(printInputValue).join(', ') + ')';
|
||||
}
|
||||
|
||||
return (
|
||||
'(\n' +
|
||||
args
|
||||
.map(
|
||||
(arg, i) =>
|
||||
printDescription(options, arg, ' ' + indentation, !i) +
|
||||
' ' +
|
||||
indentation +
|
||||
printInputValue(arg),
|
||||
)
|
||||
.join('\n') +
|
||||
'\n' +
|
||||
indentation +
|
||||
')'
|
||||
);
|
||||
}
|
||||
|
||||
function printInputValue(arg) {
|
||||
let argDecl = arg.name + ': ' + String(arg.type);
|
||||
if (!isInvalid(arg.defaultValue)) {
|
||||
argDecl += ` = ${print(astFromValue(arg.defaultValue, arg.type))}`;
|
||||
}
|
||||
return argDecl;
|
||||
}
|
||||
|
||||
function printDirective(directive, options) {
|
||||
return (
|
||||
printDescription(options, directive) +
|
||||
'directive @' +
|
||||
directive.name +
|
||||
printArgs(options, directive.args) +
|
||||
' on ' +
|
||||
directive.locations.join(' | ')
|
||||
);
|
||||
}
|
||||
|
||||
function printDeprecated(fieldOrEnumVal) {
|
||||
if (!fieldOrEnumVal.isDeprecated) {
|
||||
return '';
|
||||
}
|
||||
const reason = fieldOrEnumVal.deprecationReason;
|
||||
if (
|
||||
isNullish(reason) ||
|
||||
reason === '' ||
|
||||
reason === DEFAULT_DEPRECATION_REASON
|
||||
) {
|
||||
return ' @deprecated';
|
||||
}
|
||||
return (
|
||||
' @deprecated(reason: ' + print(astFromValue(reason, GraphQLString)) + ')'
|
||||
);
|
||||
}
|
||||
|
||||
function printDescription(
|
||||
options,
|
||||
def,
|
||||
indentation = '',
|
||||
firstInBlock = true,
|
||||
): string {
|
||||
if (!def.description) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const lines = descriptionLines(def.description, 120 - indentation.length);
|
||||
if (options && options.commentDescriptions) {
|
||||
return printDescriptionWithComments(lines, indentation, firstInBlock);
|
||||
}
|
||||
|
||||
let description =
|
||||
indentation && !firstInBlock
|
||||
? '\n' + indentation + '"""'
|
||||
: indentation + '"""';
|
||||
|
||||
// In some circumstances, a single line can be used for the description.
|
||||
if (
|
||||
lines.length === 1 &&
|
||||
lines[0].length < 70 &&
|
||||
lines[0][lines[0].length - 1] !== '"'
|
||||
) {
|
||||
return description + escapeQuote(lines[0]) + '"""\n';
|
||||
}
|
||||
|
||||
// Format a multi-line block quote to account for leading space.
|
||||
const hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t';
|
||||
if (!hasLeadingSpace) {
|
||||
description += '\n';
|
||||
}
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (i !== 0 || !hasLeadingSpace) {
|
||||
description += indentation;
|
||||
}
|
||||
description += escapeQuote(lines[i]) + '\n';
|
||||
}
|
||||
description += indentation + '"""\n';
|
||||
return description;
|
||||
}
|
||||
|
||||
function escapeQuote(line) {
|
||||
return line.replace(/"""/g, '\\"""');
|
||||
}
|
||||
|
||||
function printDescriptionWithComments(lines, indentation, firstInBlock) {
|
||||
let description = indentation && !firstInBlock ? '\n' : '';
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (lines[i] === '') {
|
||||
description += indentation + '#\n';
|
||||
} else {
|
||||
description += indentation + '# ' + lines[i] + '\n';
|
||||
}
|
||||
}
|
||||
return description;
|
||||
}
|
||||
|
||||
function descriptionLines(description: string, maxLen: number): Array<string> {
|
||||
const lines = [];
|
||||
const rawLines = description.split('\n');
|
||||
for (let i = 0; i < rawLines.length; i++) {
|
||||
if (rawLines[i] === '') {
|
||||
lines.push(rawLines[i]);
|
||||
} else {
|
||||
// For > 120 character long lines, cut at space boundaries into sublines
|
||||
// of ~80 chars.
|
||||
const sublines = breakLine(rawLines[i], maxLen);
|
||||
for (let j = 0; j < sublines.length; j++) {
|
||||
lines.push(sublines[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function breakLine(line: string, maxLen: number): Array<string> {
|
||||
if (line.length < maxLen + 5) {
|
||||
return [line];
|
||||
}
|
||||
const parts = line.split(new RegExp(`((?: |^).{15,${maxLen - 40}}(?= |$))`));
|
||||
if (parts.length < 4) {
|
||||
return [line];
|
||||
}
|
||||
const sublines = [parts[0] + parts[1] + parts[2]];
|
||||
for (let i = 3; i < parts.length; i += 2) {
|
||||
sublines.push(parts[i].slice(1) + parts[i + 1]);
|
||||
}
|
||||
return sublines;
|
||||
}
|
||||
+321
@@ -0,0 +1,321 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import isNullish from '../jsutils/isNullish';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import { astFromValue } from '../utilities/astFromValue';
|
||||
import { print } from '../language/printer';
|
||||
import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from '../type/definition';
|
||||
import { GraphQLString, isSpecifiedScalarType } from '../type/scalars';
|
||||
import { GraphQLDirective, DEFAULT_DEPRECATION_REASON, isSpecifiedDirective } from '../type/directives';
|
||||
import { isIntrospectionType } from '../type/introspection';
|
||||
|
||||
/**
|
||||
* Accepts options as a second argument:
|
||||
*
|
||||
* - commentDescriptions:
|
||||
* Provide true to use preceding comments as the description.
|
||||
*
|
||||
*/
|
||||
export function printSchema(schema, options) {
|
||||
return printFilteredSchema(schema, function (n) {
|
||||
return !isSpecifiedDirective(n);
|
||||
}, isDefinedType, options);
|
||||
}
|
||||
export function printIntrospectionSchema(schema, options) {
|
||||
return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType, options);
|
||||
}
|
||||
|
||||
function isDefinedType(type) {
|
||||
return !isSpecifiedScalarType(type) && !isIntrospectionType(type);
|
||||
}
|
||||
|
||||
function printFilteredSchema(schema, directiveFilter, typeFilter, options) {
|
||||
var directives = schema.getDirectives().filter(directiveFilter);
|
||||
var typeMap = schema.getTypeMap();
|
||||
var types = objectValues(typeMap).sort(function (type1, type2) {
|
||||
return type1.name.localeCompare(type2.name);
|
||||
}).filter(typeFilter);
|
||||
return [printSchemaDefinition(schema)].concat(directives.map(function (directive) {
|
||||
return printDirective(directive, options);
|
||||
}), types.map(function (type) {
|
||||
return printType(type, options);
|
||||
})).filter(Boolean).join('\n\n') + '\n';
|
||||
}
|
||||
|
||||
function printSchemaDefinition(schema) {
|
||||
if (isSchemaOfCommonNames(schema)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var operationTypes = [];
|
||||
var queryType = schema.getQueryType();
|
||||
|
||||
if (queryType) {
|
||||
operationTypes.push(" query: ".concat(queryType.name));
|
||||
}
|
||||
|
||||
var mutationType = schema.getMutationType();
|
||||
|
||||
if (mutationType) {
|
||||
operationTypes.push(" mutation: ".concat(mutationType.name));
|
||||
}
|
||||
|
||||
var subscriptionType = schema.getSubscriptionType();
|
||||
|
||||
if (subscriptionType) {
|
||||
operationTypes.push(" subscription: ".concat(subscriptionType.name));
|
||||
}
|
||||
|
||||
return "schema {\n".concat(operationTypes.join('\n'), "\n}");
|
||||
}
|
||||
/**
|
||||
* GraphQL schema define root types for each type of operation. These types are
|
||||
* the same as any other type and can be named in any manner, however there is
|
||||
* a common naming convention:
|
||||
*
|
||||
* schema {
|
||||
* query: Query
|
||||
* mutation: Mutation
|
||||
* }
|
||||
*
|
||||
* When using this naming convention, the schema description can be omitted.
|
||||
*/
|
||||
|
||||
|
||||
function isSchemaOfCommonNames(schema) {
|
||||
var queryType = schema.getQueryType();
|
||||
|
||||
if (queryType && queryType.name !== 'Query') {
|
||||
return false;
|
||||
}
|
||||
|
||||
var mutationType = schema.getMutationType();
|
||||
|
||||
if (mutationType && mutationType.name !== 'Mutation') {
|
||||
return false;
|
||||
}
|
||||
|
||||
var subscriptionType = schema.getSubscriptionType();
|
||||
|
||||
if (subscriptionType && subscriptionType.name !== 'Subscription') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function printType(type, options) {
|
||||
if (isScalarType(type)) {
|
||||
return printScalar(type, options);
|
||||
} else if (isObjectType(type)) {
|
||||
return printObject(type, options);
|
||||
} else if (isInterfaceType(type)) {
|
||||
return printInterface(type, options);
|
||||
} else if (isUnionType(type)) {
|
||||
return printUnion(type, options);
|
||||
} else if (isEnumType(type)) {
|
||||
return printEnum(type, options);
|
||||
} else if (isInputObjectType(type)) {
|
||||
return printInputObject(type, options);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unknown type: ".concat(type, "."));
|
||||
}
|
||||
|
||||
function printScalar(type, options) {
|
||||
return printDescription(options, type) + "scalar ".concat(type.name);
|
||||
}
|
||||
|
||||
function printObject(type, options) {
|
||||
var interfaces = type.getInterfaces();
|
||||
var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) {
|
||||
return i.name;
|
||||
}).join(' & ') : '';
|
||||
return printDescription(options, type) + "type ".concat(type.name).concat(implementedInterfaces, " {\n") + printFields(options, type) + '\n' + '}';
|
||||
}
|
||||
|
||||
function printInterface(type, options) {
|
||||
return printDescription(options, type) + "interface ".concat(type.name, " {\n") + printFields(options, type) + '\n' + '}';
|
||||
}
|
||||
|
||||
function printUnion(type, options) {
|
||||
return printDescription(options, type) + "union ".concat(type.name, " = ").concat(type.getTypes().join(' | '));
|
||||
}
|
||||
|
||||
function printEnum(type, options) {
|
||||
return printDescription(options, type) + "enum ".concat(type.name, " {\n") + printEnumValues(type.getValues(), options) + '\n' + '}';
|
||||
}
|
||||
|
||||
function printEnumValues(values, options) {
|
||||
return values.map(function (value, i) {
|
||||
return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
function printInputObject(type, options) {
|
||||
var fields = objectValues(type.getFields());
|
||||
return printDescription(options, type) + "input ".concat(type.name, " {\n") + fields.map(function (f, i) {
|
||||
return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f);
|
||||
}).join('\n') + '\n' + '}';
|
||||
}
|
||||
|
||||
function printFields(options, type) {
|
||||
var fields = objectValues(type.getFields());
|
||||
return fields.map(function (f, i) {
|
||||
return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
function printArgs(options, args) {
|
||||
var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
|
||||
|
||||
if (args.length === 0) {
|
||||
return '';
|
||||
} // If every arg does not have a description, print them on one line.
|
||||
|
||||
|
||||
if (args.every(function (arg) {
|
||||
return !arg.description;
|
||||
})) {
|
||||
return '(' + args.map(printInputValue).join(', ') + ')';
|
||||
}
|
||||
|
||||
return '(\n' + args.map(function (arg, i) {
|
||||
return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg);
|
||||
}).join('\n') + '\n' + indentation + ')';
|
||||
}
|
||||
|
||||
function printInputValue(arg) {
|
||||
var argDecl = arg.name + ': ' + String(arg.type);
|
||||
|
||||
if (!isInvalid(arg.defaultValue)) {
|
||||
argDecl += " = ".concat(print(astFromValue(arg.defaultValue, arg.type)));
|
||||
}
|
||||
|
||||
return argDecl;
|
||||
}
|
||||
|
||||
function printDirective(directive, options) {
|
||||
return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + ' on ' + directive.locations.join(' | ');
|
||||
}
|
||||
|
||||
function printDeprecated(fieldOrEnumVal) {
|
||||
if (!fieldOrEnumVal.isDeprecated) {
|
||||
return '';
|
||||
}
|
||||
|
||||
var reason = fieldOrEnumVal.deprecationReason;
|
||||
|
||||
if (isNullish(reason) || reason === '' || reason === DEFAULT_DEPRECATION_REASON) {
|
||||
return ' @deprecated';
|
||||
}
|
||||
|
||||
return ' @deprecated(reason: ' + print(astFromValue(reason, GraphQLString)) + ')';
|
||||
}
|
||||
|
||||
function printDescription(options, def) {
|
||||
var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
|
||||
var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
|
||||
|
||||
if (!def.description) {
|
||||
return '';
|
||||
}
|
||||
|
||||
var lines = descriptionLines(def.description, 120 - indentation.length);
|
||||
|
||||
if (options && options.commentDescriptions) {
|
||||
return printDescriptionWithComments(lines, indentation, firstInBlock);
|
||||
}
|
||||
|
||||
var description = indentation && !firstInBlock ? '\n' + indentation + '"""' : indentation + '"""'; // In some circumstances, a single line can be used for the description.
|
||||
|
||||
if (lines.length === 1 && lines[0].length < 70 && lines[0][lines[0].length - 1] !== '"') {
|
||||
return description + escapeQuote(lines[0]) + '"""\n';
|
||||
} // Format a multi-line block quote to account for leading space.
|
||||
|
||||
|
||||
var hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t';
|
||||
|
||||
if (!hasLeadingSpace) {
|
||||
description += '\n';
|
||||
}
|
||||
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
if (i !== 0 || !hasLeadingSpace) {
|
||||
description += indentation;
|
||||
}
|
||||
|
||||
description += escapeQuote(lines[i]) + '\n';
|
||||
}
|
||||
|
||||
description += indentation + '"""\n';
|
||||
return description;
|
||||
}
|
||||
|
||||
function escapeQuote(line) {
|
||||
return line.replace(/"""/g, '\\"""');
|
||||
}
|
||||
|
||||
function printDescriptionWithComments(lines, indentation, firstInBlock) {
|
||||
var description = indentation && !firstInBlock ? '\n' : '';
|
||||
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
if (lines[i] === '') {
|
||||
description += indentation + '#\n';
|
||||
} else {
|
||||
description += indentation + '# ' + lines[i] + '\n';
|
||||
}
|
||||
}
|
||||
|
||||
return description;
|
||||
}
|
||||
|
||||
function descriptionLines(description, maxLen) {
|
||||
var lines = [];
|
||||
var rawLines = description.split('\n');
|
||||
|
||||
for (var i = 0; i < rawLines.length; i++) {
|
||||
if (rawLines[i] === '') {
|
||||
lines.push(rawLines[i]);
|
||||
} else {
|
||||
// For > 120 character long lines, cut at space boundaries into sublines
|
||||
// of ~80 chars.
|
||||
var sublines = breakLine(rawLines[i], maxLen);
|
||||
|
||||
for (var j = 0; j < sublines.length; j++) {
|
||||
lines.push(sublines[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
function breakLine(line, maxLen) {
|
||||
if (line.length < maxLen + 5) {
|
||||
return [line];
|
||||
}
|
||||
|
||||
var parts = line.split(new RegExp("((?: |^).{15,".concat(maxLen - 40, "}(?= |$))")));
|
||||
|
||||
if (parts.length < 4) {
|
||||
return [line];
|
||||
}
|
||||
|
||||
var sublines = [parts[0] + parts[1] + parts[2]];
|
||||
|
||||
for (var i = 3; i < parts.length; i += 2) {
|
||||
sublines.push(parts[i].slice(1) + parts[i + 1]);
|
||||
}
|
||||
|
||||
return sublines;
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.separateOperations = separateOperations;
|
||||
|
||||
var _visitor = require("../language/visitor");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* separateOperations accepts a single AST document which may contain many
|
||||
* operations and fragments and returns a collection of AST documents each of
|
||||
* which contains a single operation as well the fragment definitions it
|
||||
* refers to.
|
||||
*/
|
||||
function separateOperations(documentAST) {
|
||||
var operations = [];
|
||||
var fragments = Object.create(null);
|
||||
var positions = new Map();
|
||||
var depGraph = Object.create(null);
|
||||
var fromName;
|
||||
var idx = 0; // Populate metadata and build a dependency graph.
|
||||
|
||||
(0, _visitor.visit)(documentAST, {
|
||||
OperationDefinition: function OperationDefinition(node) {
|
||||
fromName = opName(node);
|
||||
operations.push(node);
|
||||
positions.set(node, idx++);
|
||||
},
|
||||
FragmentDefinition: function FragmentDefinition(node) {
|
||||
fromName = node.name.value;
|
||||
fragments[fromName] = node;
|
||||
positions.set(node, idx++);
|
||||
},
|
||||
FragmentSpread: function FragmentSpread(node) {
|
||||
var toName = node.name.value;
|
||||
(depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true;
|
||||
}
|
||||
}); // For each operation, produce a new synthesized AST which includes only what
|
||||
// is necessary for completing that operation.
|
||||
|
||||
var separatedDocumentASTs = Object.create(null);
|
||||
|
||||
for (var _i = 0; _i < operations.length; _i++) {
|
||||
var operation = operations[_i];
|
||||
var operationName = opName(operation);
|
||||
var dependencies = Object.create(null);
|
||||
collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted
|
||||
// to retain the same order as the original document.
|
||||
|
||||
var definitions = [operation];
|
||||
|
||||
var _arr = Object.keys(dependencies);
|
||||
|
||||
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
|
||||
var name = _arr[_i2];
|
||||
definitions.push(fragments[name]);
|
||||
}
|
||||
|
||||
definitions.sort(function (n1, n2) {
|
||||
return (positions.get(n1) || 0) - (positions.get(n2) || 0);
|
||||
});
|
||||
separatedDocumentASTs[operationName] = {
|
||||
kind: 'Document',
|
||||
definitions: definitions
|
||||
};
|
||||
}
|
||||
|
||||
return separatedDocumentASTs;
|
||||
}
|
||||
|
||||
// Provides the empty string for anonymous operations.
|
||||
function opName(operation) {
|
||||
return operation.name ? operation.name.value : '';
|
||||
} // From a dependency graph, collects a list of transitive dependencies by
|
||||
// recursing through a dependency graph.
|
||||
|
||||
|
||||
function collectTransitiveDependencies(collected, depGraph, fromName) {
|
||||
var immediateDeps = depGraph[fromName];
|
||||
|
||||
if (immediateDeps) {
|
||||
var _arr2 = Object.keys(immediateDeps);
|
||||
|
||||
for (var _i3 = 0; _i3 < _arr2.length; _i3++) {
|
||||
var toName = _arr2[_i3];
|
||||
|
||||
if (!collected[toName]) {
|
||||
collected[toName] = true;
|
||||
collectTransitiveDependencies(collected, depGraph, toName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { visit } from '../language/visitor';
|
||||
import type { ObjMap } from '../jsutils/ObjMap';
|
||||
import type { DocumentNode, OperationDefinitionNode } from '../language/ast';
|
||||
|
||||
/**
|
||||
* separateOperations accepts a single AST document which may contain many
|
||||
* operations and fragments and returns a collection of AST documents each of
|
||||
* which contains a single operation as well the fragment definitions it
|
||||
* refers to.
|
||||
*/
|
||||
export function separateOperations(
|
||||
documentAST: DocumentNode,
|
||||
): ObjMap<DocumentNode> {
|
||||
const operations = [];
|
||||
const fragments = Object.create(null);
|
||||
const positions = new Map();
|
||||
const depGraph: DepGraph = Object.create(null);
|
||||
let fromName;
|
||||
let idx = 0;
|
||||
|
||||
// Populate metadata and build a dependency graph.
|
||||
visit(documentAST, {
|
||||
OperationDefinition(node) {
|
||||
fromName = opName(node);
|
||||
operations.push(node);
|
||||
positions.set(node, idx++);
|
||||
},
|
||||
FragmentDefinition(node) {
|
||||
fromName = node.name.value;
|
||||
fragments[fromName] = node;
|
||||
positions.set(node, idx++);
|
||||
},
|
||||
FragmentSpread(node) {
|
||||
const toName = node.name.value;
|
||||
(depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[
|
||||
toName
|
||||
] = true;
|
||||
},
|
||||
});
|
||||
|
||||
// For each operation, produce a new synthesized AST which includes only what
|
||||
// is necessary for completing that operation.
|
||||
const separatedDocumentASTs = Object.create(null);
|
||||
for (const operation of operations) {
|
||||
const operationName = opName(operation);
|
||||
const dependencies = Object.create(null);
|
||||
collectTransitiveDependencies(dependencies, depGraph, operationName);
|
||||
|
||||
// The list of definition nodes to be included for this operation, sorted
|
||||
// to retain the same order as the original document.
|
||||
const definitions = [operation];
|
||||
for (const name of Object.keys(dependencies)) {
|
||||
definitions.push(fragments[name]);
|
||||
}
|
||||
definitions.sort(
|
||||
(n1, n2) => (positions.get(n1) || 0) - (positions.get(n2) || 0),
|
||||
);
|
||||
|
||||
separatedDocumentASTs[operationName] = {
|
||||
kind: 'Document',
|
||||
definitions,
|
||||
};
|
||||
}
|
||||
|
||||
return separatedDocumentASTs;
|
||||
}
|
||||
|
||||
type DepGraph = ObjMap<ObjMap<boolean>>;
|
||||
|
||||
// Provides the empty string for anonymous operations.
|
||||
function opName(operation: OperationDefinitionNode): string {
|
||||
return operation.name ? operation.name.value : '';
|
||||
}
|
||||
|
||||
// From a dependency graph, collects a list of transitive dependencies by
|
||||
// recursing through a dependency graph.
|
||||
function collectTransitiveDependencies(
|
||||
collected: ObjMap<boolean>,
|
||||
depGraph: DepGraph,
|
||||
fromName: string,
|
||||
): void {
|
||||
const immediateDeps = depGraph[fromName];
|
||||
if (immediateDeps) {
|
||||
for (const toName of Object.keys(immediateDeps)) {
|
||||
if (!collected[toName]) {
|
||||
collected[toName] = true;
|
||||
collectTransitiveDependencies(collected, depGraph, toName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { visit } from '../language/visitor';
|
||||
|
||||
/**
|
||||
* separateOperations accepts a single AST document which may contain many
|
||||
* operations and fragments and returns a collection of AST documents each of
|
||||
* which contains a single operation as well the fragment definitions it
|
||||
* refers to.
|
||||
*/
|
||||
export function separateOperations(documentAST) {
|
||||
var operations = [];
|
||||
var fragments = Object.create(null);
|
||||
var positions = new Map();
|
||||
var depGraph = Object.create(null);
|
||||
var fromName;
|
||||
var idx = 0; // Populate metadata and build a dependency graph.
|
||||
|
||||
visit(documentAST, {
|
||||
OperationDefinition: function OperationDefinition(node) {
|
||||
fromName = opName(node);
|
||||
operations.push(node);
|
||||
positions.set(node, idx++);
|
||||
},
|
||||
FragmentDefinition: function FragmentDefinition(node) {
|
||||
fromName = node.name.value;
|
||||
fragments[fromName] = node;
|
||||
positions.set(node, idx++);
|
||||
},
|
||||
FragmentSpread: function FragmentSpread(node) {
|
||||
var toName = node.name.value;
|
||||
(depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true;
|
||||
}
|
||||
}); // For each operation, produce a new synthesized AST which includes only what
|
||||
// is necessary for completing that operation.
|
||||
|
||||
var separatedDocumentASTs = Object.create(null);
|
||||
|
||||
for (var _i = 0; _i < operations.length; _i++) {
|
||||
var operation = operations[_i];
|
||||
var operationName = opName(operation);
|
||||
var dependencies = Object.create(null);
|
||||
collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted
|
||||
// to retain the same order as the original document.
|
||||
|
||||
var definitions = [operation];
|
||||
|
||||
var _arr = Object.keys(dependencies);
|
||||
|
||||
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
|
||||
var name = _arr[_i2];
|
||||
definitions.push(fragments[name]);
|
||||
}
|
||||
|
||||
definitions.sort(function (n1, n2) {
|
||||
return (positions.get(n1) || 0) - (positions.get(n2) || 0);
|
||||
});
|
||||
separatedDocumentASTs[operationName] = {
|
||||
kind: 'Document',
|
||||
definitions: definitions
|
||||
};
|
||||
}
|
||||
|
||||
return separatedDocumentASTs;
|
||||
}
|
||||
|
||||
// Provides the empty string for anonymous operations.
|
||||
function opName(operation) {
|
||||
return operation.name ? operation.name.value : '';
|
||||
} // From a dependency graph, collects a list of transitive dependencies by
|
||||
// recursing through a dependency graph.
|
||||
|
||||
|
||||
function collectTransitiveDependencies(collected, depGraph, fromName) {
|
||||
var immediateDeps = depGraph[fromName];
|
||||
|
||||
if (immediateDeps) {
|
||||
var _arr2 = Object.keys(immediateDeps);
|
||||
|
||||
for (var _i3 = 0; _i3 < _arr2.length; _i3++) {
|
||||
var toName = _arr2[_i3];
|
||||
|
||||
if (!collected[toName]) {
|
||||
collected[toName] = true;
|
||||
collectTransitiveDependencies(collected, depGraph, toName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.isEqualType = isEqualType;
|
||||
exports.isTypeSubTypeOf = isTypeSubTypeOf;
|
||||
exports.doTypesOverlap = doTypesOverlap;
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Provided two types, return true if the types are equal (invariant).
|
||||
*/
|
||||
function isEqualType(typeA, typeB) {
|
||||
// Equivalent types are equal.
|
||||
if (typeA === typeB) {
|
||||
return true;
|
||||
} // If either type is non-null, the other must also be non-null.
|
||||
|
||||
|
||||
if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) {
|
||||
return isEqualType(typeA.ofType, typeB.ofType);
|
||||
} // If either type is a list, the other must also be a list.
|
||||
|
||||
|
||||
if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) {
|
||||
return isEqualType(typeA.ofType, typeB.ofType);
|
||||
} // Otherwise the types are not equal.
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Provided a type and a super type, return true if the first type is either
|
||||
* equal or a subset of the second super type (covariant).
|
||||
*/
|
||||
|
||||
|
||||
function isTypeSubTypeOf(schema, maybeSubType, superType) {
|
||||
// Equivalent type is a valid subtype
|
||||
if (maybeSubType === superType) {
|
||||
return true;
|
||||
} // If superType is non-null, maybeSubType must also be non-null.
|
||||
|
||||
|
||||
if ((0, _definition.isNonNullType)(superType)) {
|
||||
if ((0, _definition.isNonNullType)(maybeSubType)) {
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((0, _definition.isNonNullType)(maybeSubType)) {
|
||||
// If superType is nullable, maybeSubType may be non-null or nullable.
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
|
||||
} // If superType type is a list, maybeSubType type must also be a list.
|
||||
|
||||
|
||||
if ((0, _definition.isListType)(superType)) {
|
||||
if ((0, _definition.isListType)(maybeSubType)) {
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((0, _definition.isListType)(maybeSubType)) {
|
||||
// If superType is not a list, maybeSubType must also be not a list.
|
||||
return false;
|
||||
} // If superType type is an abstract type, maybeSubType type may be a currently
|
||||
// possible object type.
|
||||
|
||||
|
||||
if ((0, _definition.isAbstractType)(superType) && (0, _definition.isObjectType)(maybeSubType) && schema.isPossibleType(superType, maybeSubType)) {
|
||||
return true;
|
||||
} // Otherwise, the child type is not a valid subtype of the parent type.
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Provided two composite types, determine if they "overlap". Two composite
|
||||
* types overlap when the Sets of possible concrete types for each intersect.
|
||||
*
|
||||
* This is often used to determine if a fragment of a given type could possibly
|
||||
* be visited in a context of another type.
|
||||
*
|
||||
* This function is commutative.
|
||||
*/
|
||||
|
||||
|
||||
function doTypesOverlap(schema, typeA, typeB) {
|
||||
// Equivalent types overlap
|
||||
if (typeA === typeB) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ((0, _definition.isAbstractType)(typeA)) {
|
||||
if ((0, _definition.isAbstractType)(typeB)) {
|
||||
// If both types are abstract, then determine if there is any intersection
|
||||
// between possible concrete types of each.
|
||||
return schema.getPossibleTypes(typeA).some(function (type) {
|
||||
return schema.isPossibleType(typeB, type);
|
||||
});
|
||||
} // Determine if the latter type is a possible concrete type of the former.
|
||||
|
||||
|
||||
return schema.isPossibleType(typeA, typeB);
|
||||
}
|
||||
|
||||
if ((0, _definition.isAbstractType)(typeB)) {
|
||||
// Determine if the former type is a possible concrete type of the latter.
|
||||
return schema.isPossibleType(typeB, typeA);
|
||||
} // Otherwise the types do not overlap.
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import {
|
||||
isObjectType,
|
||||
isListType,
|
||||
isNonNullType,
|
||||
isAbstractType,
|
||||
} from '../type/definition';
|
||||
import type { GraphQLType, GraphQLCompositeType } from '../type/definition';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
|
||||
/**
|
||||
* Provided two types, return true if the types are equal (invariant).
|
||||
*/
|
||||
export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean {
|
||||
// Equivalent types are equal.
|
||||
if (typeA === typeB) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If either type is non-null, the other must also be non-null.
|
||||
if (isNonNullType(typeA) && isNonNullType(typeB)) {
|
||||
return isEqualType(typeA.ofType, typeB.ofType);
|
||||
}
|
||||
|
||||
// If either type is a list, the other must also be a list.
|
||||
if (isListType(typeA) && isListType(typeB)) {
|
||||
return isEqualType(typeA.ofType, typeB.ofType);
|
||||
}
|
||||
|
||||
// Otherwise the types are not equal.
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provided a type and a super type, return true if the first type is either
|
||||
* equal or a subset of the second super type (covariant).
|
||||
*/
|
||||
export function isTypeSubTypeOf(
|
||||
schema: GraphQLSchema,
|
||||
maybeSubType: GraphQLType,
|
||||
superType: GraphQLType,
|
||||
): boolean {
|
||||
// Equivalent type is a valid subtype
|
||||
if (maybeSubType === superType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If superType is non-null, maybeSubType must also be non-null.
|
||||
if (isNonNullType(superType)) {
|
||||
if (isNonNullType(maybeSubType)) {
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (isNonNullType(maybeSubType)) {
|
||||
// If superType is nullable, maybeSubType may be non-null or nullable.
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
|
||||
}
|
||||
|
||||
// If superType type is a list, maybeSubType type must also be a list.
|
||||
if (isListType(superType)) {
|
||||
if (isListType(maybeSubType)) {
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (isListType(maybeSubType)) {
|
||||
// If superType is not a list, maybeSubType must also be not a list.
|
||||
return false;
|
||||
}
|
||||
|
||||
// If superType type is an abstract type, maybeSubType type may be a currently
|
||||
// possible object type.
|
||||
if (
|
||||
isAbstractType(superType) &&
|
||||
isObjectType(maybeSubType) &&
|
||||
schema.isPossibleType(superType, maybeSubType)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Otherwise, the child type is not a valid subtype of the parent type.
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provided two composite types, determine if they "overlap". Two composite
|
||||
* types overlap when the Sets of possible concrete types for each intersect.
|
||||
*
|
||||
* This is often used to determine if a fragment of a given type could possibly
|
||||
* be visited in a context of another type.
|
||||
*
|
||||
* This function is commutative.
|
||||
*/
|
||||
export function doTypesOverlap(
|
||||
schema: GraphQLSchema,
|
||||
typeA: GraphQLCompositeType,
|
||||
typeB: GraphQLCompositeType,
|
||||
): boolean {
|
||||
// Equivalent types overlap
|
||||
if (typeA === typeB) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isAbstractType(typeA)) {
|
||||
if (isAbstractType(typeB)) {
|
||||
// If both types are abstract, then determine if there is any intersection
|
||||
// between possible concrete types of each.
|
||||
return schema
|
||||
.getPossibleTypes(typeA)
|
||||
.some(type => schema.isPossibleType(typeB, type));
|
||||
}
|
||||
// Determine if the latter type is a possible concrete type of the former.
|
||||
return schema.isPossibleType(typeA, typeB);
|
||||
}
|
||||
|
||||
if (isAbstractType(typeB)) {
|
||||
// Determine if the former type is a possible concrete type of the latter.
|
||||
return schema.isPossibleType(typeB, typeA);
|
||||
}
|
||||
|
||||
// Otherwise the types do not overlap.
|
||||
return false;
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { isObjectType, isListType, isNonNullType, isAbstractType } from '../type/definition';
|
||||
|
||||
/**
|
||||
* Provided two types, return true if the types are equal (invariant).
|
||||
*/
|
||||
export function isEqualType(typeA, typeB) {
|
||||
// Equivalent types are equal.
|
||||
if (typeA === typeB) {
|
||||
return true;
|
||||
} // If either type is non-null, the other must also be non-null.
|
||||
|
||||
|
||||
if (isNonNullType(typeA) && isNonNullType(typeB)) {
|
||||
return isEqualType(typeA.ofType, typeB.ofType);
|
||||
} // If either type is a list, the other must also be a list.
|
||||
|
||||
|
||||
if (isListType(typeA) && isListType(typeB)) {
|
||||
return isEqualType(typeA.ofType, typeB.ofType);
|
||||
} // Otherwise the types are not equal.
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Provided a type and a super type, return true if the first type is either
|
||||
* equal or a subset of the second super type (covariant).
|
||||
*/
|
||||
|
||||
export function isTypeSubTypeOf(schema, maybeSubType, superType) {
|
||||
// Equivalent type is a valid subtype
|
||||
if (maybeSubType === superType) {
|
||||
return true;
|
||||
} // If superType is non-null, maybeSubType must also be non-null.
|
||||
|
||||
|
||||
if (isNonNullType(superType)) {
|
||||
if (isNonNullType(maybeSubType)) {
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isNonNullType(maybeSubType)) {
|
||||
// If superType is nullable, maybeSubType may be non-null or nullable.
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
|
||||
} // If superType type is a list, maybeSubType type must also be a list.
|
||||
|
||||
|
||||
if (isListType(superType)) {
|
||||
if (isListType(maybeSubType)) {
|
||||
return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isListType(maybeSubType)) {
|
||||
// If superType is not a list, maybeSubType must also be not a list.
|
||||
return false;
|
||||
} // If superType type is an abstract type, maybeSubType type may be a currently
|
||||
// possible object type.
|
||||
|
||||
|
||||
if (isAbstractType(superType) && isObjectType(maybeSubType) && schema.isPossibleType(superType, maybeSubType)) {
|
||||
return true;
|
||||
} // Otherwise, the child type is not a valid subtype of the parent type.
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Provided two composite types, determine if they "overlap". Two composite
|
||||
* types overlap when the Sets of possible concrete types for each intersect.
|
||||
*
|
||||
* This is often used to determine if a fragment of a given type could possibly
|
||||
* be visited in a context of another type.
|
||||
*
|
||||
* This function is commutative.
|
||||
*/
|
||||
|
||||
export function doTypesOverlap(schema, typeA, typeB) {
|
||||
// Equivalent types overlap
|
||||
if (typeA === typeB) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isAbstractType(typeA)) {
|
||||
if (isAbstractType(typeB)) {
|
||||
// If both types are abstract, then determine if there is any intersection
|
||||
// between possible concrete types of each.
|
||||
return schema.getPossibleTypes(typeA).some(function (type) {
|
||||
return schema.isPossibleType(typeB, type);
|
||||
});
|
||||
} // Determine if the latter type is a possible concrete type of the former.
|
||||
|
||||
|
||||
return schema.isPossibleType(typeA, typeB);
|
||||
}
|
||||
|
||||
if (isAbstractType(typeB)) {
|
||||
// Determine if the former type is a possible concrete type of the latter.
|
||||
return schema.isPossibleType(typeB, typeA);
|
||||
} // Otherwise the types do not overlap.
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.typeFromAST = typeFromAST;
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
function typeFromAST(schema, typeNode) {
|
||||
/* eslint-enable no-redeclare */
|
||||
var innerType;
|
||||
|
||||
if (typeNode.kind === _kinds.Kind.LIST_TYPE) {
|
||||
innerType = typeFromAST(schema, typeNode.type);
|
||||
return innerType && (0, _definition.GraphQLList)(innerType);
|
||||
}
|
||||
|
||||
if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) {
|
||||
innerType = typeFromAST(schema, typeNode.type);
|
||||
return innerType && (0, _definition.GraphQLNonNull)(innerType);
|
||||
}
|
||||
|
||||
if (typeNode.kind === _kinds.Kind.NAMED_TYPE) {
|
||||
return schema.getType(typeNode.name.value);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unexpected type kind: ".concat(typeNode.kind, "."));
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import { Kind } from '../language/kinds';
|
||||
import type {
|
||||
NamedTypeNode,
|
||||
ListTypeNode,
|
||||
NonNullTypeNode,
|
||||
} from '../language/ast';
|
||||
import { GraphQLList, GraphQLNonNull } from '../type/definition';
|
||||
import type { GraphQLNamedType } from '../type/definition';
|
||||
import type { GraphQLSchema } from '../type/schema';
|
||||
|
||||
/**
|
||||
* Given a Schema and an AST node describing a type, return a GraphQLType
|
||||
* definition which applies to that type. For example, if provided the parsed
|
||||
* AST node for `[User]`, a GraphQLList instance will be returned, containing
|
||||
* the type called "User" found in the schema. If a type called "User" is not
|
||||
* found in the schema, then undefined will be returned.
|
||||
*/
|
||||
/* eslint-disable no-redeclare */
|
||||
declare function typeFromAST(
|
||||
schema: GraphQLSchema,
|
||||
typeNode: NamedTypeNode,
|
||||
): GraphQLNamedType | void;
|
||||
declare function typeFromAST(
|
||||
schema: GraphQLSchema,
|
||||
typeNode: ListTypeNode,
|
||||
): GraphQLList<any> | void;
|
||||
declare function typeFromAST(
|
||||
schema: GraphQLSchema,
|
||||
typeNode: NonNullTypeNode,
|
||||
): GraphQLNonNull<any> | void;
|
||||
export function typeFromAST(schema, typeNode) {
|
||||
/* eslint-enable no-redeclare */
|
||||
let innerType;
|
||||
if (typeNode.kind === Kind.LIST_TYPE) {
|
||||
innerType = typeFromAST(schema, typeNode.type);
|
||||
return innerType && GraphQLList(innerType);
|
||||
}
|
||||
if (typeNode.kind === Kind.NON_NULL_TYPE) {
|
||||
innerType = typeFromAST(schema, typeNode.type);
|
||||
return innerType && GraphQLNonNull(innerType);
|
||||
}
|
||||
if (typeNode.kind === Kind.NAMED_TYPE) {
|
||||
return schema.getType(typeNode.name.value);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
throw new Error(`Unexpected type kind: ${(typeNode.kind: empty)}.`);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import { Kind } from '../language/kinds';
|
||||
import { GraphQLList, GraphQLNonNull } from '../type/definition';
|
||||
export function typeFromAST(schema, typeNode) {
|
||||
/* eslint-enable no-redeclare */
|
||||
var innerType;
|
||||
|
||||
if (typeNode.kind === Kind.LIST_TYPE) {
|
||||
innerType = typeFromAST(schema, typeNode.type);
|
||||
return innerType && GraphQLList(innerType);
|
||||
}
|
||||
|
||||
if (typeNode.kind === Kind.NON_NULL_TYPE) {
|
||||
innerType = typeFromAST(schema, typeNode.type);
|
||||
return innerType && GraphQLNonNull(innerType);
|
||||
}
|
||||
|
||||
if (typeNode.kind === Kind.NAMED_TYPE) {
|
||||
return schema.getType(typeNode.name.value);
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unexpected type kind: ".concat(typeNode.kind, "."));
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.valueFromAST = valueFromAST;
|
||||
|
||||
var _keyMap = _interopRequireDefault(require("../jsutils/keyMap"));
|
||||
|
||||
var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
|
||||
|
||||
var _objectValues = _interopRequireDefault(require("../jsutils/objectValues"));
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
var _definition = require("../type/definition");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Produces a JavaScript value given a GraphQL Value AST.
|
||||
*
|
||||
* A GraphQL type must be provided, which will be used to interpret different
|
||||
* GraphQL Value literals.
|
||||
*
|
||||
* Returns `undefined` when the value could not be validly coerced according to
|
||||
* the provided type.
|
||||
*
|
||||
* | GraphQL Value | JSON Value |
|
||||
* | -------------------- | ------------- |
|
||||
* | Input Object | Object |
|
||||
* | List | Array |
|
||||
* | Boolean | Boolean |
|
||||
* | String | String |
|
||||
* | Int / Float | Number |
|
||||
* | Enum Value | Mixed |
|
||||
* | NullValue | null |
|
||||
*
|
||||
*/
|
||||
function valueFromAST(valueNode, type, variables) {
|
||||
if (!valueNode) {
|
||||
// When there is no node, then there is also no value.
|
||||
// Importantly, this is different from returning the value null.
|
||||
return;
|
||||
}
|
||||
|
||||
if ((0, _definition.isNonNullType)(type)) {
|
||||
if (valueNode.kind === _kinds.Kind.NULL) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
return valueFromAST(valueNode, type.ofType, variables);
|
||||
}
|
||||
|
||||
if (valueNode.kind === _kinds.Kind.NULL) {
|
||||
// This is explicitly returning the value null.
|
||||
return null;
|
||||
}
|
||||
|
||||
if (valueNode.kind === _kinds.Kind.VARIABLE) {
|
||||
var variableName = valueNode.name.value;
|
||||
|
||||
if (!variables || (0, _isInvalid.default)(variables[variableName])) {
|
||||
// No valid return value.
|
||||
return;
|
||||
}
|
||||
|
||||
var variableValue = variables[variableName];
|
||||
|
||||
if (variableValue === null && (0, _definition.isNonNullType)(type)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
} // Note: This does no further checking that this variable is correct.
|
||||
// This assumes that this query has been validated and the variable
|
||||
// usage here is of the correct type.
|
||||
|
||||
|
||||
return variableValue;
|
||||
}
|
||||
|
||||
if ((0, _definition.isListType)(type)) {
|
||||
var itemType = type.ofType;
|
||||
|
||||
if (valueNode.kind === _kinds.Kind.LIST) {
|
||||
var coercedValues = [];
|
||||
var itemNodes = valueNode.values;
|
||||
|
||||
for (var i = 0; i < itemNodes.length; i++) {
|
||||
if (isMissingVariable(itemNodes[i], variables)) {
|
||||
// If an array contains a missing variable, it is either coerced to
|
||||
// null or if the item type is non-null, it considered invalid.
|
||||
if ((0, _definition.isNonNullType)(itemType)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
coercedValues.push(null);
|
||||
} else {
|
||||
var itemValue = valueFromAST(itemNodes[i], itemType, variables);
|
||||
|
||||
if ((0, _isInvalid.default)(itemValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
coercedValues.push(itemValue);
|
||||
}
|
||||
}
|
||||
|
||||
return coercedValues;
|
||||
}
|
||||
|
||||
var coercedValue = valueFromAST(valueNode, itemType, variables);
|
||||
|
||||
if ((0, _isInvalid.default)(coercedValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
return [coercedValue];
|
||||
}
|
||||
|
||||
if ((0, _definition.isInputObjectType)(type)) {
|
||||
if (valueNode.kind !== _kinds.Kind.OBJECT) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
var coercedObj = Object.create(null);
|
||||
var fieldNodes = (0, _keyMap.default)(valueNode.fields, function (field) {
|
||||
return field.name.value;
|
||||
});
|
||||
var fields = (0, _objectValues.default)(type.getFields());
|
||||
|
||||
for (var _i = 0; _i < fields.length; _i++) {
|
||||
var field = fields[_i];
|
||||
var fieldNode = fieldNodes[field.name];
|
||||
|
||||
if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
|
||||
if (field.defaultValue !== undefined) {
|
||||
coercedObj[field.name] = field.defaultValue;
|
||||
} else if ((0, _definition.isNonNullType)(field.type)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var fieldValue = valueFromAST(fieldNode.value, field.type, variables);
|
||||
|
||||
if ((0, _isInvalid.default)(fieldValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
coercedObj[field.name] = fieldValue;
|
||||
}
|
||||
|
||||
return coercedObj;
|
||||
}
|
||||
|
||||
if ((0, _definition.isEnumType)(type)) {
|
||||
if (valueNode.kind !== _kinds.Kind.ENUM) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
var enumValue = type.getValue(valueNode.value);
|
||||
|
||||
if (!enumValue) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
return enumValue.value;
|
||||
}
|
||||
|
||||
if ((0, _definition.isScalarType)(type)) {
|
||||
// Scalars fulfill parsing a literal value via parseLiteral().
|
||||
// Invalid values represent a failure to parse correctly, in which case
|
||||
// no value is returned.
|
||||
var result;
|
||||
|
||||
try {
|
||||
result = type.parseLiteral(valueNode, variables);
|
||||
} catch (_error) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
if ((0, _isInvalid.default)(result)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unknown type: ".concat(type, "."));
|
||||
} // Returns true if the provided valueNode is a variable which is not defined
|
||||
// in the set of variables.
|
||||
|
||||
|
||||
function isMissingVariable(valueNode, variables) {
|
||||
return valueNode.kind === _kinds.Kind.VARIABLE && (!variables || (0, _isInvalid.default)(variables[valueNode.name.value]));
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import type { ObjMap } from '../jsutils/ObjMap';
|
||||
import { Kind } from '../language/kinds';
|
||||
import {
|
||||
isScalarType,
|
||||
isEnumType,
|
||||
isInputObjectType,
|
||||
isListType,
|
||||
isNonNullType,
|
||||
} from '../type/definition';
|
||||
import type { GraphQLInputType } from '../type/definition';
|
||||
import type { ValueNode } from '../language/ast';
|
||||
|
||||
/**
|
||||
* Produces a JavaScript value given a GraphQL Value AST.
|
||||
*
|
||||
* A GraphQL type must be provided, which will be used to interpret different
|
||||
* GraphQL Value literals.
|
||||
*
|
||||
* Returns `undefined` when the value could not be validly coerced according to
|
||||
* the provided type.
|
||||
*
|
||||
* | GraphQL Value | JSON Value |
|
||||
* | -------------------- | ------------- |
|
||||
* | Input Object | Object |
|
||||
* | List | Array |
|
||||
* | Boolean | Boolean |
|
||||
* | String | String |
|
||||
* | Int / Float | Number |
|
||||
* | Enum Value | Mixed |
|
||||
* | NullValue | null |
|
||||
*
|
||||
*/
|
||||
export function valueFromAST(
|
||||
valueNode: ?ValueNode,
|
||||
type: GraphQLInputType,
|
||||
variables?: ?ObjMap<mixed>,
|
||||
): mixed | void {
|
||||
if (!valueNode) {
|
||||
// When there is no node, then there is also no value.
|
||||
// Importantly, this is different from returning the value null.
|
||||
return;
|
||||
}
|
||||
|
||||
if (isNonNullType(type)) {
|
||||
if (valueNode.kind === Kind.NULL) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
return valueFromAST(valueNode, type.ofType, variables);
|
||||
}
|
||||
|
||||
if (valueNode.kind === Kind.NULL) {
|
||||
// This is explicitly returning the value null.
|
||||
return null;
|
||||
}
|
||||
|
||||
if (valueNode.kind === Kind.VARIABLE) {
|
||||
const variableName = valueNode.name.value;
|
||||
if (!variables || isInvalid(variables[variableName])) {
|
||||
// No valid return value.
|
||||
return;
|
||||
}
|
||||
const variableValue = variables[variableName];
|
||||
if (variableValue === null && isNonNullType(type)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
// Note: This does no further checking that this variable is correct.
|
||||
// This assumes that this query has been validated and the variable
|
||||
// usage here is of the correct type.
|
||||
return variableValue;
|
||||
}
|
||||
|
||||
if (isListType(type)) {
|
||||
const itemType = type.ofType;
|
||||
if (valueNode.kind === Kind.LIST) {
|
||||
const coercedValues = [];
|
||||
const itemNodes = valueNode.values;
|
||||
for (let i = 0; i < itemNodes.length; i++) {
|
||||
if (isMissingVariable(itemNodes[i], variables)) {
|
||||
// If an array contains a missing variable, it is either coerced to
|
||||
// null or if the item type is non-null, it considered invalid.
|
||||
if (isNonNullType(itemType)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
coercedValues.push(null);
|
||||
} else {
|
||||
const itemValue = valueFromAST(itemNodes[i], itemType, variables);
|
||||
if (isInvalid(itemValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
coercedValues.push(itemValue);
|
||||
}
|
||||
}
|
||||
return coercedValues;
|
||||
}
|
||||
const coercedValue = valueFromAST(valueNode, itemType, variables);
|
||||
if (isInvalid(coercedValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
return [coercedValue];
|
||||
}
|
||||
|
||||
if (isInputObjectType(type)) {
|
||||
if (valueNode.kind !== Kind.OBJECT) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
const coercedObj = Object.create(null);
|
||||
const fieldNodes = keyMap(valueNode.fields, field => field.name.value);
|
||||
const fields = objectValues(type.getFields());
|
||||
for (let i = 0; i < fields.length; i++) {
|
||||
const field = fields[i];
|
||||
const fieldNode = fieldNodes[field.name];
|
||||
if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
|
||||
if (field.defaultValue !== undefined) {
|
||||
coercedObj[field.name] = field.defaultValue;
|
||||
} else if (isNonNullType(field.type)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const fieldValue = valueFromAST(fieldNode.value, field.type, variables);
|
||||
if (isInvalid(fieldValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
coercedObj[field.name] = fieldValue;
|
||||
}
|
||||
return coercedObj;
|
||||
}
|
||||
|
||||
if (isEnumType(type)) {
|
||||
if (valueNode.kind !== Kind.ENUM) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
const enumValue = type.getValue(valueNode.value);
|
||||
if (!enumValue) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
return enumValue.value;
|
||||
}
|
||||
|
||||
if (isScalarType(type)) {
|
||||
// Scalars fulfill parsing a literal value via parseLiteral().
|
||||
// Invalid values represent a failure to parse correctly, in which case
|
||||
// no value is returned.
|
||||
let result;
|
||||
try {
|
||||
result = type.parseLiteral(valueNode, variables);
|
||||
} catch (_error) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
if (isInvalid(result)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/* istanbul ignore next */
|
||||
throw new Error(`Unknown type: ${(type: empty)}.`);
|
||||
}
|
||||
|
||||
// Returns true if the provided valueNode is a variable which is not defined
|
||||
// in the set of variables.
|
||||
function isMissingVariable(valueNode, variables) {
|
||||
return (
|
||||
valueNode.kind === Kind.VARIABLE &&
|
||||
(!variables || isInvalid(variables[valueNode.name.value]))
|
||||
);
|
||||
}
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import keyMap from '../jsutils/keyMap';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import objectValues from '../jsutils/objectValues';
|
||||
import { Kind } from '../language/kinds';
|
||||
import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition';
|
||||
|
||||
/**
|
||||
* Produces a JavaScript value given a GraphQL Value AST.
|
||||
*
|
||||
* A GraphQL type must be provided, which will be used to interpret different
|
||||
* GraphQL Value literals.
|
||||
*
|
||||
* Returns `undefined` when the value could not be validly coerced according to
|
||||
* the provided type.
|
||||
*
|
||||
* | GraphQL Value | JSON Value |
|
||||
* | -------------------- | ------------- |
|
||||
* | Input Object | Object |
|
||||
* | List | Array |
|
||||
* | Boolean | Boolean |
|
||||
* | String | String |
|
||||
* | Int / Float | Number |
|
||||
* | Enum Value | Mixed |
|
||||
* | NullValue | null |
|
||||
*
|
||||
*/
|
||||
export function valueFromAST(valueNode, type, variables) {
|
||||
if (!valueNode) {
|
||||
// When there is no node, then there is also no value.
|
||||
// Importantly, this is different from returning the value null.
|
||||
return;
|
||||
}
|
||||
|
||||
if (isNonNullType(type)) {
|
||||
if (valueNode.kind === Kind.NULL) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
return valueFromAST(valueNode, type.ofType, variables);
|
||||
}
|
||||
|
||||
if (valueNode.kind === Kind.NULL) {
|
||||
// This is explicitly returning the value null.
|
||||
return null;
|
||||
}
|
||||
|
||||
if (valueNode.kind === Kind.VARIABLE) {
|
||||
var variableName = valueNode.name.value;
|
||||
|
||||
if (!variables || isInvalid(variables[variableName])) {
|
||||
// No valid return value.
|
||||
return;
|
||||
}
|
||||
|
||||
var variableValue = variables[variableName];
|
||||
|
||||
if (variableValue === null && isNonNullType(type)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
} // Note: This does no further checking that this variable is correct.
|
||||
// This assumes that this query has been validated and the variable
|
||||
// usage here is of the correct type.
|
||||
|
||||
|
||||
return variableValue;
|
||||
}
|
||||
|
||||
if (isListType(type)) {
|
||||
var itemType = type.ofType;
|
||||
|
||||
if (valueNode.kind === Kind.LIST) {
|
||||
var coercedValues = [];
|
||||
var itemNodes = valueNode.values;
|
||||
|
||||
for (var i = 0; i < itemNodes.length; i++) {
|
||||
if (isMissingVariable(itemNodes[i], variables)) {
|
||||
// If an array contains a missing variable, it is either coerced to
|
||||
// null or if the item type is non-null, it considered invalid.
|
||||
if (isNonNullType(itemType)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
coercedValues.push(null);
|
||||
} else {
|
||||
var itemValue = valueFromAST(itemNodes[i], itemType, variables);
|
||||
|
||||
if (isInvalid(itemValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
coercedValues.push(itemValue);
|
||||
}
|
||||
}
|
||||
|
||||
return coercedValues;
|
||||
}
|
||||
|
||||
var coercedValue = valueFromAST(valueNode, itemType, variables);
|
||||
|
||||
if (isInvalid(coercedValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
return [coercedValue];
|
||||
}
|
||||
|
||||
if (isInputObjectType(type)) {
|
||||
if (valueNode.kind !== Kind.OBJECT) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
var coercedObj = Object.create(null);
|
||||
var fieldNodes = keyMap(valueNode.fields, function (field) {
|
||||
return field.name.value;
|
||||
});
|
||||
var fields = objectValues(type.getFields());
|
||||
|
||||
for (var _i = 0; _i < fields.length; _i++) {
|
||||
var field = fields[_i];
|
||||
var fieldNode = fieldNodes[field.name];
|
||||
|
||||
if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
|
||||
if (field.defaultValue !== undefined) {
|
||||
coercedObj[field.name] = field.defaultValue;
|
||||
} else if (isNonNullType(field.type)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var fieldValue = valueFromAST(fieldNode.value, field.type, variables);
|
||||
|
||||
if (isInvalid(fieldValue)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
coercedObj[field.name] = fieldValue;
|
||||
}
|
||||
|
||||
return coercedObj;
|
||||
}
|
||||
|
||||
if (isEnumType(type)) {
|
||||
if (valueNode.kind !== Kind.ENUM) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
var enumValue = type.getValue(valueNode.value);
|
||||
|
||||
if (!enumValue) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
return enumValue.value;
|
||||
}
|
||||
|
||||
if (isScalarType(type)) {
|
||||
// Scalars fulfill parsing a literal value via parseLiteral().
|
||||
// Invalid values represent a failure to parse correctly, in which case
|
||||
// no value is returned.
|
||||
var result;
|
||||
|
||||
try {
|
||||
result = type.parseLiteral(valueNode, variables);
|
||||
} catch (_error) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
if (isInvalid(result)) {
|
||||
return; // Invalid: intentionally return no value.
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error("Unknown type: ".concat(type, "."));
|
||||
} // Returns true if the provided valueNode is a variable which is not defined
|
||||
// in the set of variables.
|
||||
|
||||
function isMissingVariable(valueNode, variables) {
|
||||
return valueNode.kind === Kind.VARIABLE && (!variables || isInvalid(variables[valueNode.name.value]));
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.valueFromASTUntyped = valueFromASTUntyped;
|
||||
|
||||
var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap"));
|
||||
|
||||
var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid"));
|
||||
|
||||
var _kinds = require("../language/kinds");
|
||||
|
||||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
|
||||
/**
|
||||
* Produces a JavaScript value given a GraphQL Value AST.
|
||||
*
|
||||
* Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
|
||||
* will reflect the provided GraphQL value AST.
|
||||
*
|
||||
* | GraphQL Value | JavaScript Value |
|
||||
* | -------------------- | ---------------- |
|
||||
* | Input Object | Object |
|
||||
* | List | Array |
|
||||
* | Boolean | Boolean |
|
||||
* | String / Enum | String |
|
||||
* | Int / Float | Number |
|
||||
* | Null | null |
|
||||
*
|
||||
*/
|
||||
function valueFromASTUntyped(valueNode, variables) {
|
||||
switch (valueNode.kind) {
|
||||
case _kinds.Kind.NULL:
|
||||
return null;
|
||||
|
||||
case _kinds.Kind.INT:
|
||||
return parseInt(valueNode.value, 10);
|
||||
|
||||
case _kinds.Kind.FLOAT:
|
||||
return parseFloat(valueNode.value);
|
||||
|
||||
case _kinds.Kind.STRING:
|
||||
case _kinds.Kind.ENUM:
|
||||
case _kinds.Kind.BOOLEAN:
|
||||
return valueNode.value;
|
||||
|
||||
case _kinds.Kind.LIST:
|
||||
return valueNode.values.map(function (node) {
|
||||
return valueFromASTUntyped(node, variables);
|
||||
});
|
||||
|
||||
case _kinds.Kind.OBJECT:
|
||||
return (0, _keyValMap.default)(valueNode.fields, function (field) {
|
||||
return field.name.value;
|
||||
}, function (field) {
|
||||
return valueFromASTUntyped(field.value, variables);
|
||||
});
|
||||
|
||||
case _kinds.Kind.VARIABLE:
|
||||
var variableName = valueNode.name.value;
|
||||
return variables && !(0, _isInvalid.default)(variables[variableName]) ? variables[variableName] : undefined;
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error('Unexpected value kind: ' + valueNode.kind);
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @flow strict
|
||||
*/
|
||||
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import type { ObjMap } from '../jsutils/ObjMap';
|
||||
import { Kind } from '../language/kinds';
|
||||
import type { ValueNode } from '../language/ast';
|
||||
|
||||
/**
|
||||
* Produces a JavaScript value given a GraphQL Value AST.
|
||||
*
|
||||
* Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
|
||||
* will reflect the provided GraphQL value AST.
|
||||
*
|
||||
* | GraphQL Value | JavaScript Value |
|
||||
* | -------------------- | ---------------- |
|
||||
* | Input Object | Object |
|
||||
* | List | Array |
|
||||
* | Boolean | Boolean |
|
||||
* | String / Enum | String |
|
||||
* | Int / Float | Number |
|
||||
* | Null | null |
|
||||
*
|
||||
*/
|
||||
export function valueFromASTUntyped(
|
||||
valueNode: ValueNode,
|
||||
variables?: ?ObjMap<mixed>,
|
||||
): mixed {
|
||||
switch (valueNode.kind) {
|
||||
case Kind.NULL:
|
||||
return null;
|
||||
case Kind.INT:
|
||||
return parseInt(valueNode.value, 10);
|
||||
case Kind.FLOAT:
|
||||
return parseFloat(valueNode.value);
|
||||
case Kind.STRING:
|
||||
case Kind.ENUM:
|
||||
case Kind.BOOLEAN:
|
||||
return valueNode.value;
|
||||
case Kind.LIST:
|
||||
return valueNode.values.map(node => valueFromASTUntyped(node, variables));
|
||||
case Kind.OBJECT:
|
||||
return keyValMap(
|
||||
valueNode.fields,
|
||||
field => field.name.value,
|
||||
field => valueFromASTUntyped(field.value, variables),
|
||||
);
|
||||
case Kind.VARIABLE:
|
||||
const variableName = valueNode.name.value;
|
||||
return variables && !isInvalid(variables[variableName])
|
||||
? variables[variableName]
|
||||
: undefined;
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
throw new Error('Unexpected value kind: ' + (valueNode.kind: empty));
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* strict
|
||||
*/
|
||||
import keyValMap from '../jsutils/keyValMap';
|
||||
import isInvalid from '../jsutils/isInvalid';
|
||||
import { Kind } from '../language/kinds';
|
||||
|
||||
/**
|
||||
* Produces a JavaScript value given a GraphQL Value AST.
|
||||
*
|
||||
* Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value
|
||||
* will reflect the provided GraphQL value AST.
|
||||
*
|
||||
* | GraphQL Value | JavaScript Value |
|
||||
* | -------------------- | ---------------- |
|
||||
* | Input Object | Object |
|
||||
* | List | Array |
|
||||
* | Boolean | Boolean |
|
||||
* | String / Enum | String |
|
||||
* | Int / Float | Number |
|
||||
* | Null | null |
|
||||
*
|
||||
*/
|
||||
export function valueFromASTUntyped(valueNode, variables) {
|
||||
switch (valueNode.kind) {
|
||||
case Kind.NULL:
|
||||
return null;
|
||||
|
||||
case Kind.INT:
|
||||
return parseInt(valueNode.value, 10);
|
||||
|
||||
case Kind.FLOAT:
|
||||
return parseFloat(valueNode.value);
|
||||
|
||||
case Kind.STRING:
|
||||
case Kind.ENUM:
|
||||
case Kind.BOOLEAN:
|
||||
return valueNode.value;
|
||||
|
||||
case Kind.LIST:
|
||||
return valueNode.values.map(function (node) {
|
||||
return valueFromASTUntyped(node, variables);
|
||||
});
|
||||
|
||||
case Kind.OBJECT:
|
||||
return keyValMap(valueNode.fields, function (field) {
|
||||
return field.name.value;
|
||||
}, function (field) {
|
||||
return valueFromASTUntyped(field.value, variables);
|
||||
});
|
||||
|
||||
case Kind.VARIABLE:
|
||||
var variableName = valueNode.name.value;
|
||||
return variables && !isInvalid(variables[variableName]) ? variables[variableName] : undefined;
|
||||
}
|
||||
/* istanbul ignore next */
|
||||
|
||||
|
||||
throw new Error('Unexpected value kind: ' + valueNode.kind);
|
||||
}
|
||||
Reference in new issue
Block a user