Initial Save

This commit is contained in:
jackbeeby
2025-03-28 12:30:19 +11:00
parent e381994f19
commit d8773925e8
9910 changed files with 982718 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
import { ASTVisitor } from '../../language/visitor';
import { ASTValidationContext } from '../ValidationContext';
export function nonExecutableDefinitionMessage(defName: string): string;
/**
* Executable definitions
*
* A GraphQL document is only valid for execution if all definitions are either
* operation or fragment definitions.
*/
export function ExecutableDefinitions(
context: ASTValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.nonExecutableDefinitionMessage = nonExecutableDefinitionMessage;
exports.ExecutableDefinitions = ExecutableDefinitions;
var _GraphQLError = require("../../error/GraphQLError");
var _kinds = require("../../language/kinds");
var _predicates = require("../../language/predicates");
function nonExecutableDefinitionMessage(defName) {
return "The ".concat(defName, " definition is not executable.");
}
/**
* Executable definitions
*
* A GraphQL document is only valid for execution if all definitions are either
* operation or fragment definitions.
*/
function ExecutableDefinitions(context) {
return {
Document: function Document(node) {
for (var _i2 = 0, _node$definitions2 = node.definitions; _i2 < _node$definitions2.length; _i2++) {
var definition = _node$definitions2[_i2];
if (!(0, _predicates.isExecutableDefinitionNode)(definition)) {
context.reportError(new _GraphQLError.GraphQLError(nonExecutableDefinitionMessage(definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : definition.name.value), definition));
}
}
return false;
}
};
}

View File

@@ -0,0 +1,44 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { type ASTVisitor } from '../../language/visitor';
import { isExecutableDefinitionNode } from '../../language/predicates';
import { type ASTValidationContext } from '../ValidationContext';
export function nonExecutableDefinitionMessage(defName: string): string {
return `The ${defName} definition is not executable.`;
}
/**
* Executable definitions
*
* A GraphQL document is only valid for execution if all definitions are either
* operation or fragment definitions.
*/
export function ExecutableDefinitions(
context: ASTValidationContext,
): ASTVisitor {
return {
Document(node) {
for (const definition of node.definitions) {
if (!isExecutableDefinitionNode(definition)) {
context.reportError(
new GraphQLError(
nonExecutableDefinitionMessage(
definition.kind === Kind.SCHEMA_DEFINITION ||
definition.kind === Kind.SCHEMA_EXTENSION
? 'schema'
: definition.name.value,
),
definition,
),
);
}
}
return false;
},
};
}

View File

@@ -0,0 +1,28 @@
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { isExecutableDefinitionNode } from '../../language/predicates';
export function nonExecutableDefinitionMessage(defName) {
return "The ".concat(defName, " definition is not executable.");
}
/**
* Executable definitions
*
* A GraphQL document is only valid for execution if all definitions are either
* operation or fragment definitions.
*/
export function ExecutableDefinitions(context) {
return {
Document: function Document(node) {
for (var _i2 = 0, _node$definitions2 = node.definitions; _i2 < _node$definitions2.length; _i2++) {
var definition = _node$definitions2[_i2];
if (!isExecutableDefinitionNode(definition)) {
context.reportError(new GraphQLError(nonExecutableDefinitionMessage(definition.kind === Kind.SCHEMA_DEFINITION || definition.kind === Kind.SCHEMA_EXTENSION ? 'schema' : definition.name.value), definition));
}
}
return false;
}
};
}

View File

@@ -0,0 +1,17 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function undefinedFieldMessage(
fieldName: string,
type: string,
suggestedTypeNames: ReadonlyArray<string>,
suggestedFieldNames: ReadonlyArray<string>,
): string;
/**
* Fields on correct type
*
* A GraphQL document is only valid if all fields selected are defined by the
* parent type, or are an allowed meta field such as __typename.
*/
export function FieldsOnCorrectType(context: ValidationContext): ASTVisitor;

View File

@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.undefinedFieldMessage = undefinedFieldMessage;
exports.FieldsOnCorrectType = FieldsOnCorrectType;
var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean"));
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 undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) {
var quotedTypeNames = suggestedTypeNames.map(function (x) {
return "\"".concat(x, "\"");
});
var quotedFieldNames = suggestedFieldNames.map(function (x) {
return "\"".concat(x, "\"");
});
return "Cannot query field \"".concat(fieldName, "\" on type \"").concat(type, "\".") + ((0, _didYouMean.default)('to use an inline fragment on', quotedTypeNames) || (0, _didYouMean.default)(quotedFieldNames));
}
/**
* Fields on correct type
*
* A GraphQL document is only valid if all fields selected are defined by the
* parent type, or are an allowed meta field such as __typename.
*/
function FieldsOnCorrectType(context) {
return {
Field: function Field(node) {
var type = context.getParentType();
if (type) {
var fieldDef = context.getFieldDef();
if (!fieldDef) {
// This field doesn't exist, lets look for suggestions.
var schema = context.getSchema();
var fieldName = node.name.value; // First determine if there are any suggested types to condition on.
var suggestedTypeNames = getSuggestedTypeNames(schema, type, fieldName); // If there are no suggested types, then perhaps this was a typo?
var suggestedFieldNames = suggestedTypeNames.length !== 0 ? [] : getSuggestedFieldNames(schema, type, fieldName); // Report an error, including helpful suggestions.
context.reportError(new _GraphQLError.GraphQLError(undefinedFieldMessage(fieldName, type.name, suggestedTypeNames, suggestedFieldNames), node));
}
}
}
};
}
/**
* Go through all of the implementations of type, as well as the interfaces that
* they implement. If any of those types include the provided field, suggest
* them, sorted by how often the type is referenced, starting with Interfaces.
*/
function getSuggestedTypeNames(schema, type, fieldName) {
if ((0, _definition.isAbstractType)(type)) {
var suggestedObjectTypes = [];
var interfaceUsageCount = Object.create(null);
for (var _i2 = 0, _schema$getPossibleTy2 = schema.getPossibleTypes(type); _i2 < _schema$getPossibleTy2.length; _i2++) {
var possibleType = _schema$getPossibleTy2[_i2];
if (!possibleType.getFields()[fieldName]) {
continue;
} // This object type defines this field.
suggestedObjectTypes.push(possibleType.name);
for (var _i4 = 0, _possibleType$getInte2 = possibleType.getInterfaces(); _i4 < _possibleType$getInte2.length; _i4++) {
var possibleInterface = _possibleType$getInte2[_i4];
if (!possibleInterface.getFields()[fieldName]) {
continue;
} // This interface type defines this field.
interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1;
}
} // Suggest interface types based on how common they are.
var suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(function (a, b) {
return interfaceUsageCount[b] - interfaceUsageCount[a];
}); // Suggest both interface and object types.
return suggestedInterfaceTypes.concat(suggestedObjectTypes);
} // Otherwise, must be an Object type, which does not have possible fields.
return [];
}
/**
* For the field name provided, determine if there are any similar field names
* that may be the result of a typo.
*/
function getSuggestedFieldNames(schema, type, fieldName) {
if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) {
var possibleFieldNames = Object.keys(type.getFields());
return (0, _suggestionList.default)(fieldName, possibleFieldNames);
} // Otherwise, must be a Union type, which does not define fields.
return [];
}

View File

@@ -0,0 +1,139 @@
// @flow strict
import didYouMean from '../../jsutils/didYouMean';
import suggestionList from '../../jsutils/suggestionList';
import { GraphQLError } from '../../error/GraphQLError';
import { type FieldNode } from '../../language/ast';
import { type ASTVisitor } from '../../language/visitor';
import { type GraphQLSchema } from '../../type/schema';
import {
type GraphQLOutputType,
isObjectType,
isInterfaceType,
isAbstractType,
} from '../../type/definition';
import { type ValidationContext } from '../ValidationContext';
export function undefinedFieldMessage(
fieldName: string,
type: string,
suggestedTypeNames: $ReadOnlyArray<string>,
suggestedFieldNames: $ReadOnlyArray<string>,
): string {
const quotedTypeNames = suggestedTypeNames.map(x => `"${x}"`);
const quotedFieldNames = suggestedFieldNames.map(x => `"${x}"`);
return (
`Cannot query field "${fieldName}" on type "${type}".` +
(didYouMean('to use an inline fragment on', quotedTypeNames) ||
didYouMean(quotedFieldNames))
);
}
/**
* Fields on correct type
*
* A GraphQL document is only valid if all fields selected are defined by the
* parent type, or are an allowed meta field such as __typename.
*/
export function FieldsOnCorrectType(context: ValidationContext): ASTVisitor {
return {
Field(node: FieldNode) {
const type = context.getParentType();
if (type) {
const fieldDef = context.getFieldDef();
if (!fieldDef) {
// This field doesn't exist, lets look for suggestions.
const schema = context.getSchema();
const fieldName = node.name.value;
// First determine if there are any suggested types to condition on.
const suggestedTypeNames = getSuggestedTypeNames(
schema,
type,
fieldName,
);
// If there are no suggested types, then perhaps this was a typo?
const suggestedFieldNames =
suggestedTypeNames.length !== 0
? []
: getSuggestedFieldNames(schema, type, fieldName);
// Report an error, including helpful suggestions.
context.reportError(
new GraphQLError(
undefinedFieldMessage(
fieldName,
type.name,
suggestedTypeNames,
suggestedFieldNames,
),
node,
),
);
}
}
},
};
}
/**
* Go through all of the implementations of type, as well as the interfaces that
* they implement. If any of those types include the provided field, suggest
* them, sorted by how often the type is referenced, starting with Interfaces.
*/
function getSuggestedTypeNames(
schema: GraphQLSchema,
type: GraphQLOutputType,
fieldName: string,
): Array<string> {
if (isAbstractType(type)) {
const suggestedObjectTypes = [];
const interfaceUsageCount = Object.create(null);
for (const possibleType of schema.getPossibleTypes(type)) {
if (!possibleType.getFields()[fieldName]) {
continue;
}
// This object type defines this field.
suggestedObjectTypes.push(possibleType.name);
for (const possibleInterface of possibleType.getInterfaces()) {
if (!possibleInterface.getFields()[fieldName]) {
continue;
}
// This interface type defines this field.
interfaceUsageCount[possibleInterface.name] =
(interfaceUsageCount[possibleInterface.name] || 0) + 1;
}
}
// Suggest interface types based on how common they are.
const suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(
(a, b) => interfaceUsageCount[b] - interfaceUsageCount[a],
);
// Suggest both interface and object types.
return suggestedInterfaceTypes.concat(suggestedObjectTypes);
}
// Otherwise, must be an Object type, which does not have possible fields.
return [];
}
/**
* For the field name provided, determine if there are any similar field names
* that may be the result of a typo.
*/
function getSuggestedFieldNames(
schema: GraphQLSchema,
type: GraphQLOutputType,
fieldName: string,
): Array<string> {
if (isObjectType(type) || isInterfaceType(type)) {
const possibleFieldNames = Object.keys(type.getFields());
return suggestionList(fieldName, possibleFieldNames);
}
// Otherwise, must be a Union type, which does not define fields.
return [];
}

View File

@@ -0,0 +1,102 @@
import didYouMean from '../../jsutils/didYouMean';
import suggestionList from '../../jsutils/suggestionList';
import { GraphQLError } from '../../error/GraphQLError';
import { isObjectType, isInterfaceType, isAbstractType } from '../../type/definition';
export function undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) {
var quotedTypeNames = suggestedTypeNames.map(function (x) {
return "\"".concat(x, "\"");
});
var quotedFieldNames = suggestedFieldNames.map(function (x) {
return "\"".concat(x, "\"");
});
return "Cannot query field \"".concat(fieldName, "\" on type \"").concat(type, "\".") + (didYouMean('to use an inline fragment on', quotedTypeNames) || didYouMean(quotedFieldNames));
}
/**
* Fields on correct type
*
* A GraphQL document is only valid if all fields selected are defined by the
* parent type, or are an allowed meta field such as __typename.
*/
export function FieldsOnCorrectType(context) {
return {
Field: function Field(node) {
var type = context.getParentType();
if (type) {
var fieldDef = context.getFieldDef();
if (!fieldDef) {
// This field doesn't exist, lets look for suggestions.
var schema = context.getSchema();
var fieldName = node.name.value; // First determine if there are any suggested types to condition on.
var suggestedTypeNames = getSuggestedTypeNames(schema, type, fieldName); // If there are no suggested types, then perhaps this was a typo?
var suggestedFieldNames = suggestedTypeNames.length !== 0 ? [] : getSuggestedFieldNames(schema, type, fieldName); // Report an error, including helpful suggestions.
context.reportError(new GraphQLError(undefinedFieldMessage(fieldName, type.name, suggestedTypeNames, suggestedFieldNames), node));
}
}
}
};
}
/**
* Go through all of the implementations of type, as well as the interfaces that
* they implement. If any of those types include the provided field, suggest
* them, sorted by how often the type is referenced, starting with Interfaces.
*/
function getSuggestedTypeNames(schema, type, fieldName) {
if (isAbstractType(type)) {
var suggestedObjectTypes = [];
var interfaceUsageCount = Object.create(null);
for (var _i2 = 0, _schema$getPossibleTy2 = schema.getPossibleTypes(type); _i2 < _schema$getPossibleTy2.length; _i2++) {
var possibleType = _schema$getPossibleTy2[_i2];
if (!possibleType.getFields()[fieldName]) {
continue;
} // This object type defines this field.
suggestedObjectTypes.push(possibleType.name);
for (var _i4 = 0, _possibleType$getInte2 = possibleType.getInterfaces(); _i4 < _possibleType$getInte2.length; _i4++) {
var possibleInterface = _possibleType$getInte2[_i4];
if (!possibleInterface.getFields()[fieldName]) {
continue;
} // This interface type defines this field.
interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1;
}
} // Suggest interface types based on how common they are.
var suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(function (a, b) {
return interfaceUsageCount[b] - interfaceUsageCount[a];
}); // Suggest both interface and object types.
return suggestedInterfaceTypes.concat(suggestedObjectTypes);
} // Otherwise, must be an Object type, which does not have possible fields.
return [];
}
/**
* For the field name provided, determine if there are any similar field names
* that may be the result of a typo.
*/
function getSuggestedFieldNames(schema, type, fieldName) {
if (isObjectType(type) || isInterfaceType(type)) {
var possibleFieldNames = Object.keys(type.getFields());
return suggestionList(fieldName, possibleFieldNames);
} // Otherwise, must be a Union type, which does not define fields.
return [];
}

View File

@@ -0,0 +1,20 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function inlineFragmentOnNonCompositeErrorMessage(type: string): string;
export function fragmentOnNonCompositeErrorMessage(
fragName: string,
type: string,
): string;
/**
* Fragments on composite type
*
* Fragments use a type condition to determine if they apply, since fragments
* can only be spread into a composite type (object, interface, or union), the
* type condition must also be a composite type.
*/
export function FragmentsOnCompositeTypes(
context: ValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.inlineFragmentOnNonCompositeErrorMessage = inlineFragmentOnNonCompositeErrorMessage;
exports.fragmentOnNonCompositeErrorMessage = fragmentOnNonCompositeErrorMessage;
exports.FragmentsOnCompositeTypes = FragmentsOnCompositeTypes;
var _GraphQLError = require("../../error/GraphQLError");
var _printer = require("../../language/printer");
var _definition = require("../../type/definition");
var _typeFromAST = require("../../utilities/typeFromAST");
function inlineFragmentOnNonCompositeErrorMessage(type) {
return "Fragment cannot condition on non composite type \"".concat(type, "\".");
}
function fragmentOnNonCompositeErrorMessage(fragName, type) {
return "Fragment \"".concat(fragName, "\" cannot condition on non composite type \"").concat(type, "\".");
}
/**
* Fragments on composite type
*
* Fragments use a type condition to determine if they apply, since fragments
* can only be spread into a composite type (object, interface, or union), the
* type condition must also be a composite type.
*/
function FragmentsOnCompositeTypes(context) {
return {
InlineFragment: function InlineFragment(node) {
var typeCondition = node.typeCondition;
if (typeCondition) {
var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition);
if (type && !(0, _definition.isCompositeType)(type)) {
context.reportError(new _GraphQLError.GraphQLError(inlineFragmentOnNonCompositeErrorMessage((0, _printer.print)(typeCondition)), typeCondition));
}
}
},
FragmentDefinition: function FragmentDefinition(node) {
var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition);
if (type && !(0, _definition.isCompositeType)(type)) {
context.reportError(new _GraphQLError.GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, (0, _printer.print)(node.typeCondition)), node.typeCondition));
}
}
};
}

View File

@@ -0,0 +1,65 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { print } from '../../language/printer';
import { type ASTVisitor } from '../../language/visitor';
import { isCompositeType } from '../../type/definition';
import { typeFromAST } from '../../utilities/typeFromAST';
import { type ValidationContext } from '../ValidationContext';
export function inlineFragmentOnNonCompositeErrorMessage(type: string): string {
return `Fragment cannot condition on non composite type "${type}".`;
}
export function fragmentOnNonCompositeErrorMessage(
fragName: string,
type: string,
): string {
return `Fragment "${fragName}" cannot condition on non composite type "${type}".`;
}
/**
* Fragments on composite type
*
* Fragments use a type condition to determine if they apply, since fragments
* can only be spread into a composite type (object, interface, or union), the
* type condition must also be a composite type.
*/
export function FragmentsOnCompositeTypes(
context: ValidationContext,
): ASTVisitor {
return {
InlineFragment(node) {
const typeCondition = node.typeCondition;
if (typeCondition) {
const type = typeFromAST(context.getSchema(), typeCondition);
if (type && !isCompositeType(type)) {
context.reportError(
new GraphQLError(
inlineFragmentOnNonCompositeErrorMessage(print(typeCondition)),
typeCondition,
),
);
}
}
},
FragmentDefinition(node) {
const type = typeFromAST(context.getSchema(), node.typeCondition);
if (type && !isCompositeType(type)) {
context.reportError(
new GraphQLError(
fragmentOnNonCompositeErrorMessage(
node.name.value,
print(node.typeCondition),
),
node.typeCondition,
),
);
}
},
};
}

View File

@@ -0,0 +1,40 @@
import { GraphQLError } from '../../error/GraphQLError';
import { print } from '../../language/printer';
import { isCompositeType } from '../../type/definition';
import { typeFromAST } from '../../utilities/typeFromAST';
export function inlineFragmentOnNonCompositeErrorMessage(type) {
return "Fragment cannot condition on non composite type \"".concat(type, "\".");
}
export function fragmentOnNonCompositeErrorMessage(fragName, type) {
return "Fragment \"".concat(fragName, "\" cannot condition on non composite type \"").concat(type, "\".");
}
/**
* Fragments on composite type
*
* Fragments use a type condition to determine if they apply, since fragments
* can only be spread into a composite type (object, interface, or union), the
* type condition must also be a composite type.
*/
export function FragmentsOnCompositeTypes(context) {
return {
InlineFragment: function InlineFragment(node) {
var typeCondition = node.typeCondition;
if (typeCondition) {
var type = typeFromAST(context.getSchema(), typeCondition);
if (type && !isCompositeType(type)) {
context.reportError(new GraphQLError(inlineFragmentOnNonCompositeErrorMessage(print(typeCondition)), typeCondition));
}
}
},
FragmentDefinition: function FragmentDefinition(node) {
var type = typeFromAST(context.getSchema(), node.typeCondition);
if (type && !isCompositeType(type)) {
context.reportError(new GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, print(node.typeCondition)), node.typeCondition));
}
}
};
}

View File

@@ -0,0 +1,28 @@
import { ValidationContext, SDLValidationContext } from '../ValidationContext';
import { ASTVisitor } from '../../language/visitor';
export function unknownArgMessage(
argName: string,
fieldName: string,
typeName: string,
suggestedArgs: ReadonlyArray<string>,
): string;
export function unknownDirectiveArgMessage(
argName: string,
directiveName: string,
suggestedArgs: ReadonlyArray<string>,
): string;
/**
* Known argument names
*
* A GraphQL field is only valid if all supplied arguments are defined by
* that field.
*/
export function KnownArgumentNames(context: ValidationContext): ASTVisitor;
// @internal
export function KnownArgumentNamesOnDirectives(
context: ValidationContext | SDLValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,111 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unknownArgMessage = unknownArgMessage;
exports.unknownDirectiveArgMessage = unknownDirectiveArgMessage;
exports.KnownArgumentNames = KnownArgumentNames;
exports.KnownArgumentNamesOnDirectives = KnownArgumentNamesOnDirectives;
var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean"));
var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
var _GraphQLError = require("../../error/GraphQLError");
var _kinds = require("../../language/kinds");
var _directives = require("../../type/directives");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function unknownArgMessage(argName, fieldName, typeName, suggestedArgs) {
return "Unknown argument \"".concat(argName, "\" on field \"").concat(fieldName, "\" of type \"").concat(typeName, "\".") + (0, _didYouMean.default)(suggestedArgs.map(function (x) {
return "\"".concat(x, "\"");
}));
}
function unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) {
return "Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\".") + (0, _didYouMean.default)(suggestedArgs.map(function (x) {
return "\"".concat(x, "\"");
}));
}
/**
* Known argument names
*
* A GraphQL field is only valid if all supplied arguments are defined by
* that field.
*/
function KnownArgumentNames(context) {
return _objectSpread({}, KnownArgumentNamesOnDirectives(context), {
Argument: function Argument(argNode) {
var argDef = context.getArgument();
var fieldDef = context.getFieldDef();
var parentType = context.getParentType();
if (!argDef && fieldDef && parentType) {
var argName = argNode.name.value;
var knownArgsNames = fieldDef.args.map(function (arg) {
return arg.name;
});
context.reportError(new _GraphQLError.GraphQLError(unknownArgMessage(argName, fieldDef.name, parentType.name, (0, _suggestionList.default)(argName, knownArgsNames)), argNode));
}
}
});
} // @internal
function KnownArgumentNamesOnDirectives(context) {
var directiveArgs = Object.create(null);
var schema = context.getSchema();
var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {
var directive = definedDirectives[_i2];
directiveArgs[directive.name] = directive.args.map(function (arg) {
return arg.name;
});
}
var astDefinitions = context.getDocument().definitions;
for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {
var def = astDefinitions[_i4];
if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
directiveArgs[def.name.value] = def.arguments ? def.arguments.map(function (arg) {
return arg.name.value;
}) : [];
}
}
return {
Directive: function Directive(directiveNode) {
var directiveName = directiveNode.name.value;
var knownArgs = directiveArgs[directiveName];
if (directiveNode.arguments && knownArgs) {
for (var _i6 = 0, _directiveNode$argume2 = directiveNode.arguments; _i6 < _directiveNode$argume2.length; _i6++) {
var argNode = _directiveNode$argume2[_i6];
var argName = argNode.name.value;
if (knownArgs.indexOf(argName) === -1) {
var suggestions = (0, _suggestionList.default)(argName, knownArgs);
context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveArgMessage(argName, directiveName, suggestions), argNode));
}
}
}
return false;
}
};
}

View File

@@ -0,0 +1,120 @@
// @flow strict
import didYouMean from '../../jsutils/didYouMean';
import suggestionList from '../../jsutils/suggestionList';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { type ASTVisitor } from '../../language/visitor';
import { specifiedDirectives } from '../../type/directives';
import {
type ValidationContext,
type SDLValidationContext,
} from '../ValidationContext';
export function unknownArgMessage(
argName: string,
fieldName: string,
typeName: string,
suggestedArgs: $ReadOnlyArray<string>,
): string {
return (
`Unknown argument "${argName}" on field "${fieldName}" of type "${typeName}".` +
didYouMean(suggestedArgs.map(x => `"${x}"`))
);
}
export function unknownDirectiveArgMessage(
argName: string,
directiveName: string,
suggestedArgs: $ReadOnlyArray<string>,
): string {
return (
`Unknown argument "${argName}" on directive "@${directiveName}".` +
didYouMean(suggestedArgs.map(x => `"${x}"`))
);
}
/**
* Known argument names
*
* A GraphQL field is only valid if all supplied arguments are defined by
* that field.
*/
export function KnownArgumentNames(context: ValidationContext): ASTVisitor {
return {
...KnownArgumentNamesOnDirectives(context),
Argument(argNode) {
const argDef = context.getArgument();
const fieldDef = context.getFieldDef();
const parentType = context.getParentType();
if (!argDef && fieldDef && parentType) {
const argName = argNode.name.value;
const knownArgsNames = fieldDef.args.map(arg => arg.name);
context.reportError(
new GraphQLError(
unknownArgMessage(
argName,
fieldDef.name,
parentType.name,
suggestionList(argName, knownArgsNames),
),
argNode,
),
);
}
},
};
}
// @internal
export function KnownArgumentNamesOnDirectives(
context: ValidationContext | SDLValidationContext,
): ASTVisitor {
const directiveArgs = Object.create(null);
const schema = context.getSchema();
const definedDirectives = schema
? schema.getDirectives()
: specifiedDirectives;
for (const directive of definedDirectives) {
directiveArgs[directive.name] = directive.args.map(arg => arg.name);
}
const astDefinitions = context.getDocument().definitions;
for (const def of astDefinitions) {
if (def.kind === Kind.DIRECTIVE_DEFINITION) {
directiveArgs[def.name.value] = def.arguments
? def.arguments.map(arg => arg.name.value)
: [];
}
}
return {
Directive(directiveNode) {
const directiveName = directiveNode.name.value;
const knownArgs = directiveArgs[directiveName];
if (directiveNode.arguments && knownArgs) {
for (const argNode of directiveNode.arguments) {
const argName = argNode.name.value;
if (knownArgs.indexOf(argName) === -1) {
const suggestions = suggestionList(argName, knownArgs);
context.reportError(
new GraphQLError(
unknownDirectiveArgMessage(argName, directiveName, suggestions),
argNode,
),
);
}
}
}
return false;
},
};
}

View File

@@ -0,0 +1,91 @@
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import didYouMean from '../../jsutils/didYouMean';
import suggestionList from '../../jsutils/suggestionList';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { specifiedDirectives } from '../../type/directives';
export function unknownArgMessage(argName, fieldName, typeName, suggestedArgs) {
return "Unknown argument \"".concat(argName, "\" on field \"").concat(fieldName, "\" of type \"").concat(typeName, "\".") + didYouMean(suggestedArgs.map(function (x) {
return "\"".concat(x, "\"");
}));
}
export function unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) {
return "Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\".") + didYouMean(suggestedArgs.map(function (x) {
return "\"".concat(x, "\"");
}));
}
/**
* Known argument names
*
* A GraphQL field is only valid if all supplied arguments are defined by
* that field.
*/
export function KnownArgumentNames(context) {
return _objectSpread({}, KnownArgumentNamesOnDirectives(context), {
Argument: function Argument(argNode) {
var argDef = context.getArgument();
var fieldDef = context.getFieldDef();
var parentType = context.getParentType();
if (!argDef && fieldDef && parentType) {
var argName = argNode.name.value;
var knownArgsNames = fieldDef.args.map(function (arg) {
return arg.name;
});
context.reportError(new GraphQLError(unknownArgMessage(argName, fieldDef.name, parentType.name, suggestionList(argName, knownArgsNames)), argNode));
}
}
});
} // @internal
export function KnownArgumentNamesOnDirectives(context) {
var directiveArgs = Object.create(null);
var schema = context.getSchema();
var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;
for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {
var directive = definedDirectives[_i2];
directiveArgs[directive.name] = directive.args.map(function (arg) {
return arg.name;
});
}
var astDefinitions = context.getDocument().definitions;
for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {
var def = astDefinitions[_i4];
if (def.kind === Kind.DIRECTIVE_DEFINITION) {
directiveArgs[def.name.value] = def.arguments ? def.arguments.map(function (arg) {
return arg.name.value;
}) : [];
}
}
return {
Directive: function Directive(directiveNode) {
var directiveName = directiveNode.name.value;
var knownArgs = directiveArgs[directiveName];
if (directiveNode.arguments && knownArgs) {
for (var _i6 = 0, _directiveNode$argume2 = directiveNode.arguments; _i6 < _directiveNode$argume2.length; _i6++) {
var argNode = _directiveNode$argume2[_i6];
var argName = argNode.name.value;
if (knownArgs.indexOf(argName) === -1) {
var suggestions = suggestionList(argName, knownArgs);
context.reportError(new GraphQLError(unknownDirectiveArgMessage(argName, directiveName, suggestions), argNode));
}
}
}
return false;
}
};
}

View File

@@ -0,0 +1,19 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext, SDLValidationContext } from '../ValidationContext';
export function unknownDirectiveMessage(directiveName: string): string;
export function misplacedDirectiveMessage(
directiveName: string,
location: string,
): string;
/**
* Known directives
*
* A GraphQL document is only valid if all `@directives` are known by the
* schema and legally positioned.
*/
export function KnownDirectives(
context: ValidationContext | SDLValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,149 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unknownDirectiveMessage = unknownDirectiveMessage;
exports.misplacedDirectiveMessage = misplacedDirectiveMessage;
exports.KnownDirectives = KnownDirectives;
var _GraphQLError = require("../../error/GraphQLError");
var _kinds = require("../../language/kinds");
var _directiveLocation = require("../../language/directiveLocation");
var _directives = require("../../type/directives");
function unknownDirectiveMessage(directiveName) {
return "Unknown directive \"".concat(directiveName, "\".");
}
function misplacedDirectiveMessage(directiveName, location) {
return "Directive \"".concat(directiveName, "\" may not be used on ").concat(location, ".");
}
/**
* Known directives
*
* A GraphQL document is only valid if all `@directives` are known by the
* schema and legally positioned.
*/
function KnownDirectives(context) {
var locationsMap = Object.create(null);
var schema = context.getSchema();
var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {
var directive = definedDirectives[_i2];
locationsMap[directive.name] = directive.locations;
}
var astDefinitions = context.getDocument().definitions;
for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {
var def = astDefinitions[_i4];
if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
locationsMap[def.name.value] = def.locations.map(function (name) {
return name.value;
});
}
}
return {
Directive: function Directive(node, key, parent, path, ancestors) {
var name = node.name.value;
var locations = locationsMap[name];
if (!locations) {
context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveMessage(name), node));
return;
}
var candidateLocation = getDirectiveLocationForASTPath(ancestors);
if (candidateLocation && locations.indexOf(candidateLocation) === -1) {
context.reportError(new _GraphQLError.GraphQLError(misplacedDirectiveMessage(name, candidateLocation), node));
}
}
};
}
function getDirectiveLocationForASTPath(ancestors) {
var appliedTo = ancestors[ancestors.length - 1];
if (!Array.isArray(appliedTo)) {
switch (appliedTo.kind) {
case _kinds.Kind.OPERATION_DEFINITION:
switch (appliedTo.operation) {
case 'query':
return _directiveLocation.DirectiveLocation.QUERY;
case 'mutation':
return _directiveLocation.DirectiveLocation.MUTATION;
case 'subscription':
return _directiveLocation.DirectiveLocation.SUBSCRIPTION;
}
break;
case _kinds.Kind.FIELD:
return _directiveLocation.DirectiveLocation.FIELD;
case _kinds.Kind.FRAGMENT_SPREAD:
return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD;
case _kinds.Kind.INLINE_FRAGMENT:
return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT;
case _kinds.Kind.FRAGMENT_DEFINITION:
return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION;
case _kinds.Kind.VARIABLE_DEFINITION:
return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION;
case _kinds.Kind.SCHEMA_DEFINITION:
case _kinds.Kind.SCHEMA_EXTENSION:
return _directiveLocation.DirectiveLocation.SCHEMA;
case _kinds.Kind.SCALAR_TYPE_DEFINITION:
case _kinds.Kind.SCALAR_TYPE_EXTENSION:
return _directiveLocation.DirectiveLocation.SCALAR;
case _kinds.Kind.OBJECT_TYPE_DEFINITION:
case _kinds.Kind.OBJECT_TYPE_EXTENSION:
return _directiveLocation.DirectiveLocation.OBJECT;
case _kinds.Kind.FIELD_DEFINITION:
return _directiveLocation.DirectiveLocation.FIELD_DEFINITION;
case _kinds.Kind.INTERFACE_TYPE_DEFINITION:
case _kinds.Kind.INTERFACE_TYPE_EXTENSION:
return _directiveLocation.DirectiveLocation.INTERFACE;
case _kinds.Kind.UNION_TYPE_DEFINITION:
case _kinds.Kind.UNION_TYPE_EXTENSION:
return _directiveLocation.DirectiveLocation.UNION;
case _kinds.Kind.ENUM_TYPE_DEFINITION:
case _kinds.Kind.ENUM_TYPE_EXTENSION:
return _directiveLocation.DirectiveLocation.ENUM;
case _kinds.Kind.ENUM_VALUE_DEFINITION:
return _directiveLocation.DirectiveLocation.ENUM_VALUE;
case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION:
case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION:
return _directiveLocation.DirectiveLocation.INPUT_OBJECT;
case _kinds.Kind.INPUT_VALUE_DEFINITION:
{
var parentNode = ancestors[ancestors.length - 3];
return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION;
}
}
}
}

View File

@@ -0,0 +1,134 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { type ASTVisitor } from '../../language/visitor';
import { DirectiveLocation } from '../../language/directiveLocation';
import { specifiedDirectives } from '../../type/directives';
import {
type ValidationContext,
type SDLValidationContext,
} from '../ValidationContext';
export function unknownDirectiveMessage(directiveName: string): string {
return `Unknown directive "${directiveName}".`;
}
export function misplacedDirectiveMessage(
directiveName: string,
location: string,
): string {
return `Directive "${directiveName}" may not be used on ${location}.`;
}
/**
* Known directives
*
* A GraphQL document is only valid if all `@directives` are known by the
* schema and legally positioned.
*/
export function KnownDirectives(
context: ValidationContext | SDLValidationContext,
): ASTVisitor {
const locationsMap = Object.create(null);
const schema = context.getSchema();
const definedDirectives = schema
? schema.getDirectives()
: specifiedDirectives;
for (const directive of definedDirectives) {
locationsMap[directive.name] = directive.locations;
}
const astDefinitions = context.getDocument().definitions;
for (const def of astDefinitions) {
if (def.kind === Kind.DIRECTIVE_DEFINITION) {
locationsMap[def.name.value] = def.locations.map(name => name.value);
}
}
return {
Directive(node, key, parent, path, ancestors) {
const name = node.name.value;
const locations = locationsMap[name];
if (!locations) {
context.reportError(
new GraphQLError(unknownDirectiveMessage(name), node),
);
return;
}
const candidateLocation = getDirectiveLocationForASTPath(ancestors);
if (candidateLocation && locations.indexOf(candidateLocation) === -1) {
context.reportError(
new GraphQLError(
misplacedDirectiveMessage(name, candidateLocation),
node,
),
);
}
},
};
}
function getDirectiveLocationForASTPath(ancestors) {
const appliedTo = ancestors[ancestors.length - 1];
if (!Array.isArray(appliedTo)) {
switch (appliedTo.kind) {
case Kind.OPERATION_DEFINITION:
switch (appliedTo.operation) {
case 'query':
return DirectiveLocation.QUERY;
case 'mutation':
return DirectiveLocation.MUTATION;
case 'subscription':
return DirectiveLocation.SUBSCRIPTION;
}
break;
case Kind.FIELD:
return DirectiveLocation.FIELD;
case Kind.FRAGMENT_SPREAD:
return DirectiveLocation.FRAGMENT_SPREAD;
case Kind.INLINE_FRAGMENT:
return DirectiveLocation.INLINE_FRAGMENT;
case Kind.FRAGMENT_DEFINITION:
return DirectiveLocation.FRAGMENT_DEFINITION;
case Kind.VARIABLE_DEFINITION:
return DirectiveLocation.VARIABLE_DEFINITION;
case Kind.SCHEMA_DEFINITION:
case Kind.SCHEMA_EXTENSION:
return DirectiveLocation.SCHEMA;
case Kind.SCALAR_TYPE_DEFINITION:
case Kind.SCALAR_TYPE_EXTENSION:
return DirectiveLocation.SCALAR;
case Kind.OBJECT_TYPE_DEFINITION:
case Kind.OBJECT_TYPE_EXTENSION:
return DirectiveLocation.OBJECT;
case Kind.FIELD_DEFINITION:
return DirectiveLocation.FIELD_DEFINITION;
case Kind.INTERFACE_TYPE_DEFINITION:
case Kind.INTERFACE_TYPE_EXTENSION:
return DirectiveLocation.INTERFACE;
case Kind.UNION_TYPE_DEFINITION:
case Kind.UNION_TYPE_EXTENSION:
return DirectiveLocation.UNION;
case Kind.ENUM_TYPE_DEFINITION:
case Kind.ENUM_TYPE_EXTENSION:
return DirectiveLocation.ENUM;
case Kind.ENUM_VALUE_DEFINITION:
return DirectiveLocation.ENUM_VALUE;
case Kind.INPUT_OBJECT_TYPE_DEFINITION:
case Kind.INPUT_OBJECT_TYPE_EXTENSION:
return DirectiveLocation.INPUT_OBJECT;
case Kind.INPUT_VALUE_DEFINITION: {
const parentNode = ancestors[ancestors.length - 3];
return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION
? DirectiveLocation.INPUT_FIELD_DEFINITION
: DirectiveLocation.ARGUMENT_DEFINITION;
}
}
}
}

View File

@@ -0,0 +1,134 @@
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { DirectiveLocation } from '../../language/directiveLocation';
import { specifiedDirectives } from '../../type/directives';
export function unknownDirectiveMessage(directiveName) {
return "Unknown directive \"".concat(directiveName, "\".");
}
export function misplacedDirectiveMessage(directiveName, location) {
return "Directive \"".concat(directiveName, "\" may not be used on ").concat(location, ".");
}
/**
* Known directives
*
* A GraphQL document is only valid if all `@directives` are known by the
* schema and legally positioned.
*/
export function KnownDirectives(context) {
var locationsMap = Object.create(null);
var schema = context.getSchema();
var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;
for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {
var directive = definedDirectives[_i2];
locationsMap[directive.name] = directive.locations;
}
var astDefinitions = context.getDocument().definitions;
for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {
var def = astDefinitions[_i4];
if (def.kind === Kind.DIRECTIVE_DEFINITION) {
locationsMap[def.name.value] = def.locations.map(function (name) {
return name.value;
});
}
}
return {
Directive: function Directive(node, key, parent, path, ancestors) {
var name = node.name.value;
var locations = locationsMap[name];
if (!locations) {
context.reportError(new GraphQLError(unknownDirectiveMessage(name), node));
return;
}
var candidateLocation = getDirectiveLocationForASTPath(ancestors);
if (candidateLocation && locations.indexOf(candidateLocation) === -1) {
context.reportError(new GraphQLError(misplacedDirectiveMessage(name, candidateLocation), node));
}
}
};
}
function getDirectiveLocationForASTPath(ancestors) {
var appliedTo = ancestors[ancestors.length - 1];
if (!Array.isArray(appliedTo)) {
switch (appliedTo.kind) {
case Kind.OPERATION_DEFINITION:
switch (appliedTo.operation) {
case 'query':
return DirectiveLocation.QUERY;
case 'mutation':
return DirectiveLocation.MUTATION;
case 'subscription':
return DirectiveLocation.SUBSCRIPTION;
}
break;
case Kind.FIELD:
return DirectiveLocation.FIELD;
case Kind.FRAGMENT_SPREAD:
return DirectiveLocation.FRAGMENT_SPREAD;
case Kind.INLINE_FRAGMENT:
return DirectiveLocation.INLINE_FRAGMENT;
case Kind.FRAGMENT_DEFINITION:
return DirectiveLocation.FRAGMENT_DEFINITION;
case Kind.VARIABLE_DEFINITION:
return DirectiveLocation.VARIABLE_DEFINITION;
case Kind.SCHEMA_DEFINITION:
case Kind.SCHEMA_EXTENSION:
return DirectiveLocation.SCHEMA;
case Kind.SCALAR_TYPE_DEFINITION:
case Kind.SCALAR_TYPE_EXTENSION:
return DirectiveLocation.SCALAR;
case Kind.OBJECT_TYPE_DEFINITION:
case Kind.OBJECT_TYPE_EXTENSION:
return DirectiveLocation.OBJECT;
case Kind.FIELD_DEFINITION:
return DirectiveLocation.FIELD_DEFINITION;
case Kind.INTERFACE_TYPE_DEFINITION:
case Kind.INTERFACE_TYPE_EXTENSION:
return DirectiveLocation.INTERFACE;
case Kind.UNION_TYPE_DEFINITION:
case Kind.UNION_TYPE_EXTENSION:
return DirectiveLocation.UNION;
case Kind.ENUM_TYPE_DEFINITION:
case Kind.ENUM_TYPE_EXTENSION:
return DirectiveLocation.ENUM;
case Kind.ENUM_VALUE_DEFINITION:
return DirectiveLocation.ENUM_VALUE;
case Kind.INPUT_OBJECT_TYPE_DEFINITION:
case Kind.INPUT_OBJECT_TYPE_EXTENSION:
return DirectiveLocation.INPUT_OBJECT;
case Kind.INPUT_VALUE_DEFINITION:
{
var parentNode = ancestors[ancestors.length - 3];
return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? DirectiveLocation.INPUT_FIELD_DEFINITION : DirectiveLocation.ARGUMENT_DEFINITION;
}
}
}
}

View File

@@ -0,0 +1,12 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function unknownFragmentMessage(fragName: string): string;
/**
* Known fragment names
*
* A GraphQL document is only valid if all `...Fragment` fragment spreads refer
* to fragments defined in the same document.
*/
export function KnownFragmentNames(context: ValidationContext): ASTVisitor;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unknownFragmentMessage = unknownFragmentMessage;
exports.KnownFragmentNames = KnownFragmentNames;
var _GraphQLError = require("../../error/GraphQLError");
function unknownFragmentMessage(fragName) {
return "Unknown fragment \"".concat(fragName, "\".");
}
/**
* Known fragment names
*
* A GraphQL document is only valid if all `...Fragment` fragment spreads refer
* to fragments defined in the same document.
*/
function KnownFragmentNames(context) {
return {
FragmentSpread: function FragmentSpread(node) {
var fragmentName = node.name.value;
var fragment = context.getFragment(fragmentName);
if (!fragment) {
context.reportError(new _GraphQLError.GraphQLError(unknownFragmentMessage(fragmentName), node.name));
}
}
};
}

View File

@@ -0,0 +1,30 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type ValidationContext } from '../ValidationContext';
export function unknownFragmentMessage(fragName: string): string {
return `Unknown fragment "${fragName}".`;
}
/**
* Known fragment names
*
* A GraphQL document is only valid if all `...Fragment` fragment spreads refer
* to fragments defined in the same document.
*/
export function KnownFragmentNames(context: ValidationContext): ASTVisitor {
return {
FragmentSpread(node) {
const fragmentName = node.name.value;
const fragment = context.getFragment(fragmentName);
if (!fragment) {
context.reportError(
new GraphQLError(unknownFragmentMessage(fragmentName), node.name),
);
}
},
};
}

View File

@@ -0,0 +1,23 @@
import { GraphQLError } from '../../error/GraphQLError';
export function unknownFragmentMessage(fragName) {
return "Unknown fragment \"".concat(fragName, "\".");
}
/**
* Known fragment names
*
* A GraphQL document is only valid if all `...Fragment` fragment spreads refer
* to fragments defined in the same document.
*/
export function KnownFragmentNames(context) {
return {
FragmentSpread: function FragmentSpread(node) {
var fragmentName = node.name.value;
var fragment = context.getFragment(fragmentName);
if (!fragment) {
context.reportError(new GraphQLError(unknownFragmentMessage(fragmentName), node.name));
}
}
};
}

View File

@@ -0,0 +1,15 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function unknownTypeMessage(
typeName: string,
suggestedTypes: Array<string>,
): string;
/**
* Known type names
*
* A GraphQL document is only valid if referenced types (specifically
* variable definitions and fragment conditions) are defined by the type schema.
*/
export function KnownTypeNames(context: ValidationContext): ASTVisitor;

View File

@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unknownTypeMessage = unknownTypeMessage;
exports.KnownTypeNames = KnownTypeNames;
var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean"));
var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
var _GraphQLError = require("../../error/GraphQLError");
var _predicates = require("../../language/predicates");
var _scalars = require("../../type/scalars");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function unknownTypeMessage(typeName, suggestedTypes) {
return "Unknown type \"".concat(typeName, "\".") + (0, _didYouMean.default)(suggestedTypes.map(function (x) {
return "\"".concat(x, "\"");
}));
}
/**
* Known type names
*
* A GraphQL document is only valid if referenced types (specifically
* variable definitions and fragment conditions) are defined by the type schema.
*/
function KnownTypeNames(context) {
var schema = context.getSchema();
var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);
var definedTypes = Object.create(null);
for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {
var def = _context$getDocument$2[_i2];
if ((0, _predicates.isTypeDefinitionNode)(def)) {
definedTypes[def.name.value] = true;
}
}
var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));
return {
NamedType: function NamedType(node, _1, parent, _2, ancestors) {
var typeName = node.name.value;
if (!existingTypesMap[typeName] && !definedTypes[typeName]) {
var definitionNode = ancestors[2] || parent;
var isSDL = isSDLNode(definitionNode);
if (isSDL && isSpecifiedScalarName(typeName)) {
return;
}
var suggestedTypes = (0, _suggestionList.default)(typeName, isSDL ? specifiedScalarsNames.concat(typeNames) : typeNames);
context.reportError(new _GraphQLError.GraphQLError(unknownTypeMessage(typeName, suggestedTypes), node));
}
}
};
}
var specifiedScalarsNames = _scalars.specifiedScalarTypes.map(function (type) {
return type.name;
});
function isSpecifiedScalarName(typeName) {
return specifiedScalarsNames.indexOf(typeName) !== -1;
}
function isSDLNode(value) {
return Boolean(value && !Array.isArray(value) && ((0, _predicates.isTypeSystemDefinitionNode)(value) || (0, _predicates.isTypeSystemExtensionNode)(value)));
}

View File

@@ -0,0 +1,89 @@
// @flow strict
import didYouMean from '../../jsutils/didYouMean';
import suggestionList from '../../jsutils/suggestionList';
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTNode } from '../../language/ast';
import { type ASTVisitor } from '../../language/visitor';
import {
isTypeDefinitionNode,
isTypeSystemDefinitionNode,
isTypeSystemExtensionNode,
} from '../../language/predicates';
import { specifiedScalarTypes } from '../../type/scalars';
import {
type ValidationContext,
type SDLValidationContext,
} from '../ValidationContext';
export function unknownTypeMessage(
typeName: string,
suggestedTypes: $ReadOnlyArray<string>,
): string {
return (
`Unknown type "${typeName}".` +
didYouMean(suggestedTypes.map(x => `"${x}"`))
);
}
/**
* Known type names
*
* A GraphQL document is only valid if referenced types (specifically
* variable definitions and fragment conditions) are defined by the type schema.
*/
export function KnownTypeNames(
context: ValidationContext | SDLValidationContext,
): ASTVisitor {
const schema = context.getSchema();
const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);
const definedTypes = Object.create(null);
for (const def of context.getDocument().definitions) {
if (isTypeDefinitionNode(def)) {
definedTypes[def.name.value] = true;
}
}
const typeNames = Object.keys(existingTypesMap).concat(
Object.keys(definedTypes),
);
return {
NamedType(node, _1, parent, _2, ancestors) {
const typeName = node.name.value;
if (!existingTypesMap[typeName] && !definedTypes[typeName]) {
const definitionNode = ancestors[2] || parent;
const isSDL = isSDLNode(definitionNode);
if (isSDL && isSpecifiedScalarName(typeName)) {
return;
}
const suggestedTypes = suggestionList(
typeName,
isSDL ? specifiedScalarsNames.concat(typeNames) : typeNames,
);
context.reportError(
new GraphQLError(unknownTypeMessage(typeName, suggestedTypes), node),
);
}
},
};
}
const specifiedScalarsNames = specifiedScalarTypes.map(type => type.name);
function isSpecifiedScalarName(typeName) {
return specifiedScalarsNames.indexOf(typeName) !== -1;
}
function isSDLNode(value: ASTNode | $ReadOnlyArray<ASTNode> | void): boolean {
return Boolean(
value &&
!Array.isArray(value) &&
(isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value)),
);
}

View File

@@ -0,0 +1,60 @@
import didYouMean from '../../jsutils/didYouMean';
import suggestionList from '../../jsutils/suggestionList';
import { GraphQLError } from '../../error/GraphQLError';
import { isTypeDefinitionNode, isTypeSystemDefinitionNode, isTypeSystemExtensionNode } from '../../language/predicates';
import { specifiedScalarTypes } from '../../type/scalars';
export function unknownTypeMessage(typeName, suggestedTypes) {
return "Unknown type \"".concat(typeName, "\".") + didYouMean(suggestedTypes.map(function (x) {
return "\"".concat(x, "\"");
}));
}
/**
* Known type names
*
* A GraphQL document is only valid if referenced types (specifically
* variable definitions and fragment conditions) are defined by the type schema.
*/
export function KnownTypeNames(context) {
var schema = context.getSchema();
var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);
var definedTypes = Object.create(null);
for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {
var def = _context$getDocument$2[_i2];
if (isTypeDefinitionNode(def)) {
definedTypes[def.name.value] = true;
}
}
var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));
return {
NamedType: function NamedType(node, _1, parent, _2, ancestors) {
var typeName = node.name.value;
if (!existingTypesMap[typeName] && !definedTypes[typeName]) {
var definitionNode = ancestors[2] || parent;
var isSDL = isSDLNode(definitionNode);
if (isSDL && isSpecifiedScalarName(typeName)) {
return;
}
var suggestedTypes = suggestionList(typeName, isSDL ? specifiedScalarsNames.concat(typeNames) : typeNames);
context.reportError(new GraphQLError(unknownTypeMessage(typeName, suggestedTypes), node));
}
}
};
}
var specifiedScalarsNames = specifiedScalarTypes.map(function (type) {
return type.name;
});
function isSpecifiedScalarName(typeName) {
return specifiedScalarsNames.indexOf(typeName) !== -1;
}
function isSDLNode(value) {
return Boolean(value && !Array.isArray(value) && (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value)));
}

View File

@@ -0,0 +1,14 @@
import { ASTVisitor } from '../../language/visitor';
import { ASTValidationContext } from '../ValidationContext';
export function anonOperationNotAloneMessage(): string;
/**
* Lone anonymous operation
*
* A GraphQL document is only valid if when it contains an anonymous operation
* (the query short-hand) that it contains only that one operation definition.
*/
export function LoneAnonymousOperation(
context: ASTValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.anonOperationNotAloneMessage = anonOperationNotAloneMessage;
exports.LoneAnonymousOperation = LoneAnonymousOperation;
var _GraphQLError = require("../../error/GraphQLError");
var _kinds = require("../../language/kinds");
function anonOperationNotAloneMessage() {
return 'This anonymous operation must be the only defined operation.';
}
/**
* Lone anonymous operation
*
* A GraphQL document is only valid if when it contains an anonymous operation
* (the query short-hand) that it contains only that one operation definition.
*/
function LoneAnonymousOperation(context) {
var operationCount = 0;
return {
Document: function Document(node) {
operationCount = node.definitions.filter(function (definition) {
return definition.kind === _kinds.Kind.OPERATION_DEFINITION;
}).length;
},
OperationDefinition: function OperationDefinition(node) {
if (!node.name && operationCount > 1) {
context.reportError(new _GraphQLError.GraphQLError(anonOperationNotAloneMessage(), node));
}
}
};
}

View File

@@ -0,0 +1,38 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { type ASTVisitor } from '../../language/visitor';
import { type ASTValidationContext } from '../ValidationContext';
export function anonOperationNotAloneMessage(): string {
return 'This anonymous operation must be the only defined operation.';
}
/**
* Lone anonymous operation
*
* A GraphQL document is only valid if when it contains an anonymous operation
* (the query short-hand) that it contains only that one operation definition.
*/
export function LoneAnonymousOperation(
context: ASTValidationContext,
): ASTVisitor {
let operationCount = 0;
return {
Document(node) {
operationCount = node.definitions.filter(
definition => definition.kind === Kind.OPERATION_DEFINITION,
).length;
},
OperationDefinition(node) {
if (!node.name && operationCount > 1) {
context.reportError(
new GraphQLError(anonOperationNotAloneMessage(), node),
);
}
},
};
}

View File

@@ -0,0 +1,27 @@
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
export function anonOperationNotAloneMessage() {
return 'This anonymous operation must be the only defined operation.';
}
/**
* Lone anonymous operation
*
* A GraphQL document is only valid if when it contains an anonymous operation
* (the query short-hand) that it contains only that one operation definition.
*/
export function LoneAnonymousOperation(context) {
var operationCount = 0;
return {
Document: function Document(node) {
operationCount = node.definitions.filter(function (definition) {
return definition.kind === Kind.OPERATION_DEFINITION;
}).length;
},
OperationDefinition: function OperationDefinition(node) {
if (!node.name && operationCount > 1) {
context.reportError(new GraphQLError(anonOperationNotAloneMessage(), node));
}
}
};
}

View File

@@ -0,0 +1,13 @@
import { ASTVisitor } from '../../language/visitor';
import { SDLValidationContext } from '../ValidationContext';
export function schemaDefinitionNotAloneMessage(): string;
export function canNotDefineSchemaWithinExtensionMessage(): string;
/**
* Lone Schema definition
*
* A GraphQL document is only valid if it contains only one schema definition.
*/
export function LoneSchemaDefinition(context: SDLValidationContext): ASTVisitor;

View File

@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.schemaDefinitionNotAloneMessage = schemaDefinitionNotAloneMessage;
exports.canNotDefineSchemaWithinExtensionMessage = canNotDefineSchemaWithinExtensionMessage;
exports.LoneSchemaDefinition = LoneSchemaDefinition;
var _GraphQLError = require("../../error/GraphQLError");
function schemaDefinitionNotAloneMessage() {
return 'Must provide only one schema definition.';
}
function canNotDefineSchemaWithinExtensionMessage() {
return 'Cannot define a new schema within a schema extension.';
}
/**
* Lone Schema definition
*
* A GraphQL document is only valid if it contains only one schema definition.
*/
function LoneSchemaDefinition(context) {
var oldSchema = context.getSchema();
var alreadyDefined = oldSchema && (oldSchema.astNode || oldSchema.getQueryType() || oldSchema.getMutationType() || oldSchema.getSubscriptionType());
var schemaDefinitionsCount = 0;
return {
SchemaDefinition: function SchemaDefinition(node) {
if (alreadyDefined) {
context.reportError(new _GraphQLError.GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node));
return;
}
if (schemaDefinitionsCount > 0) {
context.reportError(new _GraphQLError.GraphQLError(schemaDefinitionNotAloneMessage(), node));
}
++schemaDefinitionsCount;
}
};
}

View File

@@ -0,0 +1,50 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type SDLValidationContext } from '../ValidationContext';
export function schemaDefinitionNotAloneMessage(): string {
return 'Must provide only one schema definition.';
}
export function canNotDefineSchemaWithinExtensionMessage(): string {
return 'Cannot define a new schema within a schema extension.';
}
/**
* Lone Schema definition
*
* A GraphQL document is only valid if it contains only one schema definition.
*/
export function LoneSchemaDefinition(
context: SDLValidationContext,
): ASTVisitor {
const oldSchema = context.getSchema();
const alreadyDefined =
oldSchema &&
(oldSchema.astNode ||
oldSchema.getQueryType() ||
oldSchema.getMutationType() ||
oldSchema.getSubscriptionType());
let schemaDefinitionsCount = 0;
return {
SchemaDefinition(node) {
if (alreadyDefined) {
context.reportError(
new GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node),
);
return;
}
if (schemaDefinitionsCount > 0) {
context.reportError(
new GraphQLError(schemaDefinitionNotAloneMessage(), node),
);
}
++schemaDefinitionsCount;
},
};
}

View File

@@ -0,0 +1,32 @@
import { GraphQLError } from '../../error/GraphQLError';
export function schemaDefinitionNotAloneMessage() {
return 'Must provide only one schema definition.';
}
export function canNotDefineSchemaWithinExtensionMessage() {
return 'Cannot define a new schema within a schema extension.';
}
/**
* Lone Schema definition
*
* A GraphQL document is only valid if it contains only one schema definition.
*/
export function LoneSchemaDefinition(context) {
var oldSchema = context.getSchema();
var alreadyDefined = oldSchema && (oldSchema.astNode || oldSchema.getQueryType() || oldSchema.getMutationType() || oldSchema.getSubscriptionType());
var schemaDefinitionsCount = 0;
return {
SchemaDefinition: function SchemaDefinition(node) {
if (alreadyDefined) {
context.reportError(new GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node));
return;
}
if (schemaDefinitionsCount > 0) {
context.reportError(new GraphQLError(schemaDefinitionNotAloneMessage(), node));
}
++schemaDefinitionsCount;
}
};
}

View File

@@ -0,0 +1,9 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function cycleErrorMessage(
fragName: string,
spreadNames: ReadonlyArray<string>,
): string;
export function NoFragmentCycles(context: ValidationContext): ASTVisitor;

View File

@@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cycleErrorMessage = cycleErrorMessage;
exports.NoFragmentCycles = NoFragmentCycles;
var _GraphQLError = require("../../error/GraphQLError");
function cycleErrorMessage(fragName, spreadNames) {
var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : '';
return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, ".");
}
function NoFragmentCycles(context) {
// Tracks already visited fragments to maintain O(N) and to ensure that cycles
// are not redundantly reported.
var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors
var spreadPath = []; // Position in the spread path
var spreadPathIndexByName = Object.create(null);
return {
OperationDefinition: function OperationDefinition() {
return false;
},
FragmentDefinition: function FragmentDefinition(node) {
detectCycleRecursive(node);
return false;
}
}; // This does a straight-forward DFS to find cycles.
// It does not terminate when a cycle was found but continues to explore
// the graph to find all possible cycles.
function detectCycleRecursive(fragment) {
if (visitedFrags[fragment.name.value]) {
return;
}
var fragmentName = fragment.name.value;
visitedFrags[fragmentName] = true;
var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
if (spreadNodes.length === 0) {
return;
}
spreadPathIndexByName[fragmentName] = spreadPath.length;
for (var _i2 = 0; _i2 < spreadNodes.length; _i2++) {
var spreadNode = spreadNodes[_i2];
var spreadName = spreadNode.name.value;
var cycleIndex = spreadPathIndexByName[spreadName];
spreadPath.push(spreadNode);
if (cycleIndex === undefined) {
var spreadFragment = context.getFragment(spreadName);
if (spreadFragment) {
detectCycleRecursive(spreadFragment);
}
} else {
var cyclePath = spreadPath.slice(cycleIndex);
var fragmentNames = cyclePath.slice(0, -1).map(function (s) {
return s.name.value;
});
context.reportError(new _GraphQLError.GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath));
}
spreadPath.pop();
}
spreadPathIndexByName[fragmentName] = undefined;
}
}

View File

@@ -0,0 +1,80 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type FragmentDefinitionNode } from '../../language/ast';
import { type ASTValidationContext } from '../ValidationContext';
export function cycleErrorMessage(
fragName: string,
spreadNames: $ReadOnlyArray<string>,
): string {
const via = spreadNames.length ? ' via ' + spreadNames.join(', ') : '';
return `Cannot spread fragment "${fragName}" within itself${via}.`;
}
export function NoFragmentCycles(context: ASTValidationContext): ASTVisitor {
// Tracks already visited fragments to maintain O(N) and to ensure that cycles
// are not redundantly reported.
const visitedFrags = Object.create(null);
// Array of AST nodes used to produce meaningful errors
const spreadPath = [];
// Position in the spread path
const spreadPathIndexByName = Object.create(null);
return {
OperationDefinition: () => false,
FragmentDefinition(node) {
detectCycleRecursive(node);
return false;
},
};
// This does a straight-forward DFS to find cycles.
// It does not terminate when a cycle was found but continues to explore
// the graph to find all possible cycles.
function detectCycleRecursive(fragment: FragmentDefinitionNode) {
if (visitedFrags[fragment.name.value]) {
return;
}
const fragmentName = fragment.name.value;
visitedFrags[fragmentName] = true;
const spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
if (spreadNodes.length === 0) {
return;
}
spreadPathIndexByName[fragmentName] = spreadPath.length;
for (const spreadNode of spreadNodes) {
const spreadName = spreadNode.name.value;
const cycleIndex = spreadPathIndexByName[spreadName];
spreadPath.push(spreadNode);
if (cycleIndex === undefined) {
const spreadFragment = context.getFragment(spreadName);
if (spreadFragment) {
detectCycleRecursive(spreadFragment);
}
} else {
const cyclePath = spreadPath.slice(cycleIndex);
const fragmentNames = cyclePath.slice(0, -1).map(s => s.name.value);
context.reportError(
new GraphQLError(
cycleErrorMessage(spreadName, fragmentNames),
cyclePath,
),
);
}
spreadPath.pop();
}
spreadPathIndexByName[fragmentName] = undefined;
}
}

View File

@@ -0,0 +1,66 @@
import { GraphQLError } from '../../error/GraphQLError';
export function cycleErrorMessage(fragName, spreadNames) {
var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : '';
return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, ".");
}
export function NoFragmentCycles(context) {
// Tracks already visited fragments to maintain O(N) and to ensure that cycles
// are not redundantly reported.
var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors
var spreadPath = []; // Position in the spread path
var spreadPathIndexByName = Object.create(null);
return {
OperationDefinition: function OperationDefinition() {
return false;
},
FragmentDefinition: function FragmentDefinition(node) {
detectCycleRecursive(node);
return false;
}
}; // This does a straight-forward DFS to find cycles.
// It does not terminate when a cycle was found but continues to explore
// the graph to find all possible cycles.
function detectCycleRecursive(fragment) {
if (visitedFrags[fragment.name.value]) {
return;
}
var fragmentName = fragment.name.value;
visitedFrags[fragmentName] = true;
var spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
if (spreadNodes.length === 0) {
return;
}
spreadPathIndexByName[fragmentName] = spreadPath.length;
for (var _i2 = 0; _i2 < spreadNodes.length; _i2++) {
var spreadNode = spreadNodes[_i2];
var spreadName = spreadNode.name.value;
var cycleIndex = spreadPathIndexByName[spreadName];
spreadPath.push(spreadNode);
if (cycleIndex === undefined) {
var spreadFragment = context.getFragment(spreadName);
if (spreadFragment) {
detectCycleRecursive(spreadFragment);
}
} else {
var cyclePath = spreadPath.slice(cycleIndex);
var fragmentNames = cyclePath.slice(0, -1).map(function (s) {
return s.name.value;
});
context.reportError(new GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath));
}
spreadPath.pop();
}
spreadPathIndexByName[fragmentName] = undefined;
}
}

View File

@@ -0,0 +1,16 @@
import Maybe from '../../tsutils/Maybe';
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function undefinedVarMessage(
varName: string,
opName: Maybe<string>,
): string;
/**
* No undefined variables
*
* A GraphQL operation is only valid if all variables encountered, both directly
* and via fragment spreads, are defined by that operation.
*/
export function NoUndefinedVariables(context: ValidationContext): ASTVisitor;

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.undefinedVarMessage = undefinedVarMessage;
exports.NoUndefinedVariables = NoUndefinedVariables;
var _GraphQLError = require("../../error/GraphQLError");
function undefinedVarMessage(varName, opName) {
return opName ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is not defined.");
}
/**
* No undefined variables
*
* A GraphQL operation is only valid if all variables encountered, both directly
* and via fragment spreads, are defined by that operation.
*/
function NoUndefinedVariables(context) {
var variableNameDefined = Object.create(null);
return {
OperationDefinition: {
enter: function enter() {
variableNameDefined = Object.create(null);
},
leave: function leave(operation) {
var usages = context.getRecursiveVariableUsages(operation);
for (var _i2 = 0; _i2 < usages.length; _i2++) {
var _ref2 = usages[_i2];
var node = _ref2.node;
var varName = node.name.value;
if (variableNameDefined[varName] !== true) {
context.reportError(new _GraphQLError.GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation]));
}
}
}
},
VariableDefinition: function VariableDefinition(node) {
variableNameDefined[node.variable.name.value] = true;
}
};
}

View File

@@ -0,0 +1,51 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type ValidationContext } from '../ValidationContext';
export function undefinedVarMessage(varName: string, opName: ?string): string {
return opName
? `Variable "$${varName}" is not defined by operation "${opName}".`
: `Variable "$${varName}" is not defined.`;
}
/**
* No undefined variables
*
* A GraphQL operation is only valid if all variables encountered, both directly
* and via fragment spreads, are defined by that operation.
*/
export function NoUndefinedVariables(context: ValidationContext): ASTVisitor {
let variableNameDefined = Object.create(null);
return {
OperationDefinition: {
enter() {
variableNameDefined = Object.create(null);
},
leave(operation) {
const usages = context.getRecursiveVariableUsages(operation);
for (const { node } of usages) {
const varName = node.name.value;
if (variableNameDefined[varName] !== true) {
context.reportError(
new GraphQLError(
undefinedVarMessage(
varName,
operation.name && operation.name.value,
),
[node, operation],
),
);
}
}
},
},
VariableDefinition(node) {
variableNameDefined[node.variable.name.value] = true;
},
};
}

View File

@@ -0,0 +1,37 @@
import { GraphQLError } from '../../error/GraphQLError';
export function undefinedVarMessage(varName, opName) {
return opName ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is not defined.");
}
/**
* No undefined variables
*
* A GraphQL operation is only valid if all variables encountered, both directly
* and via fragment spreads, are defined by that operation.
*/
export function NoUndefinedVariables(context) {
var variableNameDefined = Object.create(null);
return {
OperationDefinition: {
enter: function enter() {
variableNameDefined = Object.create(null);
},
leave: function leave(operation) {
var usages = context.getRecursiveVariableUsages(operation);
for (var _i2 = 0; _i2 < usages.length; _i2++) {
var _ref2 = usages[_i2];
var node = _ref2.node;
var varName = node.name.value;
if (variableNameDefined[varName] !== true) {
context.reportError(new GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation]));
}
}
}
},
VariableDefinition: function VariableDefinition(node) {
variableNameDefined[node.variable.name.value] = true;
}
};
}

View File

@@ -0,0 +1,12 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function unusedFragMessage(fragName: string): string;
/**
* No unused fragments
*
* A GraphQL document is only valid if all fragment definitions are spread
* within operations, or spread within other fragments spread within operations.
*/
export function NoUnusedFragments(context: ValidationContext): ASTVisitor;

View File

@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unusedFragMessage = unusedFragMessage;
exports.NoUnusedFragments = NoUnusedFragments;
var _GraphQLError = require("../../error/GraphQLError");
function unusedFragMessage(fragName) {
return "Fragment \"".concat(fragName, "\" is never used.");
}
/**
* No unused fragments
*
* A GraphQL document is only valid if all fragment definitions are spread
* within operations, or spread within other fragments spread within operations.
*/
function NoUnusedFragments(context) {
var operationDefs = [];
var fragmentDefs = [];
return {
OperationDefinition: function OperationDefinition(node) {
operationDefs.push(node);
return false;
},
FragmentDefinition: function FragmentDefinition(node) {
fragmentDefs.push(node);
return false;
},
Document: {
leave: function leave() {
var fragmentNameUsed = Object.create(null);
for (var _i2 = 0; _i2 < operationDefs.length; _i2++) {
var operation = operationDefs[_i2];
for (var _i4 = 0, _context$getRecursive2 = context.getRecursivelyReferencedFragments(operation); _i4 < _context$getRecursive2.length; _i4++) {
var fragment = _context$getRecursive2[_i4];
fragmentNameUsed[fragment.name.value] = true;
}
}
for (var _i6 = 0; _i6 < fragmentDefs.length; _i6++) {
var fragmentDef = fragmentDefs[_i6];
var fragName = fragmentDef.name.value;
if (fragmentNameUsed[fragName] !== true) {
context.reportError(new _GraphQLError.GraphQLError(unusedFragMessage(fragName), fragmentDef));
}
}
}
}
};
}

View File

@@ -0,0 +1,53 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type ASTValidationContext } from '../ValidationContext';
export function unusedFragMessage(fragName: string): string {
return `Fragment "${fragName}" is never used.`;
}
/**
* No unused fragments
*
* A GraphQL document is only valid if all fragment definitions are spread
* within operations, or spread within other fragments spread within operations.
*/
export function NoUnusedFragments(context: ASTValidationContext): ASTVisitor {
const operationDefs = [];
const fragmentDefs = [];
return {
OperationDefinition(node) {
operationDefs.push(node);
return false;
},
FragmentDefinition(node) {
fragmentDefs.push(node);
return false;
},
Document: {
leave() {
const fragmentNameUsed = Object.create(null);
for (const operation of operationDefs) {
for (const fragment of context.getRecursivelyReferencedFragments(
operation,
)) {
fragmentNameUsed[fragment.name.value] = true;
}
}
for (const fragmentDef of fragmentDefs) {
const fragName = fragmentDef.name.value;
if (fragmentNameUsed[fragName] !== true) {
context.reportError(
new GraphQLError(unusedFragMessage(fragName), fragmentDef),
);
}
}
},
},
};
}

View File

@@ -0,0 +1,48 @@
import { GraphQLError } from '../../error/GraphQLError';
export function unusedFragMessage(fragName) {
return "Fragment \"".concat(fragName, "\" is never used.");
}
/**
* No unused fragments
*
* A GraphQL document is only valid if all fragment definitions are spread
* within operations, or spread within other fragments spread within operations.
*/
export function NoUnusedFragments(context) {
var operationDefs = [];
var fragmentDefs = [];
return {
OperationDefinition: function OperationDefinition(node) {
operationDefs.push(node);
return false;
},
FragmentDefinition: function FragmentDefinition(node) {
fragmentDefs.push(node);
return false;
},
Document: {
leave: function leave() {
var fragmentNameUsed = Object.create(null);
for (var _i2 = 0; _i2 < operationDefs.length; _i2++) {
var operation = operationDefs[_i2];
for (var _i4 = 0, _context$getRecursive2 = context.getRecursivelyReferencedFragments(operation); _i4 < _context$getRecursive2.length; _i4++) {
var fragment = _context$getRecursive2[_i4];
fragmentNameUsed[fragment.name.value] = true;
}
}
for (var _i6 = 0; _i6 < fragmentDefs.length; _i6++) {
var fragmentDef = fragmentDefs[_i6];
var fragName = fragmentDef.name.value;
if (fragmentNameUsed[fragName] !== true) {
context.reportError(new GraphQLError(unusedFragMessage(fragName), fragmentDef));
}
}
}
}
};
}

View File

@@ -0,0 +1,16 @@
import Maybe from '../../tsutils/Maybe';
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function unusedVariableMessage(
varName: string,
opName: Maybe<string>,
): string;
/**
* No unused variables
*
* A GraphQL operation is only valid if all variables defined by an operation
* are used, either directly or within a spread fragment.
*/
export function NoUnusedVariables(context: ValidationContext): ASTVisitor;

View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.unusedVariableMessage = unusedVariableMessage;
exports.NoUnusedVariables = NoUnusedVariables;
var _GraphQLError = require("../../error/GraphQLError");
function unusedVariableMessage(varName, opName) {
return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used.");
}
/**
* No unused variables
*
* A GraphQL operation is only valid if all variables defined by an operation
* are used, either directly or within a spread fragment.
*/
function NoUnusedVariables(context) {
var variableDefs = [];
return {
OperationDefinition: {
enter: function enter() {
variableDefs = [];
},
leave: function leave(operation) {
var variableNameUsed = Object.create(null);
var usages = context.getRecursiveVariableUsages(operation);
var opName = operation.name ? operation.name.value : null;
for (var _i2 = 0; _i2 < usages.length; _i2++) {
var _ref2 = usages[_i2];
var node = _ref2.node;
variableNameUsed[node.name.value] = true;
}
for (var _i4 = 0, _variableDefs2 = variableDefs; _i4 < _variableDefs2.length; _i4++) {
var variableDef = _variableDefs2[_i4];
var variableName = variableDef.variable.name.value;
if (variableNameUsed[variableName] !== true) {
context.reportError(new _GraphQLError.GraphQLError(unusedVariableMessage(variableName, opName), variableDef));
}
}
}
},
VariableDefinition: function VariableDefinition(def) {
variableDefs.push(def);
}
};
}

View File

@@ -0,0 +1,57 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type ValidationContext } from '../ValidationContext';
export function unusedVariableMessage(
varName: string,
opName: ?string,
): string {
return opName
? `Variable "$${varName}" is never used in operation "${opName}".`
: `Variable "$${varName}" is never used.`;
}
/**
* No unused variables
*
* A GraphQL operation is only valid if all variables defined by an operation
* are used, either directly or within a spread fragment.
*/
export function NoUnusedVariables(context: ValidationContext): ASTVisitor {
let variableDefs = [];
return {
OperationDefinition: {
enter() {
variableDefs = [];
},
leave(operation) {
const variableNameUsed = Object.create(null);
const usages = context.getRecursiveVariableUsages(operation);
const opName = operation.name ? operation.name.value : null;
for (const { node } of usages) {
variableNameUsed[node.name.value] = true;
}
for (const variableDef of variableDefs) {
const variableName = variableDef.variable.name.value;
if (variableNameUsed[variableName] !== true) {
context.reportError(
new GraphQLError(
unusedVariableMessage(variableName, opName),
variableDef,
),
);
}
}
},
},
VariableDefinition(def) {
variableDefs.push(def);
},
};
}

View File

@@ -0,0 +1,44 @@
import { GraphQLError } from '../../error/GraphQLError';
export function unusedVariableMessage(varName, opName) {
return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used.");
}
/**
* No unused variables
*
* A GraphQL operation is only valid if all variables defined by an operation
* are used, either directly or within a spread fragment.
*/
export function NoUnusedVariables(context) {
var variableDefs = [];
return {
OperationDefinition: {
enter: function enter() {
variableDefs = [];
},
leave: function leave(operation) {
var variableNameUsed = Object.create(null);
var usages = context.getRecursiveVariableUsages(operation);
var opName = operation.name ? operation.name.value : null;
for (var _i2 = 0; _i2 < usages.length; _i2++) {
var _ref2 = usages[_i2];
var node = _ref2.node;
variableNameUsed[node.name.value] = true;
}
for (var _i4 = 0, _variableDefs2 = variableDefs; _i4 < _variableDefs2.length; _i4++) {
var variableDef = _variableDefs2[_i4];
var variableName = variableDef.variable.name.value;
if (variableNameUsed[variableName] !== true) {
context.reportError(new GraphQLError(unusedVariableMessage(variableName, opName), variableDef));
}
}
}
},
VariableDefinition: function VariableDefinition(def) {
variableDefs.push(def);
}
};
}

View File

@@ -0,0 +1,24 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function fieldsConflictMessage(
responseName: string,
reason: ConflictReasonMessage,
): string;
/**
* Overlapping fields can be merged
*
* A selection set is only valid if all fields (including spreading any
* fragments) either correspond to distinct response names or can be merged
* without ambiguity.
*/
export function OverlappingFieldsCanBeMerged(
context: ValidationContext,
): ASTVisitor;
// Field name and reason.
type ConflictReason = [string, string];
// Reason is a string, or a nested list of conflicts.
type ConflictReasonMessage = string | Array<ConflictReason>;

View File

@@ -0,0 +1,595 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fieldsConflictMessage = fieldsConflictMessage;
exports.OverlappingFieldsCanBeMerged = OverlappingFieldsCanBeMerged;
var _find = _interopRequireDefault(require("../../polyfills/find"));
var _objectEntries3 = _interopRequireDefault(require("../../polyfills/objectEntries"));
var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
var _GraphQLError = require("../../error/GraphQLError");
var _kinds = require("../../language/kinds");
var _printer = require("../../language/printer");
var _definition = require("../../type/definition");
var _typeFromAST = require("../../utilities/typeFromAST");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function fieldsConflictMessage(responseName, reason) {
return "Fields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(reason), ". ") + 'Use different aliases on the fields to fetch both if this was intentional.';
}
function reasonMessage(reason) {
if (Array.isArray(reason)) {
return reason.map(function (_ref) {
var responseName = _ref[0],
subreason = _ref[1];
return "subfields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(subreason));
}).join(' and ');
}
return reason;
}
/**
* Overlapping fields can be merged
*
* A selection set is only valid if all fields (including spreading any
* fragments) either correspond to distinct response names or can be merged
* without ambiguity.
*/
function OverlappingFieldsCanBeMerged(context) {
// A memoization for when two fragments are compared "between" each other for
// conflicts. Two fragments may be compared many times, so memoizing this can
// dramatically improve the performance of this validator.
var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given
// selection set. Selection sets may be asked for this information multiple
// times, so this improves the performance of this validator.
var cachedFieldsAndFragmentNames = new Map();
return {
SelectionSet: function SelectionSet(selectionSet) {
var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet);
for (var _i2 = 0; _i2 < conflicts.length; _i2++) {
var _ref3 = conflicts[_i2];
var _ref2$ = _ref3[0];
var responseName = _ref2$[0];
var reason = _ref2$[1];
var fields1 = _ref3[1];
var fields2 = _ref3[2];
context.reportError(new _GraphQLError.GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2)));
}
}
};
}
/**
* Algorithm:
*
* Conflicts occur when two fields exist in a query which will produce the same
* response name, but represent differing values, thus creating a conflict.
* The algorithm below finds all conflicts via making a series of comparisons
* between fields. In order to compare as few fields as possible, this makes
* a series of comparisons "within" sets of fields and "between" sets of fields.
*
* Given any selection set, a collection produces both a set of fields by
* also including all inline fragments, as well as a list of fragments
* referenced by fragment spreads.
*
* A) Each selection set represented in the document first compares "within" its
* collected set of fields, finding any conflicts between every pair of
* overlapping fields.
* Note: This is the *only time* that a the fields "within" a set are compared
* to each other. After this only fields "between" sets are compared.
*
* B) Also, if any fragment is referenced in a selection set, then a
* comparison is made "between" the original set of fields and the
* referenced fragment.
*
* C) Also, if multiple fragments are referenced, then comparisons
* are made "between" each referenced fragment.
*
* D) When comparing "between" a set of fields and a referenced fragment, first
* a comparison is made between each field in the original set of fields and
* each field in the the referenced set of fields.
*
* E) Also, if any fragment is referenced in the referenced selection set,
* then a comparison is made "between" the original set of fields and the
* referenced fragment (recursively referring to step D).
*
* F) When comparing "between" two fragments, first a comparison is made between
* each field in the first referenced set of fields and each field in the the
* second referenced set of fields.
*
* G) Also, any fragments referenced by the first must be compared to the
* second, and any fragments referenced by the second must be compared to the
* first (recursively referring to step F).
*
* H) When comparing two fields, if both have selection sets, then a comparison
* is made "between" both selection sets, first comparing the set of fields in
* the first selection set with the set of fields in the second.
*
* I) Also, if any fragment is referenced in either selection set, then a
* comparison is made "between" the other set of fields and the
* referenced fragment.
*
* J) Also, if two fragments are referenced in both selection sets, then a
* comparison is made "between" the two fragments.
*
*/
// Find all conflicts found "within" a selection set, including those found
// via spreading in fragments. Called when visiting each SelectionSet in the
// GraphQL Document.
function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) {
var conflicts = [];
var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet),
fieldMap = _getFieldsAndFragment[0],
fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set.
// Note: this is the *only place* `collectConflictsWithin` is called.
collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap);
if (fragmentNames.length !== 0) {
// (B) Then collect conflicts between these fields and those represented by
// each spread fragment name found.
var comparedFragments = Object.create(null);
for (var i = 0; i < fragmentNames.length; i++) {
collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this
// selection set to collect conflicts between fragments spread together.
// This compares each item in the list of fragment names to every other
// item in that same list (except for itself).
for (var j = i + 1; j < fragmentNames.length; j++) {
collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]);
}
}
}
return conflicts;
} // Collect all conflicts found between a set of fields and a fragment reference
// including via spreading in any nested fragments.
function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) {
// Memoize so a fragment is not compared for conflicts more than once.
if (comparedFragments[fragmentName]) {
return;
}
comparedFragments[fragmentName] = true;
var fragment = context.getFragment(fragmentName);
if (!fragment) {
return;
}
var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment),
fieldMap2 = _getReferencedFieldsA[0],
fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself.
if (fieldMap === fieldMap2) {
return;
} // (D) First collect any conflicts between the provided collection of fields
// and the collection of fields represented by the given fragment.
collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields
// and any fragment names found in the given fragment.
for (var i = 0; i < fragmentNames2.length; i++) {
collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]);
}
} // Collect all conflicts found between two fragments, including via spreading in
// any nested fragments.
function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) {
// No need to compare a fragment to itself.
if (fragmentName1 === fragmentName2) {
return;
} // Memoize so two fragments are not compared for conflicts more than once.
if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) {
return;
}
comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);
var fragment1 = context.getFragment(fragmentName1);
var fragment2 = context.getFragment(fragmentName2);
if (!fragment1 || !fragment2) {
return;
}
var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1),
fieldMap1 = _getReferencedFieldsA2[0],
fragmentNames1 = _getReferencedFieldsA2[1];
var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2),
fieldMap2 = _getReferencedFieldsA3[0],
fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields
// (not including any nested fragments).
collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested
// fragments spread in the second fragment.
for (var j = 0; j < fragmentNames2.length; j++) {
collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]);
} // (G) Then collect conflicts between the second fragment and any nested
// fragments spread in the first fragment.
for (var i = 0; i < fragmentNames1.length; i++) {
collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2);
}
} // Find all conflicts found between two selection sets, including those found
// via spreading in fragments. Called when determining if conflicts exist
// between the sub-fields of two overlapping fields.
function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) {
var conflicts = [];
var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1),
fieldMap1 = _getFieldsAndFragment2[0],
fragmentNames1 = _getFieldsAndFragment2[1];
var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2),
fieldMap2 = _getFieldsAndFragment3[0],
fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field.
collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and
// those referenced by each fragment name associated with the second.
if (fragmentNames2.length !== 0) {
var comparedFragments = Object.create(null);
for (var j = 0; j < fragmentNames2.length; j++) {
collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]);
}
} // (I) Then collect conflicts between the second collection of fields and
// those referenced by each fragment name associated with the first.
if (fragmentNames1.length !== 0) {
var _comparedFragments = Object.create(null);
for (var i = 0; i < fragmentNames1.length; i++) {
collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]);
}
} // (J) Also collect conflicts between any fragment names by the first and
// fragment names by the second. This compares each item in the first set of
// names to each item in the second set of names.
for (var _i3 = 0; _i3 < fragmentNames1.length; _i3++) {
for (var _j = 0; _j < fragmentNames2.length; _j++) {
collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i3], fragmentNames2[_j]);
}
}
return conflicts;
} // Collect all Conflicts "within" one collection of fields.
function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) {
// A field map is a keyed collection, where each key represents a response
// name and the value at that key is a list of all fields which provide that
// response name. For every response name, if there are multiple fields, they
// must be compared to find a potential conflict.
for (var _i5 = 0, _objectEntries2 = (0, _objectEntries3.default)(fieldMap); _i5 < _objectEntries2.length; _i5++) {
var _ref5 = _objectEntries2[_i5];
var responseName = _ref5[0];
var fields = _ref5[1];
// This compares every field in the list to every other field in this list
// (except to itself). If the list only has one item, nothing needs to
// be compared.
if (fields.length > 1) {
for (var i = 0; i < fields.length; i++) {
for (var j = i + 1; j < fields.length; j++) {
var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive
responseName, fields[i], fields[j]);
if (conflict) {
conflicts.push(conflict);
}
}
}
}
}
} // Collect all Conflicts between two collections of fields. This is similar to,
// but different from the `collectConflictsWithin` function above. This check
// assumes that `collectConflictsWithin` has already been called on each
// provided collection of fields. This is true because this validator traverses
// each individual selection set.
function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) {
// A field map is a keyed collection, where each key represents a response
// name and the value at that key is a list of all fields which provide that
// response name. For any response name which appears in both provided field
// maps, each field from the first field map must be compared to every field
// in the second field map to find potential conflicts.
for (var _i7 = 0, _Object$keys2 = Object.keys(fieldMap1); _i7 < _Object$keys2.length; _i7++) {
var responseName = _Object$keys2[_i7];
var fields2 = fieldMap2[responseName];
if (fields2) {
var fields1 = fieldMap1[responseName];
for (var i = 0; i < fields1.length; i++) {
for (var j = 0; j < fields2.length; j++) {
var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]);
if (conflict) {
conflicts.push(conflict);
}
}
}
}
}
} // Determines if there is a conflict between two particular fields, including
// comparing their sub-fields.
function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) {
var parentType1 = field1[0],
node1 = field1[1],
def1 = field1[2];
var parentType2 = field2[0],
node2 = field2[1],
def2 = field2[2]; // If it is known that two fields could not possibly apply at the same
// time, due to the parent types, then it is safe to permit them to diverge
// in aliased field or arguments used as they will not present any ambiguity
// by differing.
// It is known that two parent types could never overlap if they are
// different Object types. Interface or Union types might overlap - if not
// in the current state of the schema, then perhaps in some future version,
// thus may not safely diverge.
var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); // The return type for each field.
var type1 = def1 && def1.type;
var type2 = def2 && def2.type;
if (!areMutuallyExclusive) {
// Two aliases must refer to the same field.
var name1 = node1.name.value;
var name2 = node2.name.value;
if (name1 !== name2) {
return [[responseName, "".concat(name1, " and ").concat(name2, " are different fields")], [node1], [node2]];
} // Two field calls must have the same arguments.
if (!sameArguments(node1.arguments || [], node2.arguments || [])) {
return [[responseName, 'they have differing arguments'], [node1], [node2]];
}
}
if (type1 && type2 && doTypesConflict(type1, type2)) {
return [[responseName, "they return conflicting types ".concat((0, _inspect.default)(type1), " and ").concat((0, _inspect.default)(type2))], [node1], [node2]];
} // Collect and compare sub-fields. Use the same "visited fragment names" list
// for both collections so fields in a fragment reference are never
// compared to themselves.
var selectionSet1 = node1.selectionSet;
var selectionSet2 = node2.selectionSet;
if (selectionSet1 && selectionSet2) {
var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2);
return subfieldConflicts(conflicts, responseName, node1, node2);
}
}
function sameArguments(arguments1, arguments2) {
if (arguments1.length !== arguments2.length) {
return false;
}
return arguments1.every(function (argument1) {
var argument2 = (0, _find.default)(arguments2, function (argument) {
return argument.name.value === argument1.name.value;
});
if (!argument2) {
return false;
}
return sameValue(argument1.value, argument2.value);
});
}
function sameValue(value1, value2) {
return !value1 && !value2 || (0, _printer.print)(value1) === (0, _printer.print)(value2);
} // Two types conflict if both types could not apply to a value simultaneously.
// Composite types are ignored as their individual field types will be compared
// later recursively. However List and Non-Null types must match.
function doTypesConflict(type1, type2) {
if ((0, _definition.isListType)(type1)) {
return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
}
if ((0, _definition.isListType)(type2)) {
return true;
}
if ((0, _definition.isNonNullType)(type1)) {
return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
}
if ((0, _definition.isNonNullType)(type2)) {
return true;
}
if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) {
return type1 !== type2;
}
return false;
} // Given a selection set, return the collection of fields (a mapping of response
// name to field nodes and definitions) as well as a list of fragment names
// referenced via fragment spreads.
function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) {
var cached = cachedFieldsAndFragmentNames.get(selectionSet);
if (!cached) {
var nodeAndDefs = Object.create(null);
var fragmentNames = Object.create(null);
_collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames);
cached = [nodeAndDefs, Object.keys(fragmentNames)];
cachedFieldsAndFragmentNames.set(selectionSet, cached);
}
return cached;
} // Given a reference to a fragment, return the represented collection of fields
// as well as a list of nested fragment names referenced via fragment spreads.
function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) {
// Short-circuit building a type from the node if possible.
var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);
if (cached) {
return cached;
}
var fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition);
return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet);
}
function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) {
for (var _i9 = 0, _selectionSet$selecti2 = selectionSet.selections; _i9 < _selectionSet$selecti2.length; _i9++) {
var selection = _selectionSet$selecti2[_i9];
switch (selection.kind) {
case _kinds.Kind.FIELD:
{
var fieldName = selection.name.value;
var fieldDef = void 0;
if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) {
fieldDef = parentType.getFields()[fieldName];
}
var responseName = selection.alias ? selection.alias.value : fieldName;
if (!nodeAndDefs[responseName]) {
nodeAndDefs[responseName] = [];
}
nodeAndDefs[responseName].push([parentType, selection, fieldDef]);
break;
}
case _kinds.Kind.FRAGMENT_SPREAD:
fragmentNames[selection.name.value] = true;
break;
case _kinds.Kind.INLINE_FRAGMENT:
{
var typeCondition = selection.typeCondition;
var inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType;
_collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames);
break;
}
}
}
} // Given a series of Conflicts which occurred between two sub-fields, generate
// a single Conflict.
function subfieldConflicts(conflicts, responseName, node1, node2) {
if (conflicts.length > 0) {
return [[responseName, conflicts.map(function (_ref6) {
var reason = _ref6[0];
return reason;
})], conflicts.reduce(function (allFields, _ref7) {
var fields1 = _ref7[1];
return allFields.concat(fields1);
}, [node1]), conflicts.reduce(function (allFields, _ref8) {
var fields2 = _ref8[2];
return allFields.concat(fields2);
}, [node2])];
}
}
/**
* A way to keep track of pairs of things when the ordering of the pair does
* not matter. We do this by maintaining a sort of double adjacency sets.
*/
var PairSet =
/*#__PURE__*/
function () {
function PairSet() {
this._data = Object.create(null);
}
var _proto = PairSet.prototype;
_proto.has = function has(a, b, areMutuallyExclusive) {
var first = this._data[a];
var result = first && first[b];
if (result === undefined) {
return false;
} // areMutuallyExclusive being false is a superset of being true,
// hence if we want to know if this PairSet "has" these two with no
// exclusivity, we have to ensure it was added as such.
if (areMutuallyExclusive === false) {
return result === false;
}
return true;
};
_proto.add = function add(a, b, areMutuallyExclusive) {
_pairSetAdd(this._data, a, b, areMutuallyExclusive);
_pairSetAdd(this._data, b, a, areMutuallyExclusive);
};
return PairSet;
}();
function _pairSetAdd(data, a, b, areMutuallyExclusive) {
var map = data[a];
if (!map) {
map = Object.create(null);
data[a] = map;
}
map[b] = areMutuallyExclusive;
}

View File

@@ -0,0 +1,849 @@
// @flow strict
import find from '../../polyfills/find';
import objectEntries from '../../polyfills/objectEntries';
import inspect from '../../jsutils/inspect';
import { type ObjMap } from '../../jsutils/ObjMap';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { print } from '../../language/printer';
import { type ASTVisitor } from '../../language/visitor';
import {
type SelectionSetNode,
type FieldNode,
type ArgumentNode,
type FragmentDefinitionNode,
} from '../../language/ast';
import {
type GraphQLNamedType,
type GraphQLOutputType,
type GraphQLCompositeType,
type GraphQLField,
getNamedType,
isNonNullType,
isLeafType,
isObjectType,
isListType,
isInterfaceType,
} from '../../type/definition';
import { typeFromAST } from '../../utilities/typeFromAST';
import { type ValidationContext } from '../ValidationContext';
export function fieldsConflictMessage(
responseName: string,
reason: ConflictReasonMessage,
): string {
return (
`Fields "${responseName}" conflict because ${reasonMessage(reason)}. ` +
'Use different aliases on the fields to fetch both if this was intentional.'
);
}
function reasonMessage(reason: ConflictReasonMessage): string {
if (Array.isArray(reason)) {
return reason
.map(
([responseName, subreason]) =>
`subfields "${responseName}" conflict because ${reasonMessage(
subreason,
)}`,
)
.join(' and ');
}
return reason;
}
/**
* Overlapping fields can be merged
*
* A selection set is only valid if all fields (including spreading any
* fragments) either correspond to distinct response names or can be merged
* without ambiguity.
*/
export function OverlappingFieldsCanBeMerged(
context: ValidationContext,
): ASTVisitor {
// A memoization for when two fragments are compared "between" each other for
// conflicts. Two fragments may be compared many times, so memoizing this can
// dramatically improve the performance of this validator.
const comparedFragmentPairs = new PairSet();
// A cache for the "field map" and list of fragment names found in any given
// selection set. Selection sets may be asked for this information multiple
// times, so this improves the performance of this validator.
const cachedFieldsAndFragmentNames = new Map();
return {
SelectionSet(selectionSet) {
const conflicts = findConflictsWithinSelectionSet(
context,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
context.getParentType(),
selectionSet,
);
for (const [[responseName, reason], fields1, fields2] of conflicts) {
context.reportError(
new GraphQLError(
fieldsConflictMessage(responseName, reason),
fields1.concat(fields2),
),
);
}
},
};
}
type Conflict = [ConflictReason, Array<FieldNode>, Array<FieldNode>];
// Field name and reason.
type ConflictReason = [string, ConflictReasonMessage];
// Reason is a string, or a nested list of conflicts.
type ConflictReasonMessage = string | Array<ConflictReason>;
// Tuple defining a field node in a context.
type NodeAndDef = [
GraphQLCompositeType,
FieldNode,
?GraphQLField<mixed, mixed>,
];
// Map of array of those.
type NodeAndDefCollection = ObjMap<Array<NodeAndDef>>;
/**
* Algorithm:
*
* Conflicts occur when two fields exist in a query which will produce the same
* response name, but represent differing values, thus creating a conflict.
* The algorithm below finds all conflicts via making a series of comparisons
* between fields. In order to compare as few fields as possible, this makes
* a series of comparisons "within" sets of fields and "between" sets of fields.
*
* Given any selection set, a collection produces both a set of fields by
* also including all inline fragments, as well as a list of fragments
* referenced by fragment spreads.
*
* A) Each selection set represented in the document first compares "within" its
* collected set of fields, finding any conflicts between every pair of
* overlapping fields.
* Note: This is the *only time* that a the fields "within" a set are compared
* to each other. After this only fields "between" sets are compared.
*
* B) Also, if any fragment is referenced in a selection set, then a
* comparison is made "between" the original set of fields and the
* referenced fragment.
*
* C) Also, if multiple fragments are referenced, then comparisons
* are made "between" each referenced fragment.
*
* D) When comparing "between" a set of fields and a referenced fragment, first
* a comparison is made between each field in the original set of fields and
* each field in the the referenced set of fields.
*
* E) Also, if any fragment is referenced in the referenced selection set,
* then a comparison is made "between" the original set of fields and the
* referenced fragment (recursively referring to step D).
*
* F) When comparing "between" two fragments, first a comparison is made between
* each field in the first referenced set of fields and each field in the the
* second referenced set of fields.
*
* G) Also, any fragments referenced by the first must be compared to the
* second, and any fragments referenced by the second must be compared to the
* first (recursively referring to step F).
*
* H) When comparing two fields, if both have selection sets, then a comparison
* is made "between" both selection sets, first comparing the set of fields in
* the first selection set with the set of fields in the second.
*
* I) Also, if any fragment is referenced in either selection set, then a
* comparison is made "between" the other set of fields and the
* referenced fragment.
*
* J) Also, if two fragments are referenced in both selection sets, then a
* comparison is made "between" the two fragments.
*
*/
// Find all conflicts found "within" a selection set, including those found
// via spreading in fragments. Called when visiting each SelectionSet in the
// GraphQL Document.
function findConflictsWithinSelectionSet(
context: ValidationContext,
cachedFieldsAndFragmentNames,
comparedFragmentPairs: PairSet,
parentType: ?GraphQLNamedType,
selectionSet: SelectionSetNode,
): Array<Conflict> {
const conflicts = [];
const [fieldMap, fragmentNames] = getFieldsAndFragmentNames(
context,
cachedFieldsAndFragmentNames,
parentType,
selectionSet,
);
// (A) Find find all conflicts "within" the fields of this selection set.
// Note: this is the *only place* `collectConflictsWithin` is called.
collectConflictsWithin(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
fieldMap,
);
if (fragmentNames.length !== 0) {
// (B) Then collect conflicts between these fields and those represented by
// each spread fragment name found.
const comparedFragments = Object.create(null);
for (let i = 0; i < fragmentNames.length; i++) {
collectConflictsBetweenFieldsAndFragment(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragments,
comparedFragmentPairs,
false,
fieldMap,
fragmentNames[i],
);
// (C) Then compare this fragment with all other fragments found in this
// selection set to collect conflicts between fragments spread together.
// This compares each item in the list of fragment names to every other
// item in that same list (except for itself).
for (let j = i + 1; j < fragmentNames.length; j++) {
collectConflictsBetweenFragments(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
false,
fragmentNames[i],
fragmentNames[j],
);
}
}
}
return conflicts;
}
// Collect all conflicts found between a set of fields and a fragment reference
// including via spreading in any nested fragments.
function collectConflictsBetweenFieldsAndFragment(
context: ValidationContext,
conflicts: Array<Conflict>,
cachedFieldsAndFragmentNames,
comparedFragments: ObjMap<boolean>,
comparedFragmentPairs: PairSet,
areMutuallyExclusive: boolean,
fieldMap: NodeAndDefCollection,
fragmentName: string,
): void {
// Memoize so a fragment is not compared for conflicts more than once.
if (comparedFragments[fragmentName]) {
return;
}
comparedFragments[fragmentName] = true;
const fragment = context.getFragment(fragmentName);
if (!fragment) {
return;
}
const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames(
context,
cachedFieldsAndFragmentNames,
fragment,
);
// Do not compare a fragment's fieldMap to itself.
if (fieldMap === fieldMap2) {
return;
}
// (D) First collect any conflicts between the provided collection of fields
// and the collection of fields represented by the given fragment.
collectConflictsBetween(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
areMutuallyExclusive,
fieldMap,
fieldMap2,
);
// (E) Then collect any conflicts between the provided collection of fields
// and any fragment names found in the given fragment.
for (let i = 0; i < fragmentNames2.length; i++) {
collectConflictsBetweenFieldsAndFragment(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragments,
comparedFragmentPairs,
areMutuallyExclusive,
fieldMap,
fragmentNames2[i],
);
}
}
// Collect all conflicts found between two fragments, including via spreading in
// any nested fragments.
function collectConflictsBetweenFragments(
context: ValidationContext,
conflicts: Array<Conflict>,
cachedFieldsAndFragmentNames,
comparedFragmentPairs: PairSet,
areMutuallyExclusive: boolean,
fragmentName1: string,
fragmentName2: string,
): void {
// No need to compare a fragment to itself.
if (fragmentName1 === fragmentName2) {
return;
}
// Memoize so two fragments are not compared for conflicts more than once.
if (
comparedFragmentPairs.has(
fragmentName1,
fragmentName2,
areMutuallyExclusive,
)
) {
return;
}
comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);
const fragment1 = context.getFragment(fragmentName1);
const fragment2 = context.getFragment(fragmentName2);
if (!fragment1 || !fragment2) {
return;
}
const [fieldMap1, fragmentNames1] = getReferencedFieldsAndFragmentNames(
context,
cachedFieldsAndFragmentNames,
fragment1,
);
const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames(
context,
cachedFieldsAndFragmentNames,
fragment2,
);
// (F) First, collect all conflicts between these two collections of fields
// (not including any nested fragments).
collectConflictsBetween(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
areMutuallyExclusive,
fieldMap1,
fieldMap2,
);
// (G) Then collect conflicts between the first fragment and any nested
// fragments spread in the second fragment.
for (let j = 0; j < fragmentNames2.length; j++) {
collectConflictsBetweenFragments(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
areMutuallyExclusive,
fragmentName1,
fragmentNames2[j],
);
}
// (G) Then collect conflicts between the second fragment and any nested
// fragments spread in the first fragment.
for (let i = 0; i < fragmentNames1.length; i++) {
collectConflictsBetweenFragments(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
areMutuallyExclusive,
fragmentNames1[i],
fragmentName2,
);
}
}
// Find all conflicts found between two selection sets, including those found
// via spreading in fragments. Called when determining if conflicts exist
// between the sub-fields of two overlapping fields.
function findConflictsBetweenSubSelectionSets(
context: ValidationContext,
cachedFieldsAndFragmentNames,
comparedFragmentPairs: PairSet,
areMutuallyExclusive: boolean,
parentType1: ?GraphQLNamedType,
selectionSet1: SelectionSetNode,
parentType2: ?GraphQLNamedType,
selectionSet2: SelectionSetNode,
): Array<Conflict> {
const conflicts = [];
const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames(
context,
cachedFieldsAndFragmentNames,
parentType1,
selectionSet1,
);
const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames(
context,
cachedFieldsAndFragmentNames,
parentType2,
selectionSet2,
);
// (H) First, collect all conflicts between these two collections of field.
collectConflictsBetween(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
areMutuallyExclusive,
fieldMap1,
fieldMap2,
);
// (I) Then collect conflicts between the first collection of fields and
// those referenced by each fragment name associated with the second.
if (fragmentNames2.length !== 0) {
const comparedFragments = Object.create(null);
for (let j = 0; j < fragmentNames2.length; j++) {
collectConflictsBetweenFieldsAndFragment(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragments,
comparedFragmentPairs,
areMutuallyExclusive,
fieldMap1,
fragmentNames2[j],
);
}
}
// (I) Then collect conflicts between the second collection of fields and
// those referenced by each fragment name associated with the first.
if (fragmentNames1.length !== 0) {
const comparedFragments = Object.create(null);
for (let i = 0; i < fragmentNames1.length; i++) {
collectConflictsBetweenFieldsAndFragment(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragments,
comparedFragmentPairs,
areMutuallyExclusive,
fieldMap2,
fragmentNames1[i],
);
}
}
// (J) Also collect conflicts between any fragment names by the first and
// fragment names by the second. This compares each item in the first set of
// names to each item in the second set of names.
for (let i = 0; i < fragmentNames1.length; i++) {
for (let j = 0; j < fragmentNames2.length; j++) {
collectConflictsBetweenFragments(
context,
conflicts,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
areMutuallyExclusive,
fragmentNames1[i],
fragmentNames2[j],
);
}
}
return conflicts;
}
// Collect all Conflicts "within" one collection of fields.
function collectConflictsWithin(
context: ValidationContext,
conflicts: Array<Conflict>,
cachedFieldsAndFragmentNames,
comparedFragmentPairs: PairSet,
fieldMap: NodeAndDefCollection,
): void {
// A field map is a keyed collection, where each key represents a response
// name and the value at that key is a list of all fields which provide that
// response name. For every response name, if there are multiple fields, they
// must be compared to find a potential conflict.
for (const [responseName, fields] of objectEntries(fieldMap)) {
// This compares every field in the list to every other field in this list
// (except to itself). If the list only has one item, nothing needs to
// be compared.
if (fields.length > 1) {
for (let i = 0; i < fields.length; i++) {
for (let j = i + 1; j < fields.length; j++) {
const conflict = findConflict(
context,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
false, // within one collection is never mutually exclusive
responseName,
fields[i],
fields[j],
);
if (conflict) {
conflicts.push(conflict);
}
}
}
}
}
}
// Collect all Conflicts between two collections of fields. This is similar to,
// but different from the `collectConflictsWithin` function above. This check
// assumes that `collectConflictsWithin` has already been called on each
// provided collection of fields. This is true because this validator traverses
// each individual selection set.
function collectConflictsBetween(
context: ValidationContext,
conflicts: Array<Conflict>,
cachedFieldsAndFragmentNames,
comparedFragmentPairs: PairSet,
parentFieldsAreMutuallyExclusive: boolean,
fieldMap1: NodeAndDefCollection,
fieldMap2: NodeAndDefCollection,
): void {
// A field map is a keyed collection, where each key represents a response
// name and the value at that key is a list of all fields which provide that
// response name. For any response name which appears in both provided field
// maps, each field from the first field map must be compared to every field
// in the second field map to find potential conflicts.
for (const responseName of Object.keys(fieldMap1)) {
const fields2 = fieldMap2[responseName];
if (fields2) {
const fields1 = fieldMap1[responseName];
for (let i = 0; i < fields1.length; i++) {
for (let j = 0; j < fields2.length; j++) {
const conflict = findConflict(
context,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
parentFieldsAreMutuallyExclusive,
responseName,
fields1[i],
fields2[j],
);
if (conflict) {
conflicts.push(conflict);
}
}
}
}
}
}
// Determines if there is a conflict between two particular fields, including
// comparing their sub-fields.
function findConflict(
context: ValidationContext,
cachedFieldsAndFragmentNames,
comparedFragmentPairs: PairSet,
parentFieldsAreMutuallyExclusive: boolean,
responseName: string,
field1: NodeAndDef,
field2: NodeAndDef,
): ?Conflict {
const [parentType1, node1, def1] = field1;
const [parentType2, node2, def2] = field2;
// If it is known that two fields could not possibly apply at the same
// time, due to the parent types, then it is safe to permit them to diverge
// in aliased field or arguments used as they will not present any ambiguity
// by differing.
// It is known that two parent types could never overlap if they are
// different Object types. Interface or Union types might overlap - if not
// in the current state of the schema, then perhaps in some future version,
// thus may not safely diverge.
const areMutuallyExclusive =
parentFieldsAreMutuallyExclusive ||
(parentType1 !== parentType2 &&
isObjectType(parentType1) &&
isObjectType(parentType2));
// The return type for each field.
const type1 = def1 && def1.type;
const type2 = def2 && def2.type;
if (!areMutuallyExclusive) {
// Two aliases must refer to the same field.
const name1 = node1.name.value;
const name2 = node2.name.value;
if (name1 !== name2) {
return [
[responseName, `${name1} and ${name2} are different fields`],
[node1],
[node2],
];
}
// Two field calls must have the same arguments.
if (!sameArguments(node1.arguments || [], node2.arguments || [])) {
return [
[responseName, 'they have differing arguments'],
[node1],
[node2],
];
}
}
if (type1 && type2 && doTypesConflict(type1, type2)) {
return [
[
responseName,
`they return conflicting types ${inspect(type1)} and ${inspect(type2)}`,
],
[node1],
[node2],
];
}
// Collect and compare sub-fields. Use the same "visited fragment names" list
// for both collections so fields in a fragment reference are never
// compared to themselves.
const selectionSet1 = node1.selectionSet;
const selectionSet2 = node2.selectionSet;
if (selectionSet1 && selectionSet2) {
const conflicts = findConflictsBetweenSubSelectionSets(
context,
cachedFieldsAndFragmentNames,
comparedFragmentPairs,
areMutuallyExclusive,
getNamedType(type1),
selectionSet1,
getNamedType(type2),
selectionSet2,
);
return subfieldConflicts(conflicts, responseName, node1, node2);
}
}
function sameArguments(
arguments1: $ReadOnlyArray<ArgumentNode>,
arguments2: $ReadOnlyArray<ArgumentNode>,
): boolean {
if (arguments1.length !== arguments2.length) {
return false;
}
return arguments1.every(argument1 => {
const argument2 = find(
arguments2,
argument => argument.name.value === argument1.name.value,
);
if (!argument2) {
return false;
}
return sameValue(argument1.value, argument2.value);
});
}
function sameValue(value1, value2) {
return (!value1 && !value2) || print(value1) === print(value2);
}
// Two types conflict if both types could not apply to a value simultaneously.
// Composite types are ignored as their individual field types will be compared
// later recursively. However List and Non-Null types must match.
function doTypesConflict(
type1: GraphQLOutputType,
type2: GraphQLOutputType,
): boolean {
if (isListType(type1)) {
return isListType(type2)
? doTypesConflict(type1.ofType, type2.ofType)
: true;
}
if (isListType(type2)) {
return true;
}
if (isNonNullType(type1)) {
return isNonNullType(type2)
? doTypesConflict(type1.ofType, type2.ofType)
: true;
}
if (isNonNullType(type2)) {
return true;
}
if (isLeafType(type1) || isLeafType(type2)) {
return type1 !== type2;
}
return false;
}
// Given a selection set, return the collection of fields (a mapping of response
// name to field nodes and definitions) as well as a list of fragment names
// referenced via fragment spreads.
function getFieldsAndFragmentNames(
context: ValidationContext,
cachedFieldsAndFragmentNames,
parentType: ?GraphQLNamedType,
selectionSet: SelectionSetNode,
): [NodeAndDefCollection, Array<string>] {
let cached = cachedFieldsAndFragmentNames.get(selectionSet);
if (!cached) {
const nodeAndDefs = Object.create(null);
const fragmentNames = Object.create(null);
_collectFieldsAndFragmentNames(
context,
parentType,
selectionSet,
nodeAndDefs,
fragmentNames,
);
cached = [nodeAndDefs, Object.keys(fragmentNames)];
cachedFieldsAndFragmentNames.set(selectionSet, cached);
}
return cached;
}
// Given a reference to a fragment, return the represented collection of fields
// as well as a list of nested fragment names referenced via fragment spreads.
function getReferencedFieldsAndFragmentNames(
context: ValidationContext,
cachedFieldsAndFragmentNames,
fragment: FragmentDefinitionNode,
) {
// Short-circuit building a type from the node if possible.
const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);
if (cached) {
return cached;
}
const fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition);
return getFieldsAndFragmentNames(
context,
cachedFieldsAndFragmentNames,
fragmentType,
fragment.selectionSet,
);
}
function _collectFieldsAndFragmentNames(
context: ValidationContext,
parentType: ?GraphQLNamedType,
selectionSet: SelectionSetNode,
nodeAndDefs,
fragmentNames,
): void {
for (const selection of selectionSet.selections) {
switch (selection.kind) {
case Kind.FIELD: {
const fieldName = selection.name.value;
let fieldDef;
if (isObjectType(parentType) || isInterfaceType(parentType)) {
fieldDef = parentType.getFields()[fieldName];
}
const responseName = selection.alias
? selection.alias.value
: fieldName;
if (!nodeAndDefs[responseName]) {
nodeAndDefs[responseName] = [];
}
nodeAndDefs[responseName].push([parentType, selection, fieldDef]);
break;
}
case Kind.FRAGMENT_SPREAD:
fragmentNames[selection.name.value] = true;
break;
case Kind.INLINE_FRAGMENT: {
const typeCondition = selection.typeCondition;
const inlineFragmentType = typeCondition
? typeFromAST(context.getSchema(), typeCondition)
: parentType;
_collectFieldsAndFragmentNames(
context,
inlineFragmentType,
selection.selectionSet,
nodeAndDefs,
fragmentNames,
);
break;
}
}
}
}
// Given a series of Conflicts which occurred between two sub-fields, generate
// a single Conflict.
function subfieldConflicts(
conflicts: $ReadOnlyArray<Conflict>,
responseName: string,
node1: FieldNode,
node2: FieldNode,
): ?Conflict {
if (conflicts.length > 0) {
return [
[responseName, conflicts.map(([reason]) => reason)],
conflicts.reduce((allFields, [, fields1]) => allFields.concat(fields1), [
node1,
]),
conflicts.reduce(
(allFields, [, , fields2]) => allFields.concat(fields2),
[node2],
),
];
}
}
/**
* A way to keep track of pairs of things when the ordering of the pair does
* not matter. We do this by maintaining a sort of double adjacency sets.
*/
class PairSet {
_data: ObjMap<ObjMap<boolean>>;
constructor(): void {
this._data = Object.create(null);
}
has(a: string, b: string, areMutuallyExclusive: boolean) {
const first = this._data[a];
const result = first && first[b];
if (result === undefined) {
return false;
}
// areMutuallyExclusive being false is a superset of being true,
// hence if we want to know if this PairSet "has" these two with no
// exclusivity, we have to ensure it was added as such.
if (areMutuallyExclusive === false) {
return result === false;
}
return true;
}
add(a: string, b: string, areMutuallyExclusive: boolean) {
_pairSetAdd(this._data, a, b, areMutuallyExclusive);
_pairSetAdd(this._data, b, a, areMutuallyExclusive);
}
}
function _pairSetAdd(data, a, b, areMutuallyExclusive) {
let map = data[a];
if (!map) {
map = Object.create(null);
data[a] = map;
}
map[b] = areMutuallyExclusive;
}

View File

@@ -0,0 +1,577 @@
import find from '../../polyfills/find';
import objectEntries from '../../polyfills/objectEntries';
import inspect from '../../jsutils/inspect';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { print } from '../../language/printer';
import { getNamedType, isNonNullType, isLeafType, isObjectType, isListType, isInterfaceType } from '../../type/definition';
import { typeFromAST } from '../../utilities/typeFromAST';
export function fieldsConflictMessage(responseName, reason) {
return "Fields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(reason), ". ") + 'Use different aliases on the fields to fetch both if this was intentional.';
}
function reasonMessage(reason) {
if (Array.isArray(reason)) {
return reason.map(function (_ref) {
var responseName = _ref[0],
subreason = _ref[1];
return "subfields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(subreason));
}).join(' and ');
}
return reason;
}
/**
* Overlapping fields can be merged
*
* A selection set is only valid if all fields (including spreading any
* fragments) either correspond to distinct response names or can be merged
* without ambiguity.
*/
export function OverlappingFieldsCanBeMerged(context) {
// A memoization for when two fragments are compared "between" each other for
// conflicts. Two fragments may be compared many times, so memoizing this can
// dramatically improve the performance of this validator.
var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given
// selection set. Selection sets may be asked for this information multiple
// times, so this improves the performance of this validator.
var cachedFieldsAndFragmentNames = new Map();
return {
SelectionSet: function SelectionSet(selectionSet) {
var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet);
for (var _i2 = 0; _i2 < conflicts.length; _i2++) {
var _ref3 = conflicts[_i2];
var _ref2$ = _ref3[0];
var responseName = _ref2$[0];
var reason = _ref2$[1];
var fields1 = _ref3[1];
var fields2 = _ref3[2];
context.reportError(new GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2)));
}
}
};
}
/**
* Algorithm:
*
* Conflicts occur when two fields exist in a query which will produce the same
* response name, but represent differing values, thus creating a conflict.
* The algorithm below finds all conflicts via making a series of comparisons
* between fields. In order to compare as few fields as possible, this makes
* a series of comparisons "within" sets of fields and "between" sets of fields.
*
* Given any selection set, a collection produces both a set of fields by
* also including all inline fragments, as well as a list of fragments
* referenced by fragment spreads.
*
* A) Each selection set represented in the document first compares "within" its
* collected set of fields, finding any conflicts between every pair of
* overlapping fields.
* Note: This is the *only time* that a the fields "within" a set are compared
* to each other. After this only fields "between" sets are compared.
*
* B) Also, if any fragment is referenced in a selection set, then a
* comparison is made "between" the original set of fields and the
* referenced fragment.
*
* C) Also, if multiple fragments are referenced, then comparisons
* are made "between" each referenced fragment.
*
* D) When comparing "between" a set of fields and a referenced fragment, first
* a comparison is made between each field in the original set of fields and
* each field in the the referenced set of fields.
*
* E) Also, if any fragment is referenced in the referenced selection set,
* then a comparison is made "between" the original set of fields and the
* referenced fragment (recursively referring to step D).
*
* F) When comparing "between" two fragments, first a comparison is made between
* each field in the first referenced set of fields and each field in the the
* second referenced set of fields.
*
* G) Also, any fragments referenced by the first must be compared to the
* second, and any fragments referenced by the second must be compared to the
* first (recursively referring to step F).
*
* H) When comparing two fields, if both have selection sets, then a comparison
* is made "between" both selection sets, first comparing the set of fields in
* the first selection set with the set of fields in the second.
*
* I) Also, if any fragment is referenced in either selection set, then a
* comparison is made "between" the other set of fields and the
* referenced fragment.
*
* J) Also, if two fragments are referenced in both selection sets, then a
* comparison is made "between" the two fragments.
*
*/
// Find all conflicts found "within" a selection set, including those found
// via spreading in fragments. Called when visiting each SelectionSet in the
// GraphQL Document.
function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) {
var conflicts = [];
var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet),
fieldMap = _getFieldsAndFragment[0],
fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set.
// Note: this is the *only place* `collectConflictsWithin` is called.
collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap);
if (fragmentNames.length !== 0) {
// (B) Then collect conflicts between these fields and those represented by
// each spread fragment name found.
var comparedFragments = Object.create(null);
for (var i = 0; i < fragmentNames.length; i++) {
collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this
// selection set to collect conflicts between fragments spread together.
// This compares each item in the list of fragment names to every other
// item in that same list (except for itself).
for (var j = i + 1; j < fragmentNames.length; j++) {
collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]);
}
}
}
return conflicts;
} // Collect all conflicts found between a set of fields and a fragment reference
// including via spreading in any nested fragments.
function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) {
// Memoize so a fragment is not compared for conflicts more than once.
if (comparedFragments[fragmentName]) {
return;
}
comparedFragments[fragmentName] = true;
var fragment = context.getFragment(fragmentName);
if (!fragment) {
return;
}
var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment),
fieldMap2 = _getReferencedFieldsA[0],
fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself.
if (fieldMap === fieldMap2) {
return;
} // (D) First collect any conflicts between the provided collection of fields
// and the collection of fields represented by the given fragment.
collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields
// and any fragment names found in the given fragment.
for (var i = 0; i < fragmentNames2.length; i++) {
collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]);
}
} // Collect all conflicts found between two fragments, including via spreading in
// any nested fragments.
function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) {
// No need to compare a fragment to itself.
if (fragmentName1 === fragmentName2) {
return;
} // Memoize so two fragments are not compared for conflicts more than once.
if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) {
return;
}
comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);
var fragment1 = context.getFragment(fragmentName1);
var fragment2 = context.getFragment(fragmentName2);
if (!fragment1 || !fragment2) {
return;
}
var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1),
fieldMap1 = _getReferencedFieldsA2[0],
fragmentNames1 = _getReferencedFieldsA2[1];
var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2),
fieldMap2 = _getReferencedFieldsA3[0],
fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields
// (not including any nested fragments).
collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested
// fragments spread in the second fragment.
for (var j = 0; j < fragmentNames2.length; j++) {
collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]);
} // (G) Then collect conflicts between the second fragment and any nested
// fragments spread in the first fragment.
for (var i = 0; i < fragmentNames1.length; i++) {
collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2);
}
} // Find all conflicts found between two selection sets, including those found
// via spreading in fragments. Called when determining if conflicts exist
// between the sub-fields of two overlapping fields.
function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) {
var conflicts = [];
var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1),
fieldMap1 = _getFieldsAndFragment2[0],
fragmentNames1 = _getFieldsAndFragment2[1];
var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2),
fieldMap2 = _getFieldsAndFragment3[0],
fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field.
collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and
// those referenced by each fragment name associated with the second.
if (fragmentNames2.length !== 0) {
var comparedFragments = Object.create(null);
for (var j = 0; j < fragmentNames2.length; j++) {
collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]);
}
} // (I) Then collect conflicts between the second collection of fields and
// those referenced by each fragment name associated with the first.
if (fragmentNames1.length !== 0) {
var _comparedFragments = Object.create(null);
for (var i = 0; i < fragmentNames1.length; i++) {
collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]);
}
} // (J) Also collect conflicts between any fragment names by the first and
// fragment names by the second. This compares each item in the first set of
// names to each item in the second set of names.
for (var _i3 = 0; _i3 < fragmentNames1.length; _i3++) {
for (var _j = 0; _j < fragmentNames2.length; _j++) {
collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i3], fragmentNames2[_j]);
}
}
return conflicts;
} // Collect all Conflicts "within" one collection of fields.
function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) {
// A field map is a keyed collection, where each key represents a response
// name and the value at that key is a list of all fields which provide that
// response name. For every response name, if there are multiple fields, they
// must be compared to find a potential conflict.
for (var _i5 = 0, _objectEntries2 = objectEntries(fieldMap); _i5 < _objectEntries2.length; _i5++) {
var _ref5 = _objectEntries2[_i5];
var responseName = _ref5[0];
var fields = _ref5[1];
// This compares every field in the list to every other field in this list
// (except to itself). If the list only has one item, nothing needs to
// be compared.
if (fields.length > 1) {
for (var i = 0; i < fields.length; i++) {
for (var j = i + 1; j < fields.length; j++) {
var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive
responseName, fields[i], fields[j]);
if (conflict) {
conflicts.push(conflict);
}
}
}
}
}
} // Collect all Conflicts between two collections of fields. This is similar to,
// but different from the `collectConflictsWithin` function above. This check
// assumes that `collectConflictsWithin` has already been called on each
// provided collection of fields. This is true because this validator traverses
// each individual selection set.
function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) {
// A field map is a keyed collection, where each key represents a response
// name and the value at that key is a list of all fields which provide that
// response name. For any response name which appears in both provided field
// maps, each field from the first field map must be compared to every field
// in the second field map to find potential conflicts.
for (var _i7 = 0, _Object$keys2 = Object.keys(fieldMap1); _i7 < _Object$keys2.length; _i7++) {
var responseName = _Object$keys2[_i7];
var fields2 = fieldMap2[responseName];
if (fields2) {
var fields1 = fieldMap1[responseName];
for (var i = 0; i < fields1.length; i++) {
for (var j = 0; j < fields2.length; j++) {
var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]);
if (conflict) {
conflicts.push(conflict);
}
}
}
}
}
} // Determines if there is a conflict between two particular fields, including
// comparing their sub-fields.
function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) {
var parentType1 = field1[0],
node1 = field1[1],
def1 = field1[2];
var parentType2 = field2[0],
node2 = field2[1],
def2 = field2[2]; // If it is known that two fields could not possibly apply at the same
// time, due to the parent types, then it is safe to permit them to diverge
// in aliased field or arguments used as they will not present any ambiguity
// by differing.
// It is known that two parent types could never overlap if they are
// different Object types. Interface or Union types might overlap - if not
// in the current state of the schema, then perhaps in some future version,
// thus may not safely diverge.
var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && isObjectType(parentType1) && isObjectType(parentType2); // The return type for each field.
var type1 = def1 && def1.type;
var type2 = def2 && def2.type;
if (!areMutuallyExclusive) {
// Two aliases must refer to the same field.
var name1 = node1.name.value;
var name2 = node2.name.value;
if (name1 !== name2) {
return [[responseName, "".concat(name1, " and ").concat(name2, " are different fields")], [node1], [node2]];
} // Two field calls must have the same arguments.
if (!sameArguments(node1.arguments || [], node2.arguments || [])) {
return [[responseName, 'they have differing arguments'], [node1], [node2]];
}
}
if (type1 && type2 && doTypesConflict(type1, type2)) {
return [[responseName, "they return conflicting types ".concat(inspect(type1), " and ").concat(inspect(type2))], [node1], [node2]];
} // Collect and compare sub-fields. Use the same "visited fragment names" list
// for both collections so fields in a fragment reference are never
// compared to themselves.
var selectionSet1 = node1.selectionSet;
var selectionSet2 = node2.selectionSet;
if (selectionSet1 && selectionSet2) {
var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, getNamedType(type1), selectionSet1, getNamedType(type2), selectionSet2);
return subfieldConflicts(conflicts, responseName, node1, node2);
}
}
function sameArguments(arguments1, arguments2) {
if (arguments1.length !== arguments2.length) {
return false;
}
return arguments1.every(function (argument1) {
var argument2 = find(arguments2, function (argument) {
return argument.name.value === argument1.name.value;
});
if (!argument2) {
return false;
}
return sameValue(argument1.value, argument2.value);
});
}
function sameValue(value1, value2) {
return !value1 && !value2 || print(value1) === print(value2);
} // Two types conflict if both types could not apply to a value simultaneously.
// Composite types are ignored as their individual field types will be compared
// later recursively. However List and Non-Null types must match.
function doTypesConflict(type1, type2) {
if (isListType(type1)) {
return isListType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
}
if (isListType(type2)) {
return true;
}
if (isNonNullType(type1)) {
return isNonNullType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
}
if (isNonNullType(type2)) {
return true;
}
if (isLeafType(type1) || isLeafType(type2)) {
return type1 !== type2;
}
return false;
} // Given a selection set, return the collection of fields (a mapping of response
// name to field nodes and definitions) as well as a list of fragment names
// referenced via fragment spreads.
function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) {
var cached = cachedFieldsAndFragmentNames.get(selectionSet);
if (!cached) {
var nodeAndDefs = Object.create(null);
var fragmentNames = Object.create(null);
_collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames);
cached = [nodeAndDefs, Object.keys(fragmentNames)];
cachedFieldsAndFragmentNames.set(selectionSet, cached);
}
return cached;
} // Given a reference to a fragment, return the represented collection of fields
// as well as a list of nested fragment names referenced via fragment spreads.
function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) {
// Short-circuit building a type from the node if possible.
var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);
if (cached) {
return cached;
}
var fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition);
return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet);
}
function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) {
for (var _i9 = 0, _selectionSet$selecti2 = selectionSet.selections; _i9 < _selectionSet$selecti2.length; _i9++) {
var selection = _selectionSet$selecti2[_i9];
switch (selection.kind) {
case Kind.FIELD:
{
var fieldName = selection.name.value;
var fieldDef = void 0;
if (isObjectType(parentType) || isInterfaceType(parentType)) {
fieldDef = parentType.getFields()[fieldName];
}
var responseName = selection.alias ? selection.alias.value : fieldName;
if (!nodeAndDefs[responseName]) {
nodeAndDefs[responseName] = [];
}
nodeAndDefs[responseName].push([parentType, selection, fieldDef]);
break;
}
case Kind.FRAGMENT_SPREAD:
fragmentNames[selection.name.value] = true;
break;
case Kind.INLINE_FRAGMENT:
{
var typeCondition = selection.typeCondition;
var inlineFragmentType = typeCondition ? typeFromAST(context.getSchema(), typeCondition) : parentType;
_collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames);
break;
}
}
}
} // Given a series of Conflicts which occurred between two sub-fields, generate
// a single Conflict.
function subfieldConflicts(conflicts, responseName, node1, node2) {
if (conflicts.length > 0) {
return [[responseName, conflicts.map(function (_ref6) {
var reason = _ref6[0];
return reason;
})], conflicts.reduce(function (allFields, _ref7) {
var fields1 = _ref7[1];
return allFields.concat(fields1);
}, [node1]), conflicts.reduce(function (allFields, _ref8) {
var fields2 = _ref8[2];
return allFields.concat(fields2);
}, [node2])];
}
}
/**
* A way to keep track of pairs of things when the ordering of the pair does
* not matter. We do this by maintaining a sort of double adjacency sets.
*/
var PairSet =
/*#__PURE__*/
function () {
function PairSet() {
this._data = Object.create(null);
}
var _proto = PairSet.prototype;
_proto.has = function has(a, b, areMutuallyExclusive) {
var first = this._data[a];
var result = first && first[b];
if (result === undefined) {
return false;
} // areMutuallyExclusive being false is a superset of being true,
// hence if we want to know if this PairSet "has" these two with no
// exclusivity, we have to ensure it was added as such.
if (areMutuallyExclusive === false) {
return result === false;
}
return true;
};
_proto.add = function add(a, b, areMutuallyExclusive) {
_pairSetAdd(this._data, a, b, areMutuallyExclusive);
_pairSetAdd(this._data, b, a, areMutuallyExclusive);
};
return PairSet;
}();
function _pairSetAdd(data, a, b, areMutuallyExclusive) {
var map = data[a];
if (!map) {
map = Object.create(null);
data[a] = map;
}
map[b] = areMutuallyExclusive;
}

View File

@@ -0,0 +1,22 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function typeIncompatibleSpreadMessage(
fragName: string,
parentType: string,
fragType: string,
): string;
export function typeIncompatibleAnonSpreadMessage(
parentType: string,
fragType: string,
): string;
/**
* Possible fragment spread
*
* A fragment spread is only valid if the type condition could ever possibly
* be true: if there is a non-empty intersection of the possible parent types,
* and possible types which pass the type condition.
*/
export function PossibleFragmentSpreads(context: ValidationContext): ASTVisitor;

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.typeIncompatibleSpreadMessage = typeIncompatibleSpreadMessage;
exports.typeIncompatibleAnonSpreadMessage = typeIncompatibleAnonSpreadMessage;
exports.PossibleFragmentSpreads = PossibleFragmentSpreads;
var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
var _GraphQLError = require("../../error/GraphQLError");
var _definition = require("../../type/definition");
var _typeFromAST = require("../../utilities/typeFromAST");
var _typeComparators = require("../../utilities/typeComparators");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function typeIncompatibleSpreadMessage(fragName, parentType, fragType) {
return "Fragment \"".concat(fragName, "\" cannot be spread here as objects of type \"").concat(parentType, "\" can never be of type \"").concat(fragType, "\".");
}
function typeIncompatibleAnonSpreadMessage(parentType, fragType) {
return "Fragment cannot be spread here as objects of type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\".");
}
/**
* Possible fragment spread
*
* A fragment spread is only valid if the type condition could ever possibly
* be true: if there is a non-empty intersection of the possible parent types,
* and possible types which pass the type condition.
*/
function PossibleFragmentSpreads(context) {
return {
InlineFragment: function InlineFragment(node) {
var fragType = context.getType();
var parentType = context.getParentType();
if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) {
context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleAnonSpreadMessage((0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), node));
}
},
FragmentSpread: function FragmentSpread(node) {
var fragName = node.name.value;
var fragType = getFragmentType(context, fragName);
var parentType = context.getParentType();
if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) {
context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleSpreadMessage(fragName, (0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), node));
}
}
};
}
function getFragmentType(context, name) {
var frag = context.getFragment(name);
if (frag) {
var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition);
if ((0, _definition.isCompositeType)(type)) {
return type;
}
}
}

View File

@@ -0,0 +1,93 @@
// @flow strict
import inspect from '../../jsutils/inspect';
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { isCompositeType } from '../../type/definition';
import { typeFromAST } from '../../utilities/typeFromAST';
import { doTypesOverlap } from '../../utilities/typeComparators';
import { type ValidationContext } from '../ValidationContext';
export function typeIncompatibleSpreadMessage(
fragName: string,
parentType: string,
fragType: string,
): string {
return `Fragment "${fragName}" cannot be spread here as objects of type "${parentType}" can never be of type "${fragType}".`;
}
export function typeIncompatibleAnonSpreadMessage(
parentType: string,
fragType: string,
): string {
return `Fragment cannot be spread here as objects of type "${parentType}" can never be of type "${fragType}".`;
}
/**
* Possible fragment spread
*
* A fragment spread is only valid if the type condition could ever possibly
* be true: if there is a non-empty intersection of the possible parent types,
* and possible types which pass the type condition.
*/
export function PossibleFragmentSpreads(
context: ValidationContext,
): ASTVisitor {
return {
InlineFragment(node) {
const fragType = context.getType();
const parentType = context.getParentType();
if (
isCompositeType(fragType) &&
isCompositeType(parentType) &&
!doTypesOverlap(context.getSchema(), fragType, parentType)
) {
context.reportError(
new GraphQLError(
typeIncompatibleAnonSpreadMessage(
inspect(parentType),
inspect(fragType),
),
node,
),
);
}
},
FragmentSpread(node) {
const fragName = node.name.value;
const fragType = getFragmentType(context, fragName);
const parentType = context.getParentType();
if (
fragType &&
parentType &&
!doTypesOverlap(context.getSchema(), fragType, parentType)
) {
context.reportError(
new GraphQLError(
typeIncompatibleSpreadMessage(
fragName,
inspect(parentType),
inspect(fragType),
),
node,
),
);
}
},
};
}
function getFragmentType(context, name) {
const frag = context.getFragment(name);
if (frag) {
const type = typeFromAST(context.getSchema(), frag.typeCondition);
if (isCompositeType(type)) {
return type;
}
}
}

View File

@@ -0,0 +1,52 @@
import inspect from '../../jsutils/inspect';
import { GraphQLError } from '../../error/GraphQLError';
import { isCompositeType } from '../../type/definition';
import { typeFromAST } from '../../utilities/typeFromAST';
import { doTypesOverlap } from '../../utilities/typeComparators';
export function typeIncompatibleSpreadMessage(fragName, parentType, fragType) {
return "Fragment \"".concat(fragName, "\" cannot be spread here as objects of type \"").concat(parentType, "\" can never be of type \"").concat(fragType, "\".");
}
export function typeIncompatibleAnonSpreadMessage(parentType, fragType) {
return "Fragment cannot be spread here as objects of type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\".");
}
/**
* Possible fragment spread
*
* A fragment spread is only valid if the type condition could ever possibly
* be true: if there is a non-empty intersection of the possible parent types,
* and possible types which pass the type condition.
*/
export function PossibleFragmentSpreads(context) {
return {
InlineFragment: function InlineFragment(node) {
var fragType = context.getType();
var parentType = context.getParentType();
if (isCompositeType(fragType) && isCompositeType(parentType) && !doTypesOverlap(context.getSchema(), fragType, parentType)) {
context.reportError(new GraphQLError(typeIncompatibleAnonSpreadMessage(inspect(parentType), inspect(fragType)), node));
}
},
FragmentSpread: function FragmentSpread(node) {
var fragName = node.name.value;
var fragType = getFragmentType(context, fragName);
var parentType = context.getParentType();
if (fragType && parentType && !doTypesOverlap(context.getSchema(), fragType, parentType)) {
context.reportError(new GraphQLError(typeIncompatibleSpreadMessage(fragName, inspect(parentType), inspect(fragType)), node));
}
}
};
}
function getFragmentType(context, name) {
var frag = context.getFragment(name);
if (frag) {
var type = typeFromAST(context.getSchema(), frag.typeCondition);
if (isCompositeType(type)) {
return type;
}
}
}

View File

@@ -0,0 +1,21 @@
import { ASTVisitor } from '../../language/visitor';
import { SDLValidationContext } from '../ValidationContext';
export function extendingUnknownTypeMessage(
typeName: string,
suggestedTypes: ReadonlyArray<string>,
): string;
export function extendingDifferentTypeKindMessage(
typeName: string,
kind: string,
): string;
/**
* Possible type extension
*
* A type extension is only valid if the type is defined and has the same kind.
*/
export function PossibleTypeExtensions(
context: SDLValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,136 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.extendingUnknownTypeMessage = extendingUnknownTypeMessage;
exports.extendingDifferentTypeKindMessage = extendingDifferentTypeKindMessage;
exports.PossibleTypeExtensions = PossibleTypeExtensions;
var _didYouMean = _interopRequireDefault(require("../../jsutils/didYouMean"));
var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList"));
var _GraphQLError = require("../../error/GraphQLError");
var _kinds = require("../../language/kinds");
var _predicates = require("../../language/predicates");
var _definition = require("../../type/definition");
var _defKindToExtKind;
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; }
function extendingUnknownTypeMessage(typeName, suggestedTypes) {
return "Cannot extend type \"".concat(typeName, "\" because it is not defined.") + (0, _didYouMean.default)(suggestedTypes.map(function (x) {
return "\"".concat(x, "\"");
}));
}
function extendingDifferentTypeKindMessage(typeName, kind) {
return "Cannot extend non-".concat(kind, " type \"").concat(typeName, "\".");
}
/**
* Possible type extension
*
* A type extension is only valid if the type is defined and has the same kind.
*/
function PossibleTypeExtensions(context) {
var schema = context.getSchema();
var definedTypes = Object.create(null);
for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {
var def = _context$getDocument$2[_i2];
if ((0, _predicates.isTypeDefinitionNode)(def)) {
definedTypes[def.name.value] = def;
}
}
return {
ScalarTypeExtension: checkExtension,
ObjectTypeExtension: checkExtension,
InterfaceTypeExtension: checkExtension,
UnionTypeExtension: checkExtension,
EnumTypeExtension: checkExtension,
InputObjectTypeExtension: checkExtension
};
function checkExtension(node) {
var typeName = node.name.value;
var defNode = definedTypes[typeName];
var existingType = schema && schema.getType(typeName);
if (defNode) {
var expectedKind = defKindToExtKind[defNode.kind];
if (expectedKind !== node.kind) {
context.reportError(new _GraphQLError.GraphQLError(extendingDifferentTypeKindMessage(typeName, extensionKindToTypeName(expectedKind)), [defNode, node]));
}
} else if (existingType) {
var _expectedKind = typeToExtKind(existingType);
if (_expectedKind !== node.kind) {
context.reportError(new _GraphQLError.GraphQLError(extendingDifferentTypeKindMessage(typeName, extensionKindToTypeName(_expectedKind)), node));
}
} else {
var allTypeNames = Object.keys(definedTypes);
if (schema) {
allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap()));
}
var suggestedTypes = (0, _suggestionList.default)(typeName, allTypeNames);
context.reportError(new _GraphQLError.GraphQLError(extendingUnknownTypeMessage(typeName, suggestedTypes), node.name));
}
}
}
var defKindToExtKind = (_defKindToExtKind = {}, _defineProperty(_defKindToExtKind, _kinds.Kind.SCALAR_TYPE_DEFINITION, _kinds.Kind.SCALAR_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.OBJECT_TYPE_DEFINITION, _kinds.Kind.OBJECT_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.INTERFACE_TYPE_DEFINITION, _kinds.Kind.INTERFACE_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.UNION_TYPE_DEFINITION, _kinds.Kind.UNION_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.ENUM_TYPE_DEFINITION, _kinds.Kind.ENUM_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION), _defKindToExtKind);
function typeToExtKind(type) {
if ((0, _definition.isScalarType)(type)) {
return _kinds.Kind.SCALAR_TYPE_EXTENSION;
} else if ((0, _definition.isObjectType)(type)) {
return _kinds.Kind.OBJECT_TYPE_EXTENSION;
} else if ((0, _definition.isInterfaceType)(type)) {
return _kinds.Kind.INTERFACE_TYPE_EXTENSION;
} else if ((0, _definition.isUnionType)(type)) {
return _kinds.Kind.UNION_TYPE_EXTENSION;
} else if ((0, _definition.isEnumType)(type)) {
return _kinds.Kind.ENUM_TYPE_EXTENSION;
} else if ((0, _definition.isInputObjectType)(type)) {
return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION;
}
}
function extensionKindToTypeName(kind) {
switch (kind) {
case _kinds.Kind.SCALAR_TYPE_EXTENSION:
return 'scalar';
case _kinds.Kind.OBJECT_TYPE_EXTENSION:
return 'object';
case _kinds.Kind.INTERFACE_TYPE_EXTENSION:
return 'interface';
case _kinds.Kind.UNION_TYPE_EXTENSION:
return 'union';
case _kinds.Kind.ENUM_TYPE_EXTENSION:
return 'enum';
case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION:
return 'input object';
default:
return 'unknown type';
}
}

View File

@@ -0,0 +1,156 @@
// @flow strict
import didYouMean from '../../jsutils/didYouMean';
import suggestionList from '../../jsutils/suggestionList';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { type ASTVisitor } from '../../language/visitor';
import { isTypeDefinitionNode } from '../../language/predicates';
import {
isScalarType,
isObjectType,
isInterfaceType,
isUnionType,
isEnumType,
isInputObjectType,
} from '../../type/definition';
import { type SDLValidationContext } from '../ValidationContext';
export function extendingUnknownTypeMessage(
typeName: string,
suggestedTypes: $ReadOnlyArray<string>,
): string {
return (
`Cannot extend type "${typeName}" because it is not defined.` +
didYouMean(suggestedTypes.map(x => `"${x}"`))
);
}
export function extendingDifferentTypeKindMessage(
typeName: string,
kind: string,
): string {
return `Cannot extend non-${kind} type "${typeName}".`;
}
/**
* Possible type extension
*
* A type extension is only valid if the type is defined and has the same kind.
*/
export function PossibleTypeExtensions(
context: SDLValidationContext,
): ASTVisitor {
const schema = context.getSchema();
const definedTypes = Object.create(null);
for (const def of context.getDocument().definitions) {
if (isTypeDefinitionNode(def)) {
definedTypes[def.name.value] = def;
}
}
return {
ScalarTypeExtension: checkExtension,
ObjectTypeExtension: checkExtension,
InterfaceTypeExtension: checkExtension,
UnionTypeExtension: checkExtension,
EnumTypeExtension: checkExtension,
InputObjectTypeExtension: checkExtension,
};
function checkExtension(node) {
const typeName = node.name.value;
const defNode = definedTypes[typeName];
const existingType = schema && schema.getType(typeName);
if (defNode) {
const expectedKind = defKindToExtKind[defNode.kind];
if (expectedKind !== node.kind) {
context.reportError(
new GraphQLError(
extendingDifferentTypeKindMessage(
typeName,
extensionKindToTypeName(expectedKind),
),
[defNode, node],
),
);
}
} else if (existingType) {
const expectedKind = typeToExtKind(existingType);
if (expectedKind !== node.kind) {
context.reportError(
new GraphQLError(
extendingDifferentTypeKindMessage(
typeName,
extensionKindToTypeName(expectedKind),
),
node,
),
);
}
} else {
let allTypeNames = Object.keys(definedTypes);
if (schema) {
allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap()));
}
const suggestedTypes = suggestionList(typeName, allTypeNames);
context.reportError(
new GraphQLError(
extendingUnknownTypeMessage(typeName, suggestedTypes),
node.name,
),
);
}
}
}
const defKindToExtKind = {
[Kind.SCALAR_TYPE_DEFINITION]: Kind.SCALAR_TYPE_EXTENSION,
[Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION,
[Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION,
[Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION,
[Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION,
[Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION,
};
function typeToExtKind(type) {
if (isScalarType(type)) {
return Kind.SCALAR_TYPE_EXTENSION;
} else if (isObjectType(type)) {
return Kind.OBJECT_TYPE_EXTENSION;
} else if (isInterfaceType(type)) {
return Kind.INTERFACE_TYPE_EXTENSION;
} else if (isUnionType(type)) {
return Kind.UNION_TYPE_EXTENSION;
} else if (isEnumType(type)) {
return Kind.ENUM_TYPE_EXTENSION;
} else if (isInputObjectType(type)) {
return Kind.INPUT_OBJECT_TYPE_EXTENSION;
}
}
function extensionKindToTypeName(kind) {
switch (kind) {
case Kind.SCALAR_TYPE_EXTENSION:
return 'scalar';
case Kind.OBJECT_TYPE_EXTENSION:
return 'object';
case Kind.INTERFACE_TYPE_EXTENSION:
return 'interface';
case Kind.UNION_TYPE_EXTENSION:
return 'union';
case Kind.ENUM_TYPE_EXTENSION:
return 'enum';
case Kind.INPUT_OBJECT_TYPE_EXTENSION:
return 'input object';
default:
return 'unknown type';
}
}

View File

@@ -0,0 +1,116 @@
var _defKindToExtKind;
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; }
import didYouMean from '../../jsutils/didYouMean';
import suggestionList from '../../jsutils/suggestionList';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { isTypeDefinitionNode } from '../../language/predicates';
import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from '../../type/definition';
export function extendingUnknownTypeMessage(typeName, suggestedTypes) {
return "Cannot extend type \"".concat(typeName, "\" because it is not defined.") + didYouMean(suggestedTypes.map(function (x) {
return "\"".concat(x, "\"");
}));
}
export function extendingDifferentTypeKindMessage(typeName, kind) {
return "Cannot extend non-".concat(kind, " type \"").concat(typeName, "\".");
}
/**
* Possible type extension
*
* A type extension is only valid if the type is defined and has the same kind.
*/
export function PossibleTypeExtensions(context) {
var schema = context.getSchema();
var definedTypes = Object.create(null);
for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {
var def = _context$getDocument$2[_i2];
if (isTypeDefinitionNode(def)) {
definedTypes[def.name.value] = def;
}
}
return {
ScalarTypeExtension: checkExtension,
ObjectTypeExtension: checkExtension,
InterfaceTypeExtension: checkExtension,
UnionTypeExtension: checkExtension,
EnumTypeExtension: checkExtension,
InputObjectTypeExtension: checkExtension
};
function checkExtension(node) {
var typeName = node.name.value;
var defNode = definedTypes[typeName];
var existingType = schema && schema.getType(typeName);
if (defNode) {
var expectedKind = defKindToExtKind[defNode.kind];
if (expectedKind !== node.kind) {
context.reportError(new GraphQLError(extendingDifferentTypeKindMessage(typeName, extensionKindToTypeName(expectedKind)), [defNode, node]));
}
} else if (existingType) {
var _expectedKind = typeToExtKind(existingType);
if (_expectedKind !== node.kind) {
context.reportError(new GraphQLError(extendingDifferentTypeKindMessage(typeName, extensionKindToTypeName(_expectedKind)), node));
}
} else {
var allTypeNames = Object.keys(definedTypes);
if (schema) {
allTypeNames = allTypeNames.concat(Object.keys(schema.getTypeMap()));
}
var suggestedTypes = suggestionList(typeName, allTypeNames);
context.reportError(new GraphQLError(extendingUnknownTypeMessage(typeName, suggestedTypes), node.name));
}
}
}
var defKindToExtKind = (_defKindToExtKind = {}, _defineProperty(_defKindToExtKind, Kind.SCALAR_TYPE_DEFINITION, Kind.SCALAR_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.OBJECT_TYPE_DEFINITION, Kind.OBJECT_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.INTERFACE_TYPE_DEFINITION, Kind.INTERFACE_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.UNION_TYPE_DEFINITION, Kind.UNION_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.ENUM_TYPE_DEFINITION, Kind.ENUM_TYPE_EXTENSION), _defineProperty(_defKindToExtKind, Kind.INPUT_OBJECT_TYPE_DEFINITION, Kind.INPUT_OBJECT_TYPE_EXTENSION), _defKindToExtKind);
function typeToExtKind(type) {
if (isScalarType(type)) {
return Kind.SCALAR_TYPE_EXTENSION;
} else if (isObjectType(type)) {
return Kind.OBJECT_TYPE_EXTENSION;
} else if (isInterfaceType(type)) {
return Kind.INTERFACE_TYPE_EXTENSION;
} else if (isUnionType(type)) {
return Kind.UNION_TYPE_EXTENSION;
} else if (isEnumType(type)) {
return Kind.ENUM_TYPE_EXTENSION;
} else if (isInputObjectType(type)) {
return Kind.INPUT_OBJECT_TYPE_EXTENSION;
}
}
function extensionKindToTypeName(kind) {
switch (kind) {
case Kind.SCALAR_TYPE_EXTENSION:
return 'scalar';
case Kind.OBJECT_TYPE_EXTENSION:
return 'object';
case Kind.INTERFACE_TYPE_EXTENSION:
return 'interface';
case Kind.UNION_TYPE_EXTENSION:
return 'union';
case Kind.ENUM_TYPE_EXTENSION:
return 'enum';
case Kind.INPUT_OBJECT_TYPE_EXTENSION:
return 'input object';
default:
return 'unknown type';
}
}

View File

@@ -0,0 +1,29 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext, SDLValidationContext } from '../ValidationContext';
export function missingFieldArgMessage(
fieldName: string,
argName: string,
type: string,
): string;
export function missingDirectiveArgMessage(
directiveName: string,
argName: string,
type: string,
): string;
/**
* Provided required arguments
*
* A field or directive is only valid if all required (non-null without a
* default value) field arguments have been provided.
*/
export function ProvidedRequiredArguments(
context: ValidationContext,
): ASTVisitor;
// @internal
export function ProvidedRequiredArgumentsOnDirectives(
context: ValidationContext | SDLValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,131 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.missingFieldArgMessage = missingFieldArgMessage;
exports.missingDirectiveArgMessage = missingDirectiveArgMessage;
exports.ProvidedRequiredArguments = ProvidedRequiredArguments;
exports.ProvidedRequiredArgumentsOnDirectives = ProvidedRequiredArgumentsOnDirectives;
var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap"));
var _GraphQLError = require("../../error/GraphQLError");
var _kinds = require("../../language/kinds");
var _printer = require("../../language/printer");
var _directives = require("../../type/directives");
var _definition = require("../../type/definition");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function missingFieldArgMessage(fieldName, argName, type) {
return "Field \"".concat(fieldName, "\" argument \"").concat(argName, "\" of type \"").concat(type, "\" is required, but it was not provided.");
}
function missingDirectiveArgMessage(directiveName, argName, type) {
return "Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type \"").concat(type, "\" is required, but it was not provided.");
}
/**
* Provided required arguments
*
* A field or directive is only valid if all required (non-null without a
* default value) field arguments have been provided.
*/
function ProvidedRequiredArguments(context) {
return _objectSpread({}, ProvidedRequiredArgumentsOnDirectives(context), {
Field: {
// Validate on leave to allow for deeper errors to appear first.
leave: function leave(fieldNode) {
var fieldDef = context.getFieldDef();
if (!fieldDef) {
return false;
}
var argNodes = fieldNode.arguments || [];
var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
return arg.name.value;
});
for (var _i2 = 0, _fieldDef$args2 = fieldDef.args; _i2 < _fieldDef$args2.length; _i2++) {
var argDef = _fieldDef$args2[_i2];
var argNode = argNodeMap[argDef.name];
if (!argNode && (0, _definition.isRequiredArgument)(argDef)) {
context.reportError(new _GraphQLError.GraphQLError(missingFieldArgMessage(fieldDef.name, argDef.name, (0, _inspect.default)(argDef.type)), fieldNode));
}
}
}
}
});
} // @internal
function ProvidedRequiredArgumentsOnDirectives(context) {
var requiredArgsMap = Object.create(null);
var schema = context.getSchema();
var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
for (var _i4 = 0; _i4 < definedDirectives.length; _i4++) {
var directive = definedDirectives[_i4];
requiredArgsMap[directive.name] = (0, _keyMap.default)(directive.args.filter(_definition.isRequiredArgument), function (arg) {
return arg.name;
});
}
var astDefinitions = context.getDocument().definitions;
for (var _i6 = 0; _i6 < astDefinitions.length; _i6++) {
var def = astDefinitions[_i6];
if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
requiredArgsMap[def.name.value] = (0, _keyMap.default)(def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], function (arg) {
return arg.name.value;
});
}
}
return {
Directive: {
// Validate on leave to allow for deeper errors to appear first.
leave: function leave(directiveNode) {
var directiveName = directiveNode.name.value;
var requiredArgs = requiredArgsMap[directiveName];
if (requiredArgs) {
var argNodes = directiveNode.arguments || [];
var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) {
return arg.name.value;
});
for (var _i8 = 0, _Object$keys2 = Object.keys(requiredArgs); _i8 < _Object$keys2.length; _i8++) {
var argName = _Object$keys2[_i8];
if (!argNodeMap[argName]) {
var argType = requiredArgs[argName].type;
context.reportError(new _GraphQLError.GraphQLError(missingDirectiveArgMessage(directiveName, argName, (0, _definition.isType)(argType) ? (0, _inspect.default)(argType) : (0, _printer.print)(argType)), directiveNode));
}
}
}
}
}
};
}
function isRequiredArgumentNode(arg) {
return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null;
}

View File

@@ -0,0 +1,136 @@
// @flow strict
import inspect from '../../jsutils/inspect';
import keyMap from '../../jsutils/keyMap';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { print } from '../../language/printer';
import { type ASTVisitor } from '../../language/visitor';
import { specifiedDirectives } from '../../type/directives';
import { isType, isRequiredArgument } from '../../type/definition';
import {
type ValidationContext,
type SDLValidationContext,
} from '../ValidationContext';
export function missingFieldArgMessage(
fieldName: string,
argName: string,
type: string,
): string {
return `Field "${fieldName}" argument "${argName}" of type "${type}" is required, but it was not provided.`;
}
export function missingDirectiveArgMessage(
directiveName: string,
argName: string,
type: string,
): string {
return `Directive "@${directiveName}" argument "${argName}" of type "${type}" is required, but it was not provided.`;
}
/**
* Provided required arguments
*
* A field or directive is only valid if all required (non-null without a
* default value) field arguments have been provided.
*/
export function ProvidedRequiredArguments(
context: ValidationContext,
): ASTVisitor {
return {
...ProvidedRequiredArgumentsOnDirectives(context),
Field: {
// Validate on leave to allow for deeper errors to appear first.
leave(fieldNode) {
const fieldDef = context.getFieldDef();
if (!fieldDef) {
return false;
}
const argNodes = fieldNode.arguments || [];
const argNodeMap = keyMap(argNodes, arg => arg.name.value);
for (const argDef of fieldDef.args) {
const argNode = argNodeMap[argDef.name];
if (!argNode && isRequiredArgument(argDef)) {
context.reportError(
new GraphQLError(
missingFieldArgMessage(
fieldDef.name,
argDef.name,
inspect(argDef.type),
),
fieldNode,
),
);
}
}
},
},
};
}
// @internal
export function ProvidedRequiredArgumentsOnDirectives(
context: ValidationContext | SDLValidationContext,
): ASTVisitor {
const requiredArgsMap = Object.create(null);
const schema = context.getSchema();
const definedDirectives = schema
? schema.getDirectives()
: specifiedDirectives;
for (const directive of definedDirectives) {
requiredArgsMap[directive.name] = keyMap(
directive.args.filter(isRequiredArgument),
arg => arg.name,
);
}
const astDefinitions = context.getDocument().definitions;
for (const def of astDefinitions) {
if (def.kind === Kind.DIRECTIVE_DEFINITION) {
requiredArgsMap[def.name.value] = keyMap(
def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [],
arg => arg.name.value,
);
}
}
return {
Directive: {
// Validate on leave to allow for deeper errors to appear first.
leave(directiveNode) {
const directiveName = directiveNode.name.value;
const requiredArgs = requiredArgsMap[directiveName];
if (requiredArgs) {
const argNodes = directiveNode.arguments || [];
const argNodeMap = keyMap(argNodes, arg => arg.name.value);
for (const argName of Object.keys(requiredArgs)) {
if (!argNodeMap[argName]) {
const argType = requiredArgs[argName].type;
context.reportError(
new GraphQLError(
missingDirectiveArgMessage(
directiveName,
argName,
isType(argType) ? inspect(argType) : print(argType),
),
directiveNode,
),
);
}
}
}
},
},
};
}
function isRequiredArgumentNode(arg) {
return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null;
}

View File

@@ -0,0 +1,109 @@
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import inspect from '../../jsutils/inspect';
import keyMap from '../../jsutils/keyMap';
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { print } from '../../language/printer';
import { specifiedDirectives } from '../../type/directives';
import { isType, isRequiredArgument } from '../../type/definition';
export function missingFieldArgMessage(fieldName, argName, type) {
return "Field \"".concat(fieldName, "\" argument \"").concat(argName, "\" of type \"").concat(type, "\" is required, but it was not provided.");
}
export function missingDirectiveArgMessage(directiveName, argName, type) {
return "Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type \"").concat(type, "\" is required, but it was not provided.");
}
/**
* Provided required arguments
*
* A field or directive is only valid if all required (non-null without a
* default value) field arguments have been provided.
*/
export function ProvidedRequiredArguments(context) {
return _objectSpread({}, ProvidedRequiredArgumentsOnDirectives(context), {
Field: {
// Validate on leave to allow for deeper errors to appear first.
leave: function leave(fieldNode) {
var fieldDef = context.getFieldDef();
if (!fieldDef) {
return false;
}
var argNodes = fieldNode.arguments || [];
var argNodeMap = keyMap(argNodes, function (arg) {
return arg.name.value;
});
for (var _i2 = 0, _fieldDef$args2 = fieldDef.args; _i2 < _fieldDef$args2.length; _i2++) {
var argDef = _fieldDef$args2[_i2];
var argNode = argNodeMap[argDef.name];
if (!argNode && isRequiredArgument(argDef)) {
context.reportError(new GraphQLError(missingFieldArgMessage(fieldDef.name, argDef.name, inspect(argDef.type)), fieldNode));
}
}
}
}
});
} // @internal
export function ProvidedRequiredArgumentsOnDirectives(context) {
var requiredArgsMap = Object.create(null);
var schema = context.getSchema();
var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;
for (var _i4 = 0; _i4 < definedDirectives.length; _i4++) {
var directive = definedDirectives[_i4];
requiredArgsMap[directive.name] = keyMap(directive.args.filter(isRequiredArgument), function (arg) {
return arg.name;
});
}
var astDefinitions = context.getDocument().definitions;
for (var _i6 = 0; _i6 < astDefinitions.length; _i6++) {
var def = astDefinitions[_i6];
if (def.kind === Kind.DIRECTIVE_DEFINITION) {
requiredArgsMap[def.name.value] = keyMap(def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], function (arg) {
return arg.name.value;
});
}
}
return {
Directive: {
// Validate on leave to allow for deeper errors to appear first.
leave: function leave(directiveNode) {
var directiveName = directiveNode.name.value;
var requiredArgs = requiredArgsMap[directiveName];
if (requiredArgs) {
var argNodes = directiveNode.arguments || [];
var argNodeMap = keyMap(argNodes, function (arg) {
return arg.name.value;
});
for (var _i8 = 0, _Object$keys2 = Object.keys(requiredArgs); _i8 < _Object$keys2.length; _i8++) {
var argName = _Object$keys2[_i8];
if (!argNodeMap[argName]) {
var argType = requiredArgs[argName].type;
context.reportError(new GraphQLError(missingDirectiveArgMessage(directiveName, argName, isType(argType) ? inspect(argType) : print(argType)), directiveNode));
}
}
}
}
}
};
}
function isRequiredArgumentNode(arg) {
return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null;
}

20
node_modules/graphql/validation/rules/ScalarLeafs.d.ts generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import { ASTVisitor } from '../../language/visitor';
import { ValidationContext } from '../ValidationContext';
export function noSubselectionAllowedMessage(
fieldName: string,
type: string,
): string;
export function requiredSubselectionMessage(
fieldName: string,
type: string,
): string;
/**
* Scalar leafs
*
* A GraphQL document is valid only if all leaf fields (fields without
* sub selections) are of scalar or enum types.
*/
export function ScalarLeafs(context: ValidationContext): ASTVisitor;

50
node_modules/graphql/validation/rules/ScalarLeafs.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.noSubselectionAllowedMessage = noSubselectionAllowedMessage;
exports.requiredSubselectionMessage = requiredSubselectionMessage;
exports.ScalarLeafs = ScalarLeafs;
var _inspect = _interopRequireDefault(require("../../jsutils/inspect"));
var _GraphQLError = require("../../error/GraphQLError");
var _definition = require("../../type/definition");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function noSubselectionAllowedMessage(fieldName, type) {
return "Field \"".concat(fieldName, "\" must not have a selection since type \"").concat(type, "\" has no subfields.");
}
function requiredSubselectionMessage(fieldName, type) {
return "Field \"".concat(fieldName, "\" of type \"").concat(type, "\" must have a selection of subfields. Did you mean \"").concat(fieldName, " { ... }\"?");
}
/**
* Scalar leafs
*
* A GraphQL document is valid only if all leaf fields (fields without
* sub selections) are of scalar or enum types.
*/
function ScalarLeafs(context) {
return {
Field: function Field(node) {
var type = context.getType();
var selectionSet = node.selectionSet;
if (type) {
if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) {
if (selectionSet) {
context.reportError(new _GraphQLError.GraphQLError(noSubselectionAllowedMessage(node.name.value, (0, _inspect.default)(type)), selectionSet));
}
} else if (!selectionSet) {
context.reportError(new _GraphQLError.GraphQLError(requiredSubselectionMessage(node.name.value, (0, _inspect.default)(type)), node));
}
}
}
};
}

View File

@@ -0,0 +1,60 @@
// @flow strict
import inspect from '../../jsutils/inspect';
import { GraphQLError } from '../../error/GraphQLError';
import { type FieldNode } from '../../language/ast';
import { type ASTVisitor } from '../../language/visitor';
import { getNamedType, isLeafType } from '../../type/definition';
import { type ValidationContext } from '../ValidationContext';
export function noSubselectionAllowedMessage(
fieldName: string,
type: string,
): string {
return `Field "${fieldName}" must not have a selection since type "${type}" has no subfields.`;
}
export function requiredSubselectionMessage(
fieldName: string,
type: string,
): string {
return `Field "${fieldName}" of type "${type}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`;
}
/**
* Scalar leafs
*
* A GraphQL document is valid only if all leaf fields (fields without
* sub selections) are of scalar or enum types.
*/
export function ScalarLeafs(context: ValidationContext): ASTVisitor {
return {
Field(node: FieldNode) {
const type = context.getType();
const selectionSet = node.selectionSet;
if (type) {
if (isLeafType(getNamedType(type))) {
if (selectionSet) {
context.reportError(
new GraphQLError(
noSubselectionAllowedMessage(node.name.value, inspect(type)),
selectionSet,
),
);
}
} else if (!selectionSet) {
context.reportError(
new GraphQLError(
requiredSubselectionMessage(node.name.value, inspect(type)),
node,
),
);
}
}
},
};
}

34
node_modules/graphql/validation/rules/ScalarLeafs.mjs generated vendored Normal file
View File

@@ -0,0 +1,34 @@
import inspect from '../../jsutils/inspect';
import { GraphQLError } from '../../error/GraphQLError';
import { getNamedType, isLeafType } from '../../type/definition';
export function noSubselectionAllowedMessage(fieldName, type) {
return "Field \"".concat(fieldName, "\" must not have a selection since type \"").concat(type, "\" has no subfields.");
}
export function requiredSubselectionMessage(fieldName, type) {
return "Field \"".concat(fieldName, "\" of type \"").concat(type, "\" must have a selection of subfields. Did you mean \"").concat(fieldName, " { ... }\"?");
}
/**
* Scalar leafs
*
* A GraphQL document is valid only if all leaf fields (fields without
* sub selections) are of scalar or enum types.
*/
export function ScalarLeafs(context) {
return {
Field: function Field(node) {
var type = context.getType();
var selectionSet = node.selectionSet;
if (type) {
if (isLeafType(getNamedType(type))) {
if (selectionSet) {
context.reportError(new GraphQLError(noSubselectionAllowedMessage(node.name.value, inspect(type)), selectionSet));
}
} else if (!selectionSet) {
context.reportError(new GraphQLError(requiredSubselectionMessage(node.name.value, inspect(type)), node));
}
}
}
};
}

View File

@@ -0,0 +1,14 @@
import Maybe from '../../tsutils/Maybe';
import { ASTVisitor } from '../../language/visitor';
import { ASTValidationContext } from '../ValidationContext';
export function singleFieldOnlyMessage(name: Maybe<string>): string;
/**
* Subscriptions must only include one field.
*
* A GraphQL subscription is valid only if it contains a single root field.
*/
export function SingleFieldSubscriptions(
context: ASTValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.singleFieldOnlyMessage = singleFieldOnlyMessage;
exports.SingleFieldSubscriptions = SingleFieldSubscriptions;
var _GraphQLError = require("../../error/GraphQLError");
function singleFieldOnlyMessage(name) {
return name ? "Subscription \"".concat(name, "\" must select only one top level field.") : 'Anonymous Subscription must select only one top level field.';
}
/**
* Subscriptions must only include one field.
*
* A GraphQL subscription is valid only if it contains a single root field.
*/
function SingleFieldSubscriptions(context) {
return {
OperationDefinition: function OperationDefinition(node) {
if (node.operation === 'subscription') {
if (node.selectionSet.selections.length !== 1) {
context.reportError(new _GraphQLError.GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1)));
}
}
}
};
}

View File

@@ -0,0 +1,38 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type OperationDefinitionNode } from '../../language/ast';
import { type ASTValidationContext } from '../ValidationContext';
export function singleFieldOnlyMessage(name: ?string): string {
return name
? `Subscription "${name}" must select only one top level field.`
: 'Anonymous Subscription must select only one top level field.';
}
/**
* Subscriptions must only include one field.
*
* A GraphQL subscription is valid only if it contains a single root field.
*/
export function SingleFieldSubscriptions(
context: ASTValidationContext,
): ASTVisitor {
return {
OperationDefinition(node: OperationDefinitionNode) {
if (node.operation === 'subscription') {
if (node.selectionSet.selections.length !== 1) {
context.reportError(
new GraphQLError(
singleFieldOnlyMessage(node.name && node.name.value),
node.selectionSet.selections.slice(1),
),
);
}
}
},
};
}

View File

@@ -0,0 +1,21 @@
import { GraphQLError } from '../../error/GraphQLError';
export function singleFieldOnlyMessage(name) {
return name ? "Subscription \"".concat(name, "\" must select only one top level field.") : 'Anonymous Subscription must select only one top level field.';
}
/**
* Subscriptions must only include one field.
*
* A GraphQL subscription is valid only if it contains a single root field.
*/
export function SingleFieldSubscriptions(context) {
return {
OperationDefinition: function OperationDefinition(node) {
if (node.operation === 'subscription') {
if (node.selectionSet.selections.length !== 1) {
context.reportError(new GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1)));
}
}
}
};
}

View File

@@ -0,0 +1,12 @@
import { ASTVisitor } from '../../language/visitor';
import { ASTValidationContext } from '../ValidationContext';
export function duplicateArgMessage(argName: string): string;
/**
* Unique argument names
*
* A GraphQL field or directive is only valid if all supplied arguments are
* uniquely named.
*/
export function UniqueArgumentNames(context: ASTValidationContext): ASTVisitor;

View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.duplicateArgMessage = duplicateArgMessage;
exports.UniqueArgumentNames = UniqueArgumentNames;
var _GraphQLError = require("../../error/GraphQLError");
function duplicateArgMessage(argName) {
return "There can be only one argument named \"".concat(argName, "\".");
}
/**
* Unique argument names
*
* A GraphQL field or directive is only valid if all supplied arguments are
* uniquely named.
*/
function UniqueArgumentNames(context) {
var knownArgNames = Object.create(null);
return {
Field: function Field() {
knownArgNames = Object.create(null);
},
Directive: function Directive() {
knownArgNames = Object.create(null);
},
Argument: function Argument(node) {
var argName = node.name.value;
if (knownArgNames[argName]) {
context.reportError(new _GraphQLError.GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name]));
} else {
knownArgNames[argName] = node.name;
}
return false;
}
};
}

View File

@@ -0,0 +1,42 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type ASTValidationContext } from '../ValidationContext';
export function duplicateArgMessage(argName: string): string {
return `There can be only one argument named "${argName}".`;
}
/**
* Unique argument names
*
* A GraphQL field or directive is only valid if all supplied arguments are
* uniquely named.
*/
export function UniqueArgumentNames(context: ASTValidationContext): ASTVisitor {
let knownArgNames = Object.create(null);
return {
Field() {
knownArgNames = Object.create(null);
},
Directive() {
knownArgNames = Object.create(null);
},
Argument(node) {
const argName = node.name.value;
if (knownArgNames[argName]) {
context.reportError(
new GraphQLError(duplicateArgMessage(argName), [
knownArgNames[argName],
node.name,
]),
);
} else {
knownArgNames[argName] = node.name;
}
return false;
},
};
}

View File

@@ -0,0 +1,33 @@
import { GraphQLError } from '../../error/GraphQLError';
export function duplicateArgMessage(argName) {
return "There can be only one argument named \"".concat(argName, "\".");
}
/**
* Unique argument names
*
* A GraphQL field or directive is only valid if all supplied arguments are
* uniquely named.
*/
export function UniqueArgumentNames(context) {
var knownArgNames = Object.create(null);
return {
Field: function Field() {
knownArgNames = Object.create(null);
},
Directive: function Directive() {
knownArgNames = Object.create(null);
},
Argument: function Argument(node) {
var argName = node.name.value;
if (knownArgNames[argName]) {
context.reportError(new GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name]));
} else {
knownArgNames[argName] = node.name;
}
return false;
}
};
}

View File

@@ -0,0 +1,13 @@
import { ASTVisitor } from '../../language/visitor';
import { SDLValidationContext } from '../ValidationContext';
export function duplicateDirectiveNameMessage(directiveName: string): string;
export function existedDirectiveNameMessage(directiveName: string): string;
/**
* Unique directive names
*
* A GraphQL document is only valid if all defined directives have unique names.
*/
export function UniqueDirectiveNames(context: SDLValidationContext): ASTVisitor;

View File

@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.duplicateDirectiveNameMessage = duplicateDirectiveNameMessage;
exports.existedDirectiveNameMessage = existedDirectiveNameMessage;
exports.UniqueDirectiveNames = UniqueDirectiveNames;
var _GraphQLError = require("../../error/GraphQLError");
function duplicateDirectiveNameMessage(directiveName) {
return "There can be only one directive named \"".concat(directiveName, "\".");
}
function existedDirectiveNameMessage(directiveName) {
return "Directive \"".concat(directiveName, "\" already exists in the schema. It cannot be redefined.");
}
/**
* Unique directive names
*
* A GraphQL document is only valid if all defined directives have unique names.
*/
function UniqueDirectiveNames(context) {
var knownDirectiveNames = Object.create(null);
var schema = context.getSchema();
return {
DirectiveDefinition: function DirectiveDefinition(node) {
var directiveName = node.name.value;
if (schema && schema.getDirective(directiveName)) {
context.reportError(new _GraphQLError.GraphQLError(existedDirectiveNameMessage(directiveName), node.name));
return;
}
if (knownDirectiveNames[directiveName]) {
context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveNameMessage(directiveName), [knownDirectiveNames[directiveName], node.name]));
} else {
knownDirectiveNames[directiveName] = node.name;
}
return false;
}
};
}

View File

@@ -0,0 +1,55 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type SDLValidationContext } from '../ValidationContext';
export function duplicateDirectiveNameMessage(directiveName: string): string {
return `There can be only one directive named "${directiveName}".`;
}
export function existedDirectiveNameMessage(directiveName: string): string {
return `Directive "${directiveName}" already exists in the schema. It cannot be redefined.`;
}
/**
* Unique directive names
*
* A GraphQL document is only valid if all defined directives have unique names.
*/
export function UniqueDirectiveNames(
context: SDLValidationContext,
): ASTVisitor {
const knownDirectiveNames = Object.create(null);
const schema = context.getSchema();
return {
DirectiveDefinition(node) {
const directiveName = node.name.value;
if (schema && schema.getDirective(directiveName)) {
context.reportError(
new GraphQLError(
existedDirectiveNameMessage(directiveName),
node.name,
),
);
return;
}
if (knownDirectiveNames[directiveName]) {
context.reportError(
new GraphQLError(duplicateDirectiveNameMessage(directiveName), [
knownDirectiveNames[directiveName],
node.name,
]),
);
} else {
knownDirectiveNames[directiveName] = node.name;
}
return false;
},
};
}

View File

@@ -0,0 +1,35 @@
import { GraphQLError } from '../../error/GraphQLError';
export function duplicateDirectiveNameMessage(directiveName) {
return "There can be only one directive named \"".concat(directiveName, "\".");
}
export function existedDirectiveNameMessage(directiveName) {
return "Directive \"".concat(directiveName, "\" already exists in the schema. It cannot be redefined.");
}
/**
* Unique directive names
*
* A GraphQL document is only valid if all defined directives have unique names.
*/
export function UniqueDirectiveNames(context) {
var knownDirectiveNames = Object.create(null);
var schema = context.getSchema();
return {
DirectiveDefinition: function DirectiveDefinition(node) {
var directiveName = node.name.value;
if (schema && schema.getDirective(directiveName)) {
context.reportError(new GraphQLError(existedDirectiveNameMessage(directiveName), node.name));
return;
}
if (knownDirectiveNames[directiveName]) {
context.reportError(new GraphQLError(duplicateDirectiveNameMessage(directiveName), [knownDirectiveNames[directiveName], node.name]));
} else {
knownDirectiveNames[directiveName] = node.name;
}
return false;
}
};
}

View File

@@ -0,0 +1,14 @@
import { ASTVisitor } from '../../language/visitor';
import { ASTValidationContext } from '../ValidationContext';
export function duplicateDirectiveMessage(directiveName: string): string;
/**
* Unique directive names per location
*
* A GraphQL document is only valid if all directives at a given location
* are uniquely named.
*/
export function UniqueDirectivesPerLocation(
context: ASTValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.duplicateDirectiveMessage = duplicateDirectiveMessage;
exports.UniqueDirectivesPerLocation = UniqueDirectivesPerLocation;
var _GraphQLError = require("../../error/GraphQLError");
var _kinds = require("../../language/kinds");
var _directives = require("../../type/directives");
function duplicateDirectiveMessage(directiveName) {
return "The directive \"".concat(directiveName, "\" can only be used once at this location.");
}
/**
* Unique directive names per location
*
* A GraphQL document is only valid if all non-repeatable directives at
* a given location are uniquely named.
*/
function UniqueDirectivesPerLocation(context) {
var uniqueDirectiveMap = Object.create(null);
var schema = context.getSchema();
var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives;
for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {
var directive = definedDirectives[_i2];
uniqueDirectiveMap[directive.name] = !directive.isRepeatable;
}
var astDefinitions = context.getDocument().definitions;
for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {
var def = astDefinitions[_i4];
if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) {
uniqueDirectiveMap[def.name.value] = !def.repeatable;
}
}
return {
// Many different AST nodes may contain directives. Rather than listing
// them all, just listen for entering any node, and check to see if it
// defines any directives.
enter: function enter(node) {
// Flow can't refine that node.directives will only contain directives,
// so we cast so the rest of the code is well typed.
var directives = node.directives;
if (directives) {
var knownDirectives = Object.create(null);
for (var _i6 = 0; _i6 < directives.length; _i6++) {
var _directive = directives[_i6];
var directiveName = _directive.name.value;
if (uniqueDirectiveMap[directiveName]) {
if (knownDirectives[directiveName]) {
context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], _directive]));
} else {
knownDirectives[directiveName] = _directive;
}
}
}
}
}
};
}

View File

@@ -0,0 +1,75 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { type DirectiveNode } from '../../language/ast';
import { type ASTVisitor } from '../../language/visitor';
import { specifiedDirectives } from '../../type/directives';
import {
type SDLValidationContext,
type ValidationContext,
} from '../ValidationContext';
export function duplicateDirectiveMessage(directiveName: string): string {
return `The directive "${directiveName}" can only be used once at this location.`;
}
/**
* Unique directive names per location
*
* A GraphQL document is only valid if all non-repeatable directives at
* a given location are uniquely named.
*/
export function UniqueDirectivesPerLocation(
context: ValidationContext | SDLValidationContext,
): ASTVisitor {
const uniqueDirectiveMap = Object.create(null);
const schema = context.getSchema();
const definedDirectives = schema
? schema.getDirectives()
: specifiedDirectives;
for (const directive of definedDirectives) {
uniqueDirectiveMap[directive.name] = !directive.isRepeatable;
}
const astDefinitions = context.getDocument().definitions;
for (const def of astDefinitions) {
if (def.kind === Kind.DIRECTIVE_DEFINITION) {
uniqueDirectiveMap[def.name.value] = !def.repeatable;
}
}
return {
// Many different AST nodes may contain directives. Rather than listing
// them all, just listen for entering any node, and check to see if it
// defines any directives.
enter(node) {
// Flow can't refine that node.directives will only contain directives,
// so we cast so the rest of the code is well typed.
const directives: ?$ReadOnlyArray<DirectiveNode> = (node: any).directives;
if (directives) {
const knownDirectives = Object.create(null);
for (const directive of directives) {
const directiveName = directive.name.value;
if (uniqueDirectiveMap[directiveName]) {
if (knownDirectives[directiveName]) {
context.reportError(
new GraphQLError(duplicateDirectiveMessage(directiveName), [
knownDirectives[directiveName],
directive,
]),
);
} else {
knownDirectives[directiveName] = directive;
}
}
}
}
},
};
}

View File

@@ -0,0 +1,61 @@
import { GraphQLError } from '../../error/GraphQLError';
import { Kind } from '../../language/kinds';
import { specifiedDirectives } from '../../type/directives';
export function duplicateDirectiveMessage(directiveName) {
return "The directive \"".concat(directiveName, "\" can only be used once at this location.");
}
/**
* Unique directive names per location
*
* A GraphQL document is only valid if all non-repeatable directives at
* a given location are uniquely named.
*/
export function UniqueDirectivesPerLocation(context) {
var uniqueDirectiveMap = Object.create(null);
var schema = context.getSchema();
var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;
for (var _i2 = 0; _i2 < definedDirectives.length; _i2++) {
var directive = definedDirectives[_i2];
uniqueDirectiveMap[directive.name] = !directive.isRepeatable;
}
var astDefinitions = context.getDocument().definitions;
for (var _i4 = 0; _i4 < astDefinitions.length; _i4++) {
var def = astDefinitions[_i4];
if (def.kind === Kind.DIRECTIVE_DEFINITION) {
uniqueDirectiveMap[def.name.value] = !def.repeatable;
}
}
return {
// Many different AST nodes may contain directives. Rather than listing
// them all, just listen for entering any node, and check to see if it
// defines any directives.
enter: function enter(node) {
// Flow can't refine that node.directives will only contain directives,
// so we cast so the rest of the code is well typed.
var directives = node.directives;
if (directives) {
var knownDirectives = Object.create(null);
for (var _i6 = 0; _i6 < directives.length; _i6++) {
var _directive = directives[_i6];
var directiveName = _directive.name.value;
if (uniqueDirectiveMap[directiveName]) {
if (knownDirectives[directiveName]) {
context.reportError(new GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], _directive]));
} else {
knownDirectives[directiveName] = _directive;
}
}
}
}
}
};
}

View File

@@ -0,0 +1,19 @@
import { ASTVisitor } from '../../language/visitor';
import { SDLValidationContext } from '../ValidationContext';
export function duplicateEnumValueNameMessage(
typeName: string,
valueName: string,
): string;
export function existedEnumValueNameMessage(
typeName: string,
valueName: string,
): string;
/**
* Unique enum value names
*
* A GraphQL enum type is only valid if all its values are uniquely named.
*/
export function UniqueEnumValueNames(context: SDLValidationContext): ASTVisitor;

View File

@@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.duplicateEnumValueNameMessage = duplicateEnumValueNameMessage;
exports.existedEnumValueNameMessage = existedEnumValueNameMessage;
exports.UniqueEnumValueNames = UniqueEnumValueNames;
var _GraphQLError = require("../../error/GraphQLError");
var _definition = require("../../type/definition");
function duplicateEnumValueNameMessage(typeName, valueName) {
return "Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once.");
}
function existedEnumValueNameMessage(typeName, valueName) {
return "Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. It cannot also be defined in this type extension.");
}
/**
* Unique enum value names
*
* A GraphQL enum type is only valid if all its values are uniquely named.
*/
function UniqueEnumValueNames(context) {
var schema = context.getSchema();
var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
var knownValueNames = Object.create(null);
return {
EnumTypeDefinition: checkValueUniqueness,
EnumTypeExtension: checkValueUniqueness
};
function checkValueUniqueness(node) {
var typeName = node.name.value;
if (!knownValueNames[typeName]) {
knownValueNames[typeName] = Object.create(null);
}
if (node.values) {
var valueNames = knownValueNames[typeName];
for (var _i2 = 0, _node$values2 = node.values; _i2 < _node$values2.length; _i2++) {
var valueDef = _node$values2[_i2];
var valueName = valueDef.name.value;
var existingType = existingTypeMap[typeName];
if ((0, _definition.isEnumType)(existingType) && existingType.getValue(valueName)) {
context.reportError(new _GraphQLError.GraphQLError(existedEnumValueNameMessage(typeName, valueName), valueDef.name));
} else if (valueNames[valueName]) {
context.reportError(new _GraphQLError.GraphQLError(duplicateEnumValueNameMessage(typeName, valueName), [valueNames[valueName], valueDef.name]));
} else {
valueNames[valueName] = valueDef.name;
}
}
}
return false;
}
}

View File

@@ -0,0 +1,76 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { isEnumType } from '../../type/definition';
import { type SDLValidationContext } from '../ValidationContext';
export function duplicateEnumValueNameMessage(
typeName: string,
valueName: string,
): string {
return `Enum value "${typeName}.${valueName}" can only be defined once.`;
}
export function existedEnumValueNameMessage(
typeName: string,
valueName: string,
): string {
return `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`;
}
/**
* Unique enum value names
*
* A GraphQL enum type is only valid if all its values are uniquely named.
*/
export function UniqueEnumValueNames(
context: SDLValidationContext,
): ASTVisitor {
const schema = context.getSchema();
const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
const knownValueNames = Object.create(null);
return {
EnumTypeDefinition: checkValueUniqueness,
EnumTypeExtension: checkValueUniqueness,
};
function checkValueUniqueness(node) {
const typeName = node.name.value;
if (!knownValueNames[typeName]) {
knownValueNames[typeName] = Object.create(null);
}
if (node.values) {
const valueNames = knownValueNames[typeName];
for (const valueDef of node.values) {
const valueName = valueDef.name.value;
const existingType = existingTypeMap[typeName];
if (isEnumType(existingType) && existingType.getValue(valueName)) {
context.reportError(
new GraphQLError(
existedEnumValueNameMessage(typeName, valueName),
valueDef.name,
),
);
} else if (valueNames[valueName]) {
context.reportError(
new GraphQLError(
duplicateEnumValueNameMessage(typeName, valueName),
[valueNames[valueName], valueDef.name],
),
);
} else {
valueNames[valueName] = valueDef.name;
}
}
}
return false;
}
}

View File

@@ -0,0 +1,51 @@
import { GraphQLError } from '../../error/GraphQLError';
import { isEnumType } from '../../type/definition';
export function duplicateEnumValueNameMessage(typeName, valueName) {
return "Enum value \"".concat(typeName, ".").concat(valueName, "\" can only be defined once.");
}
export function existedEnumValueNameMessage(typeName, valueName) {
return "Enum value \"".concat(typeName, ".").concat(valueName, "\" already exists in the schema. It cannot also be defined in this type extension.");
}
/**
* Unique enum value names
*
* A GraphQL enum type is only valid if all its values are uniquely named.
*/
export function UniqueEnumValueNames(context) {
var schema = context.getSchema();
var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
var knownValueNames = Object.create(null);
return {
EnumTypeDefinition: checkValueUniqueness,
EnumTypeExtension: checkValueUniqueness
};
function checkValueUniqueness(node) {
var typeName = node.name.value;
if (!knownValueNames[typeName]) {
knownValueNames[typeName] = Object.create(null);
}
if (node.values) {
var valueNames = knownValueNames[typeName];
for (var _i2 = 0, _node$values2 = node.values; _i2 < _node$values2.length; _i2++) {
var valueDef = _node$values2[_i2];
var valueName = valueDef.name.value;
var existingType = existingTypeMap[typeName];
if (isEnumType(existingType) && existingType.getValue(valueName)) {
context.reportError(new GraphQLError(existedEnumValueNameMessage(typeName, valueName), valueDef.name));
} else if (valueNames[valueName]) {
context.reportError(new GraphQLError(duplicateEnumValueNameMessage(typeName, valueName), [valueNames[valueName], valueDef.name]));
} else {
valueNames[valueName] = valueDef.name;
}
}
}
return false;
}
}

View File

@@ -0,0 +1,21 @@
import { ASTVisitor } from '../../language/visitor';
import { SDLValidationContext } from '../ValidationContext';
export function duplicateFieldDefinitionNameMessage(
typeName: string,
fieldName: string,
): string;
export function existedFieldDefinitionNameMessage(
typeName: string,
fieldName: string,
): string;
/**
* Unique field definition names
*
* A GraphQL complex type is only valid if all its fields are uniquely named.
*/
export function UniqueFieldDefinitionNames(
context: SDLValidationContext,
): ASTVisitor;

View File

@@ -0,0 +1,75 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.duplicateFieldDefinitionNameMessage = duplicateFieldDefinitionNameMessage;
exports.existedFieldDefinitionNameMessage = existedFieldDefinitionNameMessage;
exports.UniqueFieldDefinitionNames = UniqueFieldDefinitionNames;
var _GraphQLError = require("../../error/GraphQLError");
var _definition = require("../../type/definition");
function duplicateFieldDefinitionNameMessage(typeName, fieldName) {
return "Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once.");
}
function existedFieldDefinitionNameMessage(typeName, fieldName) {
return "Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. It cannot also be defined in this type extension.");
}
/**
* Unique field definition names
*
* A GraphQL complex type is only valid if all its fields are uniquely named.
*/
function UniqueFieldDefinitionNames(context) {
var schema = context.getSchema();
var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
var knownFieldNames = Object.create(null);
return {
InputObjectTypeDefinition: checkFieldUniqueness,
InputObjectTypeExtension: checkFieldUniqueness,
InterfaceTypeDefinition: checkFieldUniqueness,
InterfaceTypeExtension: checkFieldUniqueness,
ObjectTypeDefinition: checkFieldUniqueness,
ObjectTypeExtension: checkFieldUniqueness
};
function checkFieldUniqueness(node) {
var typeName = node.name.value;
if (!knownFieldNames[typeName]) {
knownFieldNames[typeName] = Object.create(null);
}
if (node.fields) {
var fieldNames = knownFieldNames[typeName];
for (var _i2 = 0, _node$fields2 = node.fields; _i2 < _node$fields2.length; _i2++) {
var fieldDef = _node$fields2[_i2];
var fieldName = fieldDef.name.value;
if (hasField(existingTypeMap[typeName], fieldName)) {
context.reportError(new _GraphQLError.GraphQLError(existedFieldDefinitionNameMessage(typeName, fieldName), fieldDef.name));
} else if (fieldNames[fieldName]) {
context.reportError(new _GraphQLError.GraphQLError(duplicateFieldDefinitionNameMessage(typeName, fieldName), [fieldNames[fieldName], fieldDef.name]));
} else {
fieldNames[fieldName] = fieldDef.name;
}
}
}
return false;
}
}
function hasField(type, fieldName) {
if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type) || (0, _definition.isInputObjectType)(type)) {
return type.getFields()[fieldName];
}
return false;
}

View File

@@ -0,0 +1,90 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import {
isObjectType,
isInterfaceType,
isInputObjectType,
} from '../../type/definition';
import { type SDLValidationContext } from '../ValidationContext';
export function duplicateFieldDefinitionNameMessage(
typeName: string,
fieldName: string,
): string {
return `Field "${typeName}.${fieldName}" can only be defined once.`;
}
export function existedFieldDefinitionNameMessage(
typeName: string,
fieldName: string,
): string {
return `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`;
}
/**
* Unique field definition names
*
* A GraphQL complex type is only valid if all its fields are uniquely named.
*/
export function UniqueFieldDefinitionNames(
context: SDLValidationContext,
): ASTVisitor {
const schema = context.getSchema();
const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
const knownFieldNames = Object.create(null);
return {
InputObjectTypeDefinition: checkFieldUniqueness,
InputObjectTypeExtension: checkFieldUniqueness,
InterfaceTypeDefinition: checkFieldUniqueness,
InterfaceTypeExtension: checkFieldUniqueness,
ObjectTypeDefinition: checkFieldUniqueness,
ObjectTypeExtension: checkFieldUniqueness,
};
function checkFieldUniqueness(node) {
const typeName = node.name.value;
if (!knownFieldNames[typeName]) {
knownFieldNames[typeName] = Object.create(null);
}
if (node.fields) {
const fieldNames = knownFieldNames[typeName];
for (const fieldDef of node.fields) {
const fieldName = fieldDef.name.value;
if (hasField(existingTypeMap[typeName], fieldName)) {
context.reportError(
new GraphQLError(
existedFieldDefinitionNameMessage(typeName, fieldName),
fieldDef.name,
),
);
} else if (fieldNames[fieldName]) {
context.reportError(
new GraphQLError(
duplicateFieldDefinitionNameMessage(typeName, fieldName),
[fieldNames[fieldName], fieldDef.name],
),
);
} else {
fieldNames[fieldName] = fieldDef.name;
}
}
}
return false;
}
}
function hasField(type, fieldName) {
if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {
return type.getFields()[fieldName];
}
return false;
}

View File

@@ -0,0 +1,62 @@
import { GraphQLError } from '../../error/GraphQLError';
import { isObjectType, isInterfaceType, isInputObjectType } from '../../type/definition';
export function duplicateFieldDefinitionNameMessage(typeName, fieldName) {
return "Field \"".concat(typeName, ".").concat(fieldName, "\" can only be defined once.");
}
export function existedFieldDefinitionNameMessage(typeName, fieldName) {
return "Field \"".concat(typeName, ".").concat(fieldName, "\" already exists in the schema. It cannot also be defined in this type extension.");
}
/**
* Unique field definition names
*
* A GraphQL complex type is only valid if all its fields are uniquely named.
*/
export function UniqueFieldDefinitionNames(context) {
var schema = context.getSchema();
var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);
var knownFieldNames = Object.create(null);
return {
InputObjectTypeDefinition: checkFieldUniqueness,
InputObjectTypeExtension: checkFieldUniqueness,
InterfaceTypeDefinition: checkFieldUniqueness,
InterfaceTypeExtension: checkFieldUniqueness,
ObjectTypeDefinition: checkFieldUniqueness,
ObjectTypeExtension: checkFieldUniqueness
};
function checkFieldUniqueness(node) {
var typeName = node.name.value;
if (!knownFieldNames[typeName]) {
knownFieldNames[typeName] = Object.create(null);
}
if (node.fields) {
var fieldNames = knownFieldNames[typeName];
for (var _i2 = 0, _node$fields2 = node.fields; _i2 < _node$fields2.length; _i2++) {
var fieldDef = _node$fields2[_i2];
var fieldName = fieldDef.name.value;
if (hasField(existingTypeMap[typeName], fieldName)) {
context.reportError(new GraphQLError(existedFieldDefinitionNameMessage(typeName, fieldName), fieldDef.name));
} else if (fieldNames[fieldName]) {
context.reportError(new GraphQLError(duplicateFieldDefinitionNameMessage(typeName, fieldName), [fieldNames[fieldName], fieldDef.name]));
} else {
fieldNames[fieldName] = fieldDef.name;
}
}
}
return false;
}
}
function hasField(type, fieldName) {
if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {
return type.getFields()[fieldName];
}
return false;
}

View File

@@ -0,0 +1,11 @@
import { ASTVisitor } from '../../language/visitor';
import { ASTValidationContext } from '../ValidationContext';
export function duplicateFragmentNameMessage(fragName: string): string;
/**
* Unique fragment names
*
* A GraphQL document is only valid if all defined fragments have unique names.
*/
export function UniqueFragmentNames(context: ASTValidationContext): ASTVisitor;

View File

@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.duplicateFragmentNameMessage = duplicateFragmentNameMessage;
exports.UniqueFragmentNames = UniqueFragmentNames;
var _GraphQLError = require("../../error/GraphQLError");
function duplicateFragmentNameMessage(fragName) {
return "There can be only one fragment named \"".concat(fragName, "\".");
}
/**
* Unique fragment names
*
* A GraphQL document is only valid if all defined fragments have unique names.
*/
function UniqueFragmentNames(context) {
var knownFragmentNames = Object.create(null);
return {
OperationDefinition: function OperationDefinition() {
return false;
},
FragmentDefinition: function FragmentDefinition(node) {
var fragmentName = node.name.value;
if (knownFragmentNames[fragmentName]) {
context.reportError(new _GraphQLError.GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name]));
} else {
knownFragmentNames[fragmentName] = node.name;
}
return false;
}
};
}

View File

@@ -0,0 +1,36 @@
// @flow strict
import { GraphQLError } from '../../error/GraphQLError';
import { type ASTVisitor } from '../../language/visitor';
import { type ASTValidationContext } from '../ValidationContext';
export function duplicateFragmentNameMessage(fragName: string): string {
return `There can be only one fragment named "${fragName}".`;
}
/**
* Unique fragment names
*
* A GraphQL document is only valid if all defined fragments have unique names.
*/
export function UniqueFragmentNames(context: ASTValidationContext): ASTVisitor {
const knownFragmentNames = Object.create(null);
return {
OperationDefinition: () => false,
FragmentDefinition(node) {
const fragmentName = node.name.value;
if (knownFragmentNames[fragmentName]) {
context.reportError(
new GraphQLError(duplicateFragmentNameMessage(fragmentName), [
knownFragmentNames[fragmentName],
node.name,
]),
);
} else {
knownFragmentNames[fragmentName] = node.name;
}
return false;
},
};
}

View File

@@ -0,0 +1,29 @@
import { GraphQLError } from '../../error/GraphQLError';
export function duplicateFragmentNameMessage(fragName) {
return "There can be only one fragment named \"".concat(fragName, "\".");
}
/**
* Unique fragment names
*
* A GraphQL document is only valid if all defined fragments have unique names.
*/
export function UniqueFragmentNames(context) {
var knownFragmentNames = Object.create(null);
return {
OperationDefinition: function OperationDefinition() {
return false;
},
FragmentDefinition: function FragmentDefinition(node) {
var fragmentName = node.name.value;
if (knownFragmentNames[fragmentName]) {
context.reportError(new GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name]));
} else {
knownFragmentNames[fragmentName] = node.name;
}
return false;
}
};
}

Some files were not shown because too many files have changed in this diff Show More