diff --git a/src/execution/execute.ts b/src/execution/execute.ts index 65953098c1..b60edc5d08 100644 --- a/src/execution/execute.ts +++ b/src/execution/execute.ts @@ -45,6 +45,7 @@ import { isListType, isNonNullType, isObjectType, + isSemanticNonNullType, } from '../type/definition'; import { SchemaMetaFieldDef, @@ -679,9 +680,9 @@ function completeValue( throw result; } - // If field type is NonNull, complete for inner type, and throw field error + // If field type is non-nullable, complete for inner type, and throw field error // if result is null. - if (isNonNullType(returnType)) { + if (isNonNullType(returnType) || isSemanticNonNullType(returnType)) { const completed = completeValue( exeContext, returnType.ofType, @@ -692,7 +693,9 @@ function completeValue( ); if (completed === null) { throw new Error( - `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`, + `Cannot return null for ${ + isSemanticNonNullType(returnType) ? 'semantically ' : '' + }non-nullable field ${info.parentType.name}.${info.fieldName}.`, ); } return completed; diff --git a/src/index.ts b/src/index.ts index 4df70d7d74..fc00f68ae7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -48,6 +48,7 @@ export { GraphQLInputObjectType, GraphQLList, GraphQLNonNull, + GraphQLSemanticNonNull, // Standard GraphQL Scalars specifiedScalarTypes, GraphQLInt, @@ -95,6 +96,7 @@ export { isInputObjectType, isListType, isNonNullType, + isSemanticNonNullType, isInputType, isOutputType, isLeafType, @@ -120,6 +122,7 @@ export { assertInputObjectType, assertListType, assertNonNullType, + assertSemanticNonNullType, assertInputType, assertOutputType, assertLeafType, @@ -148,6 +151,7 @@ export type { GraphQLAbstractType, GraphQLWrappingType, GraphQLNullableType, + GraphQLNullableOutputType, GraphQLNamedType, GraphQLNamedInputType, GraphQLNamedOutputType, @@ -287,6 +291,7 @@ export type { NamedTypeNode, ListTypeNode, NonNullTypeNode, + SemanticNonNullTypeNode, TypeSystemDefinitionNode, SchemaDefinitionNode, OperationTypeDefinitionNode, @@ -482,6 +487,7 @@ export type { IntrospectionNamedTypeRef, IntrospectionListTypeRef, IntrospectionNonNullTypeRef, + IntrospectionSemanticNonNullTypeRef, IntrospectionField, IntrospectionInputValue, IntrospectionEnumValue, diff --git a/src/jsutils/memoize1.ts b/src/jsutils/memoize1.ts new file mode 100644 index 0000000000..d3ea100b68 --- /dev/null +++ b/src/jsutils/memoize1.ts @@ -0,0 +1,22 @@ +/** + * Memoizes the provided single-argument function. + */ +export function memoize1( + fn: (a1: A1) => R, +): (a1: A1) => R { + let cache0: WeakMap; + + return function memoized(a1) { + if (cache0 === undefined) { + cache0 = new WeakMap(); + } + + let fnResult = cache0.get(a1); + if (fnResult === undefined) { + fnResult = fn(a1); + cache0.set(a1, fnResult); + } + + return fnResult; + }; +} diff --git a/src/language/__tests__/parser-test.ts b/src/language/__tests__/parser-test.ts index caa922a27d..59d39cd872 100644 --- a/src/language/__tests__/parser-test.ts +++ b/src/language/__tests__/parser-test.ts @@ -636,6 +636,23 @@ describe('Parser', () => { }); }); + it('parses semantic-non-null types', () => { + const result = parseType('MyType*'); + expectJSON(result).toDeepEqual({ + kind: Kind.SEMANTIC_NON_NULL_TYPE, + loc: { start: 0, end: 7 }, + type: { + kind: Kind.NAMED_TYPE, + loc: { start: 0, end: 6 }, + name: { + kind: Kind.NAME, + loc: { start: 0, end: 6 }, + value: 'MyType', + }, + }, + }); + }); + it('parses nested types', () => { const result = parseType('[MyType!]'); expectJSON(result).toDeepEqual({ diff --git a/src/language/__tests__/predicates-test.ts b/src/language/__tests__/predicates-test.ts index 13477f8de9..32ef7d1fe1 100644 --- a/src/language/__tests__/predicates-test.ts +++ b/src/language/__tests__/predicates-test.ts @@ -92,6 +92,7 @@ describe('AST node predicates', () => { 'NamedType', 'ListType', 'NonNullType', + 'SemanticNonNullType', ]); }); diff --git a/src/language/ast.ts b/src/language/ast.ts index 6137eb6c1a..1fc99414ef 100644 --- a/src/language/ast.ts +++ b/src/language/ast.ts @@ -161,6 +161,7 @@ export type ASTNode = | NamedTypeNode | ListTypeNode | NonNullTypeNode + | SemanticNonNullTypeNode | SchemaDefinitionNode | OperationTypeDefinitionNode | ScalarTypeDefinitionNode @@ -235,6 +236,7 @@ export const QueryDocumentKeys: { NamedType: ['name'], ListType: ['type'], NonNullType: ['type'], + SemanticNonNullType: ['type'], SchemaDefinition: ['description', 'directives', 'operationTypes'], OperationTypeDefinition: ['type'], @@ -521,7 +523,11 @@ export interface ConstDirectiveNode { /** Type Reference */ -export type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNode; +export type TypeNode = + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SemanticNonNullTypeNode; export interface NamedTypeNode { readonly kind: Kind.NAMED_TYPE; @@ -541,6 +547,12 @@ export interface NonNullTypeNode { readonly type: NamedTypeNode | ListTypeNode; } +export interface SemanticNonNullTypeNode { + readonly kind: Kind.SEMANTIC_NON_NULL_TYPE; + readonly loc?: Location; + readonly type: NamedTypeNode | ListTypeNode; +} + /** Type System Definition */ export type TypeSystemDefinitionNode = diff --git a/src/language/index.ts b/src/language/index.ts index ec4d195e1a..a760fd21b3 100644 --- a/src/language/index.ts +++ b/src/language/index.ts @@ -67,6 +67,7 @@ export type { NamedTypeNode, ListTypeNode, NonNullTypeNode, + SemanticNonNullTypeNode, TypeSystemDefinitionNode, SchemaDefinitionNode, OperationTypeDefinitionNode, diff --git a/src/language/kinds.ts b/src/language/kinds.ts index cd05f66a3b..e91373746c 100644 --- a/src/language/kinds.ts +++ b/src/language/kinds.ts @@ -37,6 +37,7 @@ enum Kind { NAMED_TYPE = 'NamedType', LIST_TYPE = 'ListType', NON_NULL_TYPE = 'NonNullType', + SEMANTIC_NON_NULL_TYPE = 'SemanticNonNullType', /** Type System Definitions */ SCHEMA_DEFINITION = 'SchemaDefinition', diff --git a/src/language/lexer.ts b/src/language/lexer.ts index 818f81b286..8fccd4e709 100644 --- a/src/language/lexer.ts +++ b/src/language/lexer.ts @@ -91,6 +91,7 @@ export class Lexer { export function isPunctuatorTokenKind(kind: TokenKind): boolean { return ( kind === TokenKind.BANG || + kind === TokenKind.ASTERISK || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || @@ -246,7 +247,7 @@ function readNextToken(lexer: Lexer, start: number): Token { // - FloatValue // - StringValue // - // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } + // Punctuator :: one of ! $ & ( ) * ... : = @ [ ] { | } case 0x0021: // ! return createToken(lexer, TokenKind.BANG, position, position + 1); case 0x0024: // $ @@ -257,6 +258,8 @@ function readNextToken(lexer: Lexer, start: number): Token { return createToken(lexer, TokenKind.PAREN_L, position, position + 1); case 0x0029: // ) return createToken(lexer, TokenKind.PAREN_R, position, position + 1); + case 0x002a: // * + return createToken(lexer, TokenKind.ASTERISK, position, position + 1); case 0x002e: // . if ( body.charCodeAt(position + 1) === 0x002e && diff --git a/src/language/parser.ts b/src/language/parser.ts index 03e4166210..57477430a3 100644 --- a/src/language/parser.ts +++ b/src/language/parser.ts @@ -50,6 +50,7 @@ import type { SchemaExtensionNode, SelectionNode, SelectionSetNode, + SemanticNonNullTypeNode, StringValueNode, Token, TypeNode, @@ -749,6 +750,7 @@ export class Parser { * - NamedType * - ListType * - NonNullType + * - SemanticNonNullType */ parseTypeReference(): TypeNode { const start = this._lexer.token; @@ -770,6 +772,12 @@ export class Parser { type, }); } + if (this.expectOptionalToken(TokenKind.ASTERISK)) { + return this.node(start, { + kind: Kind.SEMANTIC_NON_NULL_TYPE, + type, + }); + } return type; } diff --git a/src/language/predicates.ts b/src/language/predicates.ts index a390f4ee55..3ddf52b94c 100644 --- a/src/language/predicates.ts +++ b/src/language/predicates.ts @@ -67,7 +67,8 @@ export function isTypeNode(node: ASTNode): node is TypeNode { return ( node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || - node.kind === Kind.NON_NULL_TYPE + node.kind === Kind.NON_NULL_TYPE || + node.kind === Kind.SEMANTIC_NON_NULL_TYPE ); } diff --git a/src/language/printer.ts b/src/language/printer.ts index e95c118d8b..f08ba54f56 100644 --- a/src/language/printer.ts +++ b/src/language/printer.ts @@ -131,6 +131,7 @@ const printDocASTReducer: ASTReducer = { NamedType: { leave: ({ name }) => name }, ListType: { leave: ({ type }) => '[' + type + ']' }, NonNullType: { leave: ({ type }) => type + '!' }, + SemanticNonNullType: { leave: ({ type }) => type + '*' }, // Type System Definitions diff --git a/src/language/tokenKind.ts b/src/language/tokenKind.ts index 0c260df99e..fd53d6ebf3 100644 --- a/src/language/tokenKind.ts +++ b/src/language/tokenKind.ts @@ -6,6 +6,7 @@ enum TokenKind { SOF = '', EOF = '', BANG = '!', + ASTERISK = '*', DOLLAR = '$', AMP = '&', PAREN_L = '(', diff --git a/src/type/__tests__/introspection-test.ts b/src/type/__tests__/introspection-test.ts index 8c5cacba0d..77d024c9cf 100644 --- a/src/type/__tests__/introspection-test.ts +++ b/src/type/__tests__/introspection-test.ts @@ -437,6 +437,11 @@ describe('Introspection', () => { isDeprecated: false, deprecationReason: null, }, + { + name: 'SEMANTIC_NON_NULL', + isDeprecated: false, + deprecationReason: null, + }, ], possibleTypes: null, }, @@ -506,7 +511,21 @@ describe('Introspection', () => { }, { name: 'type', - args: [], + args: [ + { + name: 'includeSemanticNonNull', + type: { + kind: 'NON_NULL', + name: null, + ofType: { + kind: 'SCALAR', + name: 'Boolean', + ofType: null, + }, + }, + defaultValue: 'false', + }, + ], type: { kind: 'NON_NULL', name: null, diff --git a/src/type/__tests__/predicate-test.ts b/src/type/__tests__/predicate-test.ts index 81e721e7df..1c576e8eaa 100644 --- a/src/type/__tests__/predicate-test.ts +++ b/src/type/__tests__/predicate-test.ts @@ -23,6 +23,7 @@ import { assertObjectType, assertOutputType, assertScalarType, + assertSemanticNonNullType, assertType, assertUnionType, assertWrappingType, @@ -35,6 +36,7 @@ import { GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, + GraphQLSemanticNonNull, GraphQLUnionType, isAbstractType, isCompositeType, @@ -52,6 +54,7 @@ import { isRequiredArgument, isRequiredInputField, isScalarType, + isSemanticNonNullType, isType, isUnionType, isWrappingType, @@ -298,6 +301,47 @@ describe('Type predicates', () => { expect(() => assertNonNullType(new GraphQLList(new GraphQLNonNull(ObjectType))), ).to.throw(); + expect(isNonNullType(new GraphQLSemanticNonNull(ObjectType))).to.equal( + false, + ); + expect(() => + assertNonNullType(new GraphQLSemanticNonNull(ObjectType)), + ).to.throw(); + }); + }); + + describe('isSemanticNonNullType', () => { + it('returns true for a semantic-non-null wrapped type', () => { + expect( + isSemanticNonNullType(new GraphQLSemanticNonNull(ObjectType)), + ).to.equal(true); + expect(() => + assertSemanticNonNullType(new GraphQLSemanticNonNull(ObjectType)), + ).to.not.throw(); + }); + + it('returns false for an unwrapped type', () => { + expect(isSemanticNonNullType(ObjectType)).to.equal(false); + expect(() => assertSemanticNonNullType(ObjectType)).to.throw(); + }); + + it('returns false for a not non-null wrapped type', () => { + expect( + isSemanticNonNullType( + new GraphQLList(new GraphQLSemanticNonNull(ObjectType)), + ), + ).to.equal(false); + expect(() => + assertSemanticNonNullType( + new GraphQLList(new GraphQLSemanticNonNull(ObjectType)), + ), + ).to.throw(); + expect(isSemanticNonNullType(new GraphQLNonNull(ObjectType))).to.equal( + false, + ); + expect(() => + assertSemanticNonNullType(new GraphQLNonNull(ObjectType)), + ).to.throw(); }); }); @@ -476,6 +520,12 @@ describe('Type predicates', () => { expect(() => assertWrappingType(new GraphQLNonNull(ObjectType)), ).to.not.throw(); + expect(isWrappingType(new GraphQLSemanticNonNull(ObjectType))).to.equal( + true, + ); + expect(() => + assertWrappingType(new GraphQLSemanticNonNull(ObjectType)), + ).to.not.throw(); }); it('returns false for unwrapped types', () => { @@ -497,6 +547,14 @@ describe('Type predicates', () => { expect(() => assertNullableType(new GraphQLList(new GraphQLNonNull(ObjectType))), ).to.not.throw(); + expect( + isNullableType(new GraphQLList(new GraphQLSemanticNonNull(ObjectType))), + ).to.equal(true); + expect(() => + assertNullableType( + new GraphQLList(new GraphQLSemanticNonNull(ObjectType)), + ), + ).to.not.throw(); }); it('returns false for non-null types', () => { @@ -504,6 +562,12 @@ describe('Type predicates', () => { expect(() => assertNullableType(new GraphQLNonNull(ObjectType)), ).to.throw(); + expect(isNullableType(new GraphQLSemanticNonNull(ObjectType))).to.equal( + false, + ); + expect(() => + assertNullableType(new GraphQLSemanticNonNull(ObjectType)), + ).to.throw(); }); }); diff --git a/src/type/definition.ts b/src/type/definition.ts index 61c57c4f38..3a814944dc 100644 --- a/src/type/definition.ts +++ b/src/type/definition.ts @@ -67,6 +67,14 @@ export type GraphQLType = | GraphQLEnumType | GraphQLInputObjectType | GraphQLList + > + | GraphQLSemanticNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList >; export function isType(type: unknown): type is GraphQLType { @@ -78,7 +86,8 @@ export function isType(type: unknown): type is GraphQLType { isEnumType(type) || isInputObjectType(type) || isListType(type) || - isNonNullType(type) + isNonNullType(type) || + isSemanticNonNullType(type) ); } @@ -204,6 +213,23 @@ export function assertNonNullType(type: unknown): GraphQLNonNull { return type; } +export function isSemanticNonNullType( + type: unknown, +): type is GraphQLSemanticNonNull { + return instanceOf(type, GraphQLSemanticNonNull); +} + +export function assertSemanticNonNullType( + type: unknown, +): GraphQLSemanticNonNull { + if (!isSemanticNonNullType(type)) { + throw new Error( + `Expected ${inspect(type)} to be a GraphQL Semantic-Non-Null type.`, + ); + } + return type; +} + /** * These types may be used as input types for arguments and directives. */ @@ -218,13 +244,16 @@ export type GraphQLInputType = | GraphQLInputObjectType | GraphQLList >; +// Note: GraphQLSemanticNonNull is currently not allowed for input types export function isInputType(type: unknown): type is GraphQLInputType { return ( isScalarType(type) || isEnumType(type) || isInputObjectType(type) || - (isWrappingType(type) && isInputType(type.ofType)) + (!isSemanticNonNullType(type) && + isWrappingType(type) && + isInputType(type.ofType)) ); } @@ -252,6 +281,14 @@ export type GraphQLOutputType = | GraphQLUnionType | GraphQLEnumType | GraphQLList + > + | GraphQLSemanticNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList >; export function isOutputType(type: unknown): type is GraphQLOutputType { @@ -415,16 +452,70 @@ export class GraphQLNonNull { } } +/** + * Semantic-Non-Null Type Wrapper + * + * A semantic-non-null is a wrapping type which points to another type. + * Semantic-non-null types enforce that their values are never null unless + * caused by an error being raised. It is useful for fields which you can make + * a guarantee on non-nullability in a no-error case, for example when you know + * that a related entity must exist (but acknowledge that retrieving it may + * produce an error). + * + * Example: + * + * ```ts + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * email: { type: new GraphQLSemanticNonNull(GraphQLString) }, + * }) + * }) + * ``` + * Note: the enforcement of non-nullability occurs within the executor. + * + * @experimental + */ +export class GraphQLSemanticNonNull { + readonly ofType: T; + + constructor(ofType: T) { + devAssert( + isNullableType(ofType), + `Expected ${inspect(ofType)} to be a GraphQL nullable type.`, + ); + devAssert( + isOutputType(ofType), + `Expected ${inspect(ofType)} to be a GraphQL output type.`, + ); + + this.ofType = ofType; + } + + get [Symbol.toStringTag]() { + return 'GraphQLSemanticNonNull'; + } + + toString(): string { + return String(this.ofType) + '*'; + } + + toJSON(): string { + return this.toString(); + } +} + /** * These types wrap and modify other types */ export type GraphQLWrappingType = | GraphQLList - | GraphQLNonNull; + | GraphQLNonNull + | GraphQLSemanticNonNull; export function isWrappingType(type: unknown): type is GraphQLWrappingType { - return isListType(type) || isNonNullType(type); + return isListType(type) || isNonNullType(type) || isSemanticNonNullType(type); } export function assertWrappingType(type: unknown): GraphQLWrappingType { @@ -446,8 +537,19 @@ export type GraphQLNullableType = | GraphQLInputObjectType | GraphQLList; +/** + * These types can all accept null as a value, and are suitable for output. + */ +export type GraphQLNullableOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList; + export function isNullableType(type: unknown): type is GraphQLNullableType { - return isType(type) && !isNonNullType(type); + return isType(type) && !isNonNullType(type) && !isSemanticNonNullType(type); } export function assertNullableType(type: unknown): GraphQLNullableType { @@ -458,7 +560,11 @@ export function assertNullableType(type: unknown): GraphQLNullableType { } export function getNullableType(type: undefined | null): void; +export function getNullableType( + type: T | GraphQLNonNull | GraphQLSemanticNonNull, +): T; export function getNullableType( + // eslint-disable-next-line @typescript-eslint/unified-signatures type: T | GraphQLNonNull, ): T; export function getNullableType( @@ -468,12 +574,14 @@ export function getNullableType( type: Maybe, ): GraphQLNullableType | undefined { if (type) { - return isNonNullType(type) ? type.ofType : type; + return isNonNullType(type) || isSemanticNonNullType(type) + ? type.ofType + : type; } } /** - * These named types do not include modifiers like List or NonNull. + * These named types do not include modifiers like List, NonNull, or SemanticNonNull */ export type GraphQLNamedType = GraphQLNamedInputType | GraphQLNamedOutputType; @@ -1073,6 +1181,7 @@ export interface GraphQLArgument { } export function isRequiredArgument(arg: GraphQLArgument): boolean { + // Note: input types cannot be SemanticNonNull return isNonNullType(arg.type) && arg.defaultValue === undefined; } @@ -1764,6 +1873,7 @@ export interface GraphQLInputField { } export function isRequiredInputField(field: GraphQLInputField): boolean { + // Note: input types cannot be SemanticNonNull return isNonNullType(field.type) && field.defaultValue === undefined; } diff --git a/src/type/index.ts b/src/type/index.ts index cf276d1e02..92199ca0d6 100644 --- a/src/type/index.ts +++ b/src/type/index.ts @@ -23,6 +23,7 @@ export { isInputObjectType, isListType, isNonNullType, + isSemanticNonNullType, isInputType, isOutputType, isLeafType, @@ -43,6 +44,7 @@ export { assertInputObjectType, assertListType, assertNonNullType, + assertSemanticNonNullType, assertInputType, assertOutputType, assertLeafType, @@ -64,6 +66,7 @@ export { // Type Wrappers GraphQLList, GraphQLNonNull, + GraphQLSemanticNonNull, } from './definition'; export type { @@ -75,6 +78,7 @@ export type { GraphQLAbstractType, GraphQLWrappingType, GraphQLNullableType, + GraphQLNullableOutputType, GraphQLNamedType, GraphQLNamedInputType, GraphQLNamedOutputType, diff --git a/src/type/introspection.ts b/src/type/introspection.ts index 2c66ca5098..ced8e56e0c 100644 --- a/src/type/introspection.ts +++ b/src/type/introspection.ts @@ -1,5 +1,6 @@ import { inspect } from '../jsutils/inspect'; import { invariant } from '../jsutils/invariant'; +import { memoize1 } from '../jsutils/memoize1'; import { DirectiveLocation } from '../language/directiveLocation'; import { print } from '../language/printer'; @@ -12,6 +13,7 @@ import type { GraphQLFieldConfigMap, GraphQLInputField, GraphQLNamedType, + GraphQLOutputType, GraphQLType, } from './definition'; import { @@ -27,6 +29,7 @@ import { isNonNullType, isObjectType, isScalarType, + isSemanticNonNullType, isUnionType, } from './definition'; import type { GraphQLDirective } from './directives'; @@ -237,6 +240,9 @@ export const __Type: GraphQLObjectType = new GraphQLObjectType({ if (isNonNullType(type)) { return TypeKind.NON_NULL; } + if (isSemanticNonNullType(type)) { + return TypeKind.SEMANTIC_NON_NULL; + } /* c8 ignore next 3 */ // Not reachable, all possible types have been considered) invariant(false, `Unexpected type: "${inspect(type)}".`); @@ -366,7 +372,18 @@ export const __Field: GraphQLObjectType = new GraphQLObjectType({ }, type: { type: new GraphQLNonNull(__Type), - resolve: (field) => field.type, + args: { + includeSemanticNonNull: { + type: new GraphQLNonNull(GraphQLBoolean), + defaultValue: false, + }, + }, + resolve: (field, { includeSemanticNonNull }) => { + if (includeSemanticNonNull) { + return field.type; + } + return stripSemanticNonNullTypes(field.type); + }, }, isDeprecated: { type: new GraphQLNonNull(GraphQLBoolean), @@ -379,6 +396,28 @@ export const __Field: GraphQLObjectType = new GraphQLObjectType({ } as GraphQLFieldConfigMap, unknown>), }); +const stripSemanticNonNullTypes = memoize1(_stripSemanticNonNullTypes); +function _stripSemanticNonNullTypes( + type: GraphQLOutputType, +): GraphQLOutputType { + if (isNonNullType(type)) { + const convertedInner = stripSemanticNonNullTypes(type.ofType); + if (convertedInner === type.ofType) { + return type; // No change needed + } + return new GraphQLNonNull(convertedInner); + } else if (isListType(type)) { + const convertedInner = stripSemanticNonNullTypes(type.ofType); + if (convertedInner === type.ofType) { + return type; // No change needed + } + return new GraphQLList(convertedInner); + } else if (isSemanticNonNullType(type)) { + return stripSemanticNonNullTypes(type.ofType); + } + return type; +} + export const __InputValue: GraphQLObjectType = new GraphQLObjectType({ name: '__InputValue', description: @@ -452,6 +491,7 @@ enum TypeKind { INPUT_OBJECT = 'INPUT_OBJECT', LIST = 'LIST', NON_NULL = 'NON_NULL', + SEMANTIC_NON_NULL = 'SEMANTIC_NON_NULL', } export { TypeKind }; @@ -497,6 +537,11 @@ export const __TypeKind: GraphQLEnumType = new GraphQLEnumType({ description: 'Indicates this type is a non-null. `ofType` is a valid field.', }, + SEMANTIC_NON_NULL: { + value: TypeKind.SEMANTIC_NON_NULL, + description: + 'Indicates this type is a semantic-non-null. `ofType` is a valid field.', + }, }, }); diff --git a/src/utilities/__tests__/printSchema-test.ts b/src/utilities/__tests__/printSchema-test.ts index 37af4a60f7..4596a73cf4 100644 --- a/src/utilities/__tests__/printSchema-test.ts +++ b/src/utilities/__tests__/printSchema-test.ts @@ -770,6 +770,9 @@ describe('Type System Printer', () => { """Indicates this type is a non-null. \`ofType\` is a valid field.""" NON_NULL + + """Indicates this type is a semantic-non-null. \`ofType\` is a valid field.""" + SEMANTIC_NON_NULL } """ @@ -779,7 +782,7 @@ describe('Type System Printer', () => { name: String! description: String args(includeDeprecated: Boolean = false): [__InputValue!]! - type: __Type! + type(includeSemanticNonNull: Boolean! = false): __Type! isDeprecated: Boolean! deprecationReason: String } diff --git a/src/utilities/astFromValue.ts b/src/utilities/astFromValue.ts index 1a880449c8..c605025035 100644 --- a/src/utilities/astFromValue.ts +++ b/src/utilities/astFromValue.ts @@ -42,6 +42,7 @@ export function astFromValue( value: unknown, type: GraphQLInputType, ): Maybe { + // Note: input types cannot be SemanticNonNull if (isNonNullType(type)) { const astValue = astFromValue(value, type.ofType); if (astValue?.kind === Kind.NULL) { diff --git a/src/utilities/buildClientSchema.ts b/src/utilities/buildClientSchema.ts index 83f6abada8..35dd0cac22 100644 --- a/src/utilities/buildClientSchema.ts +++ b/src/utilities/buildClientSchema.ts @@ -22,6 +22,7 @@ import { GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, + GraphQLSemanticNonNull, GraphQLUnionType, isInputType, isOutputType, @@ -137,6 +138,19 @@ export function buildClientSchema( const nullableType = getType(nullableRef); return new GraphQLNonNull(assertNullableType(nullableType)); } + if (typeRef.kind === TypeKind.SEMANTIC_NON_NULL) { + const nullableRef = typeRef.ofType; + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + const nullableType = assertNullableType(getType(nullableRef)); + if (!isOutputType(nullableType)) { + throw new Error( + 'A semantic non-null wrapper must wrap an output type.', + ); + } + return new GraphQLSemanticNonNull(nullableType); + } return getNamedType(typeRef); } diff --git a/src/utilities/extendSchema.ts b/src/utilities/extendSchema.ts index d53752d919..f33feaa038 100644 --- a/src/utilities/extendSchema.ts +++ b/src/utilities/extendSchema.ts @@ -53,6 +53,7 @@ import { GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, + GraphQLSemanticNonNull, GraphQLUnionType, isEnumType, isInputObjectType, @@ -60,7 +61,9 @@ import { isListType, isNonNullType, isObjectType, + isOutputType, isScalarType, + isSemanticNonNullType, isUnionType, } from '../type/definition'; import { @@ -225,6 +228,10 @@ export function extendSchemaImpl( // @ts-expect-error return new GraphQLNonNull(replaceType(type.ofType)); } + if (isSemanticNonNullType(type)) { + // @ts-expect-error + return new GraphQLSemanticNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME return replaceNamedType(type); } @@ -432,6 +439,13 @@ export function extendSchemaImpl( if (node.kind === Kind.NON_NULL_TYPE) { return new GraphQLNonNull(getWrappedType(node.type)); } + if (node.kind === Kind.SEMANTIC_NON_NULL_TYPE) { + const wrapped = getWrappedType(node.type); + if (!isOutputType(wrapped)) { + throw new Error('A semantic non-null type cannot wrap an input type.'); + } + return new GraphQLSemanticNonNull(wrapped); + } return getNamedType(node); } diff --git a/src/utilities/findBreakingChanges.ts b/src/utilities/findBreakingChanges.ts index 2489af9d62..5ed0313ae3 100644 --- a/src/utilities/findBreakingChanges.ts +++ b/src/utilities/findBreakingChanges.ts @@ -26,6 +26,7 @@ import { isRequiredArgument, isRequiredInputField, isScalarType, + isSemanticNonNullType, isUnionType, } from '../type/definition'; import { isSpecifiedScalarType } from '../type/scalars'; @@ -458,6 +459,9 @@ function isChangeSafeForObjectOrInterfaceField( )) || // moving from nullable to non-null of the same underlying type is safe (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) || + // moving from nullable to semantic-non-null of the same underlying type is safe + (isSemanticNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) ); } @@ -470,11 +474,28 @@ function isChangeSafeForObjectOrInterfaceField( ); } + if (isSemanticNonNullType(oldType)) { + return ( + // if they're both semantic-non-null, make sure the underlying types are compatible + (isSemanticNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField( + oldType.ofType, + newType.ofType, + )) || + // moving from semantic-non-null to non-null of the same underlying type is safe + (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType)) + ); + } + return ( // if they're both named types, see if their names are equivalent (isNamedType(newType) && oldType.name === newType.name) || // moving from nullable to non-null of the same underlying type is safe (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) || + // moving from nullable to semantic-non-null of the same underlying type is safe + (isSemanticNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) ); } diff --git a/src/utilities/getIntrospectionQuery.ts b/src/utilities/getIntrospectionQuery.ts index 373b474ed5..fa39a3ee58 100644 --- a/src/utilities/getIntrospectionQuery.ts +++ b/src/utilities/getIntrospectionQuery.ts @@ -38,6 +38,12 @@ export interface IntrospectionOptions { * Default: false */ oneOf?: boolean; + + /** + * Whether semantic non-null type wrappers should be included in the result. + * Default: false + */ + includeSemanticNonNull?: boolean; } /** @@ -52,6 +58,7 @@ export function getIntrospectionQuery(options?: IntrospectionOptions): string { schemaDescription: false, inputValueDeprecation: false, oneOf: false, + includeSemanticNonNull: false, ...options, }; @@ -70,6 +77,7 @@ export function getIntrospectionQuery(options?: IntrospectionOptions): string { return optionsWithDefault.inputValueDeprecation ? str : ''; } const oneOf = optionsWithDefault.oneOf ? 'isOneOf' : ''; + const includeSemanticNonNull = optionsWithDefault.includeSemanticNonNull; return ` query IntrospectionQuery { @@ -105,7 +113,11 @@ export function getIntrospectionQuery(options?: IntrospectionOptions): string { args${inputDeprecation('(includeDeprecated: true)')} { ...InputValue } - type { + type${ + includeSemanticNonNull + ? `(includeSemanticNonNull: ${includeSemanticNonNull})` + : '' + } { ...TypeRef } isDeprecated @@ -285,11 +297,21 @@ export interface IntrospectionNonNullTypeRef< readonly ofType: T; } +export interface IntrospectionSemanticNonNullTypeRef< + T extends IntrospectionTypeRef = IntrospectionTypeRef, +> { + readonly kind: 'SEMANTIC_NON_NULL'; + readonly ofType: T; +} + export type IntrospectionTypeRef = | IntrospectionNamedTypeRef | IntrospectionListTypeRef | IntrospectionNonNullTypeRef< IntrospectionNamedTypeRef | IntrospectionListTypeRef + > + | IntrospectionSemanticNonNullTypeRef< + IntrospectionNamedTypeRef | IntrospectionListTypeRef >; export type IntrospectionOutputTypeRef = diff --git a/src/utilities/index.ts b/src/utilities/index.ts index 452b975233..fa69583012 100644 --- a/src/utilities/index.ts +++ b/src/utilities/index.ts @@ -20,6 +20,7 @@ export type { IntrospectionNamedTypeRef, IntrospectionListTypeRef, IntrospectionNonNullTypeRef, + IntrospectionSemanticNonNullTypeRef, IntrospectionField, IntrospectionInputValue, IntrospectionEnumValue, diff --git a/src/utilities/lexicographicSortSchema.ts b/src/utilities/lexicographicSortSchema.ts index 26b6908c9f..5beb646859 100644 --- a/src/utilities/lexicographicSortSchema.ts +++ b/src/utilities/lexicographicSortSchema.ts @@ -19,6 +19,7 @@ import { GraphQLList, GraphQLNonNull, GraphQLObjectType, + GraphQLSemanticNonNull, GraphQLUnionType, isEnumType, isInputObjectType, @@ -27,6 +28,7 @@ import { isNonNullType, isObjectType, isScalarType, + isSemanticNonNullType, isUnionType, } from '../type/definition'; import { GraphQLDirective } from '../type/directives'; @@ -62,6 +64,9 @@ export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema { } else if (isNonNullType(type)) { // @ts-expect-error return new GraphQLNonNull(replaceType(type.ofType)); + } else if (isSemanticNonNullType(type)) { + // @ts-expect-error + return new GraphQLSemanticNonNull(replaceType(type.ofType)); } // @ts-expect-error FIXME: TS Conversion return replaceNamedType(type); diff --git a/src/utilities/typeComparators.ts b/src/utilities/typeComparators.ts index 287be40bfe..338ca24528 100644 --- a/src/utilities/typeComparators.ts +++ b/src/utilities/typeComparators.ts @@ -5,6 +5,7 @@ import { isListType, isNonNullType, isObjectType, + isSemanticNonNullType, } from '../type/definition'; import type { GraphQLSchema } from '../type/schema'; @@ -22,6 +23,11 @@ export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean { return isEqualType(typeA.ofType, typeB.ofType); } + // If either type is semantic-non-null, the other must also be semantic-non-null. + if (isSemanticNonNullType(typeA) && isSemanticNonNullType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } + // If either type is a list, the other must also be a list. if (isListType(typeA) && isListType(typeB)) { return isEqualType(typeA.ofType, typeB.ofType); @@ -52,8 +58,15 @@ export function isTypeSubTypeOf( } return false; } - if (isNonNullType(maybeSubType)) { - // If superType is nullable, maybeSubType may be non-null or nullable. + // If superType is semantic-non-null, maybeSubType must be semantic-non-null or non-null. + if (isSemanticNonNullType(superType)) { + if (isNonNullType(maybeSubType) || isSemanticNonNullType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if (isNonNullType(maybeSubType) || isSemanticNonNullType(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null, semantic-non-null, or nullable. return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); } diff --git a/src/utilities/typeFromAST.ts b/src/utilities/typeFromAST.ts index 7510df1046..67b7bbc5a2 100644 --- a/src/utilities/typeFromAST.ts +++ b/src/utilities/typeFromAST.ts @@ -7,7 +7,12 @@ import type { import { Kind } from '../language/kinds'; import type { GraphQLNamedType, GraphQLType } from '../type/definition'; -import { GraphQLList, GraphQLNonNull } from '../type/definition'; +import { + GraphQLList, + GraphQLNonNull, + GraphQLSemanticNonNull, + isOutputType, +} from '../type/definition'; import type { GraphQLSchema } from '../type/schema'; /** @@ -46,6 +51,13 @@ export function typeFromAST( const innerType = typeFromAST(schema, typeNode.type); return innerType && new GraphQLNonNull(innerType); } + case Kind.SEMANTIC_NON_NULL_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + if (!isOutputType(innerType)) { + throw new Error('A semantic non-null type must wrap an output type.'); + } + return innerType && new GraphQLSemanticNonNull(innerType); + } case Kind.NAMED_TYPE: return schema.getType(typeNode.name.value); } diff --git a/src/validation/rules/OverlappingFieldsCanBeMergedRule.ts b/src/validation/rules/OverlappingFieldsCanBeMergedRule.ts index 8397a35b80..182215fd3f 100644 --- a/src/validation/rules/OverlappingFieldsCanBeMergedRule.ts +++ b/src/validation/rules/OverlappingFieldsCanBeMergedRule.ts @@ -27,6 +27,7 @@ import { isListType, isNonNullType, isObjectType, + isSemanticNonNullType, } from '../../type/definition'; import { sortValueNode } from '../../utilities/sortValueNode'; @@ -723,6 +724,14 @@ function doTypesConflict( if (isNonNullType(type2)) { return true; } + if (isSemanticNonNullType(type1)) { + return isSemanticNonNullType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if (isSemanticNonNullType(type2)) { + return true; + } if (isLeafType(type1) || isLeafType(type2)) { return type1 !== type2; } diff --git a/src/validation/rules/ValuesOfCorrectTypeRule.ts b/src/validation/rules/ValuesOfCorrectTypeRule.ts index 3f284d7103..716135effd 100644 --- a/src/validation/rules/ValuesOfCorrectTypeRule.ts +++ b/src/validation/rules/ValuesOfCorrectTypeRule.ts @@ -118,6 +118,7 @@ export function ValuesOfCorrectTypeRule( ), ); } + // Note: SemanticNonNull cannot happen on input. }, EnumValue: (node) => isValidValueNode(context, node), IntValue: (node) => isValidValueNode(context, node), diff --git a/src/validation/rules/VariablesInAllowedPositionRule.ts b/src/validation/rules/VariablesInAllowedPositionRule.ts index a0b7e991a6..2871b49bba 100644 --- a/src/validation/rules/VariablesInAllowedPositionRule.ts +++ b/src/validation/rules/VariablesInAllowedPositionRule.ts @@ -88,6 +88,7 @@ function allowedVariableUsage( locationType: GraphQLType, locationDefaultValue: Maybe, ): boolean { + // Note: SemanticNonNull cannot occur on input. if (isNonNullType(locationType) && !isNonNullType(varType)) { const hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== Kind.NULL;