diff --git a/.changeset/red-coins-develop.md b/.changeset/red-coins-develop.md new file mode 100644 index 0000000000..a0b3b1be66 --- /dev/null +++ b/.changeset/red-coins-develop.md @@ -0,0 +1,5 @@ +--- +'graphql-yoga': minor +--- + +bring in validation rules for defer stream graphql/graphql-js#3659 diff --git a/packages/graphql-yoga/__tests__/validations/defer-stream-directive-label.spec.ts b/packages/graphql-yoga/__tests__/validations/defer-stream-directive-label.spec.ts new file mode 100644 index 0000000000..c4250bdb1f --- /dev/null +++ b/packages/graphql-yoga/__tests__/validations/defer-stream-directive-label.spec.ts @@ -0,0 +1,169 @@ +import { DeferStreamDirectiveLabelRule } from '../../src/validations/defer-stream-directive-label.js' + +import { expectValidationErrors } from './harness.js' + +function expectErrors(queryStr: string) { + return expectValidationErrors(DeferStreamDirectiveLabelRule, queryStr) +} + +function expectValid(queryStr: string) { + expectErrors(queryStr).toDeepEqual([]) +} + +describe('Validate: Defer/Stream directive on root field', () => { + it('Defer fragments with no label', () => { + expectValid(` + { + dog { + ...dogFragmentA @defer + ...dogFragmentB @defer + } + } + fragment dogFragmentA on Dog { + name + } + fragment dogFragmentB on Dog { + nickname + } + `) + }) + + it('Defer fragments, one with label, one without', () => { + expectValid(` + { + dog { + ...dogFragmentA @defer(label: "fragA") + ...dogFragmentB @defer + } + } + fragment dogFragmentA on Dog { + name + } + fragment dogFragmentB on Dog { + nickname + } + `) + }) + + it('Defer fragment with variable label', () => { + expectErrors(` + query($label: String) { + dog { + ...dogFragmentA @defer(label: $label) + ...dogFragmentB @defer(label: "fragA") + } + } + fragment dogFragmentA on Dog { + name + } + fragment dogFragmentB on Dog { + nickname + } + `).toDeepEqual([ + { + message: 'Directive "defer"\'s label argument must be a static string.', + locations: [{ line: 4, column: 25 }], + }, + ]) + }) + + it('Defer fragments with different labels', () => { + expectValid(` + { + dog { + ...dogFragmentA @defer(label: "fragB") + ...dogFragmentB @defer(label: "fragA") + } + } + fragment dogFragmentA on Dog { + name + } + fragment dogFragmentB on Dog { + nickname + } + `) + }) + it('Defer fragments with same label', () => { + expectErrors(` + { + dog { + ...dogFragmentA @defer(label: "fragA") + ...dogFragmentB @defer(label: "fragA") + } + } + fragment dogFragmentA on Dog { + name + } + fragment dogFragmentB on Dog { + nickname + } + `).toDeepEqual([ + { + message: 'Defer/Stream directive label argument must be unique.', + locations: [ + { line: 4, column: 25 }, + { line: 5, column: 25 }, + ], + }, + ]) + }) + it('Defer and stream with no label', () => { + expectValid(` + { + dog { + ...dogFragment @defer + } + pets @stream(initialCount: 0) @stream { + name + } + } + fragment dogFragment on Dog { + name + } + `) + }) + it('Stream with variable label', () => { + expectErrors(` + query ($label: String!) { + dog { + ...dogFragment @defer + } + pets @stream(initialCount: 0) @stream(label: $label) { + name + } + } + fragment dogFragment on Dog { + name + } + `).toDeepEqual([ + { + message: + 'Directive "stream"\'s label argument must be a static string.', + locations: [{ line: 6, column: 39 }], + }, + ]) + }) + it('Defer and stream with the same label', () => { + expectErrors(` + { + dog { + ...dogFragment @defer(label: "MyLabel") + } + pets @stream(initialCount: 0) @stream(label: "MyLabel") { + name + } + } + fragment dogFragment on Dog { + name + } + `).toDeepEqual([ + { + message: 'Defer/Stream directive label argument must be unique.', + locations: [ + { line: 4, column: 26 }, + { line: 6, column: 39 }, + ], + }, + ]) + }) +}) diff --git a/packages/graphql-yoga/__tests__/validations/defer-stream-directive-on-root-field.spec.ts b/packages/graphql-yoga/__tests__/validations/defer-stream-directive-on-root-field.spec.ts new file mode 100644 index 0000000000..dc09550a44 --- /dev/null +++ b/packages/graphql-yoga/__tests__/validations/defer-stream-directive-on-root-field.spec.ts @@ -0,0 +1,254 @@ +import { buildSchema } from 'graphql' +import { DeferStreamDirectiveOnRootFieldRule } from '../../src/validations/defer-stream-directive-on-root-field.js' +import { expectValidationErrorsWithSchema } from './harness.js' + +function expectErrors(queryStr: string) { + return expectValidationErrorsWithSchema( + schema, + DeferStreamDirectiveOnRootFieldRule, + queryStr, + ) +} + +function expectValid(queryStr: string) { + expectErrors(queryStr).toDeepEqual([]) +} + +const schema = buildSchema(` + type Message { + body: String + sender: String + } + + type SubscriptionRoot { + subscriptionField: Message + subscriptionListField: [Message] + } + + type MutationRoot { + mutationField: Message + mutationListField: [Message] + } + + type QueryRoot { + message: Message + messages: [Message] + } + + schema { + query: QueryRoot + mutation: MutationRoot + subscription: SubscriptionRoot + } +`) + +describe('Validate: Defer/Stream directive on root field', () => { + it('Defer fragment spread on root query field', () => { + expectValid(` + { + ...rootQueryFragment @defer + } + fragment rootQueryFragment on QueryRoot { + message { + body + } + } + `) + }) + + it('Defer inline fragment spread on root query field', () => { + expectValid(` + { + ... @defer { + message { + body + } + } + } + `) + }) + + it('Defer fragment spread on root mutation field', () => { + expectErrors(` + mutation { + ...rootFragment @defer + } + fragment rootFragment on MutationRoot { + mutationField { + body + } + } + `).toDeepEqual([ + { + message: + 'Defer directive cannot be used on root mutation type "MutationRoot".', + locations: [{ line: 3, column: 25 }], + }, + ]) + }) + it('Defer inline fragment spread on root mutation field', () => { + expectErrors(` + mutation { + ... @defer { + mutationField { + body + } + } + } + `).toDeepEqual([ + { + message: + 'Defer directive cannot be used on root mutation type "MutationRoot".', + locations: [{ line: 3, column: 13 }], + }, + ]) + }) + + it('Defer fragment spread on nested mutation field', () => { + expectValid(` + mutation { + mutationField { + ... @defer { + body + } + } + } + `) + }) + + it('Defer fragment spread on root subscription field', () => { + expectErrors(` + subscription { + ...rootFragment @defer + } + fragment rootFragment on SubscriptionRoot { + subscriptionField { + body + } + } + `).toDeepEqual([ + { + message: + 'Defer directive cannot be used on root subscription type "SubscriptionRoot".', + locations: [{ line: 3, column: 25 }], + }, + ]) + }) + it('Defer inline fragment spread on root subscription field', () => { + expectErrors(` + subscription { + ... @defer { + subscriptionField { + body + } + } + } + `).toDeepEqual([ + { + message: + 'Defer directive cannot be used on root subscription type "SubscriptionRoot".', + locations: [{ line: 3, column: 13 }], + }, + ]) + }) + + it('Defer fragment spread on nested subscription field', () => { + expectValid(` + subscription { + subscriptionField { + ...nestedFragment + } + } + fragment nestedFragment on Message { + body + } + `) + }) + it('Stream field on root query field', () => { + expectValid(` + { + messages @stream { + name + } + } + `) + }) + it('Stream field on fragment on root query field', () => { + expectValid(` + { + ...rootFragment + } + fragment rootFragment on QueryType { + messages @stream { + name + } + } + `) + }) + it('Stream field on root mutation field', () => { + expectErrors(` + mutation { + mutationListField @stream { + name + } + } + `).toDeepEqual([ + { + message: + 'Stream directive cannot be used on root mutation type "MutationRoot".', + locations: [{ line: 3, column: 27 }], + }, + ]) + }) + it('Stream field on fragment on root mutation field', () => { + expectErrors(` + mutation { + ...rootFragment + } + fragment rootFragment on MutationRoot { + mutationListField @stream { + name + } + } + `).toDeepEqual([ + { + message: + 'Stream directive cannot be used on root mutation type "MutationRoot".', + locations: [{ line: 6, column: 27 }], + }, + ]) + }) + it('Stream field on root subscription field', () => { + expectErrors(` + subscription { + subscriptionListField @stream { + name + } + } + `).toDeepEqual([ + { + message: + 'Stream directive cannot be used on root subscription type "SubscriptionRoot".', + locations: [{ line: 3, column: 31 }], + }, + ]) + }) + it('Stream field on fragment on root subscription field', () => { + expectErrors(` + subscription { + ...rootFragment + } + fragment rootFragment on SubscriptionRoot { + subscriptionListField @stream { + name + } + } + `).toDeepEqual([ + { + message: + 'Stream directive cannot be used on root subscription type "SubscriptionRoot".', + locations: [{ line: 6, column: 31 }], + }, + ]) + }) +}) diff --git a/packages/graphql-yoga/__tests__/validations/harness.ts b/packages/graphql-yoga/__tests__/validations/harness.ts new file mode 100644 index 0000000000..f5b6305d10 --- /dev/null +++ b/packages/graphql-yoga/__tests__/validations/harness.ts @@ -0,0 +1,205 @@ +import { + parse, + GraphQLSchema, + buildSchema, + validate, + ValidationRule, +} from 'graphql' +import { Maybe } from 'graphql/jsutils/Maybe' +import { validateSDL } from 'graphql/validation/validate' +import { SDLValidationRule } from 'graphql/validation/ValidationContext' +import { isObjectLike } from 'graphql/jsutils/isObjectLike' + +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + */ +function mapValue( + map: Record, + fn: (value: T, key: string) => V, +): Record { + const result = Object.create(null) + + for (const key of Object.keys(map)) { + result[key] = fn(map[key], key) + } + return result +} + +/** + * Deeply transforms an arbitrary value to a JSON-safe value by calling toJSON + * on any nested value which defines it. + */ +function toJSONDeep(value: unknown): unknown { + if (!isObjectLike(value)) { + return value + } + + if (typeof value.toJSON === 'function') { + return value.toJSON() + } + + if (Array.isArray(value)) { + return value.map(toJSONDeep) + } + + return mapValue(value, toJSONDeep) +} + +export function expectJSON(actual: unknown) { + const actualJSON = toJSONDeep(actual) + + return { + toDeepEqual(expected: unknown) { + const expectedJSON = toJSONDeep(expected) + expect(actualJSON).toMatchObject(expectedJSON as any) + }, + toDeepNestedProperty(path: string, expected: unknown) { + const expectedJSON = toJSONDeep(expected) + expect(actualJSON).toHaveProperty(path, expectedJSON) + }, + } +} + +export function expectToThrowJSON(fn: () => unknown) { + function mapException(): unknown { + try { + return fn() + } catch (error) { + return error + } + } + + return expect(mapException()) +} + +export const testSchema: GraphQLSchema = buildSchema(` + interface Mammal { + mother: Mammal + father: Mammal + } + + interface Pet { + name(surname: Boolean): String + } + + interface Canine implements Mammal { + name(surname: Boolean): String + mother: Canine + father: Canine + } + + enum DogCommand { + SIT + HEEL + DOWN + } + + type Dog implements Pet & Mammal & Canine { + name(surname: Boolean): String + nickname: String + barkVolume: Int + barks: Boolean + doesKnowCommand(dogCommand: DogCommand): Boolean + isHouseTrained(atOtherHomes: Boolean = true): Boolean + isAtLocation(x: Int, y: Int): Boolean + mother: Dog + father: Dog + } + + type Cat implements Pet { + name(surname: Boolean): String + nickname: String + meows: Boolean + meowsVolume: Int + furColor: FurColor + } + + union CatOrDog = Cat | Dog + + type Human { + name(surname: Boolean): String + pets: [Pet] + relatives: [Human]! + } + + enum FurColor { + BROWN + BLACK + TAN + SPOTTED + NO_FUR + UNKNOWN + } + + input ComplexInput { + requiredField: Boolean! + nonNullField: Boolean! = false + intField: Int + stringField: String + booleanField: Boolean + stringListField: [String] + } + + type ComplicatedArgs { + # TODO List + # TODO Coercion + # TODO NotNulls + intArgField(intArg: Int): String + nonNullIntArgField(nonNullIntArg: Int!): String + stringArgField(stringArg: String): String + booleanArgField(booleanArg: Boolean): String + enumArgField(enumArg: FurColor): String + floatArgField(floatArg: Float): String + idArgField(idArg: ID): String + stringListArgField(stringListArg: [String]): String + stringListNonNullArgField(stringListNonNullArg: [String!]): String + complexArgField(complexArg: ComplexInput): String + multipleReqs(req1: Int!, req2: Int!): String + nonNullFieldWithDefault(arg: Int! = 0): String + multipleOpts(opt1: Int = 0, opt2: Int = 0): String + multipleOptAndReq(req1: Int!, req2: Int!, opt1: Int = 0, opt2: Int = 0): String + } + + type QueryRoot { + human(id: ID): Human + dog: Dog + cat: Cat + pet: Pet + catOrDog: CatOrDog + complicatedArgs: ComplicatedArgs + } + + schema { + query: QueryRoot + } + + directive @onField on FIELD +`) + +export function expectValidationErrorsWithSchema( + schema: GraphQLSchema, + rule: ValidationRule, + queryStr: string, +): any { + const doc = parse(queryStr) + const errors = validate(schema, doc, [rule]) + return expectJSON(errors) +} + +export function expectValidationErrors( + rule: ValidationRule, + queryStr: string, +): any { + return expectValidationErrorsWithSchema(testSchema, rule, queryStr) +} + +export function expectSDLValidationErrors( + schema: Maybe, + rule: SDLValidationRule, + sdlStr: string, +): any { + const doc = parse(sdlStr) + const errors = validateSDL(doc, schema, [rule]) + return expectJSON(errors) +} diff --git a/packages/graphql-yoga/__tests__/validations/overlapping-fields-can-be-merged.spec.ts b/packages/graphql-yoga/__tests__/validations/overlapping-fields-can-be-merged.spec.ts new file mode 100644 index 0000000000..a4d6b040ba --- /dev/null +++ b/packages/graphql-yoga/__tests__/validations/overlapping-fields-can-be-merged.spec.ts @@ -0,0 +1,1243 @@ +import { buildSchema, GraphQLSchema } from 'graphql' +import { OverlappingFieldsCanBeMergedRule } from '../../src/validations/overlapping-fields-can-be-merged.js' +import { + expectValidationErrors, + expectValidationErrorsWithSchema, +} from './harness.js' + +function expectErrors(queryStr: string) { + return expectValidationErrors(OverlappingFieldsCanBeMergedRule, queryStr) +} + +function expectValid(queryStr: string) { + expectErrors(queryStr).toDeepEqual([]) +} + +function expectErrorsWithSchema(schema: GraphQLSchema, queryStr: string) { + return expectValidationErrorsWithSchema( + schema, + OverlappingFieldsCanBeMergedRule, + queryStr, + ) +} + +function expectValidWithSchema(schema: GraphQLSchema, queryStr: string) { + expectErrorsWithSchema(schema, queryStr).toDeepEqual([]) +} + +describe('Validate: Overlapping fields can be merged', () => { + it('unique fields', () => { + expectValid(` + fragment uniqueFields on Dog { + name + nickname + } + `) + }) + + it('identical fields', () => { + expectValid(` + fragment mergeIdenticalFields on Dog { + name + name + } + `) + }) + + it('identical fields with identical args', () => { + expectValid(` + fragment mergeIdenticalFieldsWithIdenticalArgs on Dog { + doesKnowCommand(dogCommand: SIT) + doesKnowCommand(dogCommand: SIT) + } + `) + }) + + it('identical fields with identical directives', () => { + expectValid(` + fragment mergeSameFieldsWithSameDirectives on Dog { + name @include(if: true) + name @include(if: true) + } + `) + }) + + it('different args with different aliases', () => { + expectValid(` + fragment differentArgsWithDifferentAliases on Dog { + knowsSit: doesKnowCommand(dogCommand: SIT) + knowsDown: doesKnowCommand(dogCommand: DOWN) + } + `) + }) + + it('different directives with different aliases', () => { + expectValid(` + fragment differentDirectivesWithDifferentAliases on Dog { + nameIfTrue: name @include(if: true) + nameIfFalse: name @include(if: false) + } + `) + }) + + it('different skip/include directives accepted', () => { + // Note: Differing skip/include directives don't create an ambiguous return + // value and are acceptable in conditions where differing runtime values + // may have the same desired effect of including or skipping a field. + expectValid(` + fragment differentDirectivesWithDifferentAliases on Dog { + name @include(if: true) + name @include(if: false) + } + `) + }) + + it('Same stream directives supported', () => { + expectValid(` + fragment differentDirectivesWithDifferentAliases on Dog { + name @stream(label: "streamLabel", initialCount: 1) + name @stream(label: "streamLabel", initialCount: 1) + } + `) + }) + + it('different stream directive label', () => { + expectErrors(` + fragment conflictingArgs on Dog { + name @stream(label: "streamLabel", initialCount: 1) + name @stream(label: "anotherLabel", initialCount: 1) + } + `).toDeepEqual([ + { + message: + 'Fields "name" conflict because they have differing stream directives. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('different stream directive initialCount', () => { + expectErrors(` + fragment conflictingArgs on Dog { + name @stream(label: "streamLabel", initialCount: 1) + name @stream(label: "streamLabel", initialCount: 2) + } + `).toDeepEqual([ + { + message: + 'Fields "name" conflict because they have differing stream directives. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('different stream directive first missing args', () => { + expectErrors(` + fragment conflictingArgs on Dog { + name @stream + name @stream(label: "streamLabel", initialCount: 1) + } + `).toDeepEqual([ + { + message: + 'Fields "name" conflict because they have differing stream directives. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('different stream directive second missing args', () => { + expectErrors(` + fragment conflictingArgs on Dog { + name @stream(label: "streamLabel", initialCount: 1) + name @stream + } + `).toDeepEqual([ + { + message: + 'Fields "name" conflict because they have differing stream directives. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('mix of stream and no stream', () => { + expectErrors(` + fragment conflictingArgs on Dog { + name @stream + name + } + `).toDeepEqual([ + { + message: + 'Fields "name" conflict because they have differing stream directives. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('different stream directive both missing args', () => { + expectValid(` + fragment conflictingArgs on Dog { + name @stream + name @stream + } + `) + }) + + it('Same aliases with different field targets', () => { + expectErrors(` + fragment sameAliasesWithDifferentFieldTargets on Dog { + fido: name + fido: nickname + } + `).toDeepEqual([ + { + message: + 'Fields "fido" conflict because "name" and "nickname" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('Same aliases allowed on non-overlapping fields', () => { + // This is valid since no object can be both a "Dog" and a "Cat", thus + // these fields can never overlap. + expectValid(` + fragment sameAliasesWithDifferentFieldTargets on Pet { + ... on Dog { + name + } + ... on Cat { + name: nickname + } + } + `) + }) + + it('Alias masking direct field access', () => { + expectErrors(` + fragment aliasMaskingDirectFieldAccess on Dog { + name: nickname + name + } + `).toDeepEqual([ + { + message: + 'Fields "name" conflict because "nickname" and "name" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('different args, second adds an argument', () => { + expectErrors(` + fragment conflictingArgs on Dog { + doesKnowCommand + doesKnowCommand(dogCommand: HEEL) + } + `).toDeepEqual([ + { + message: + 'Fields "doesKnowCommand" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('different args, second missing an argument', () => { + expectErrors(` + fragment conflictingArgs on Dog { + doesKnowCommand(dogCommand: SIT) + doesKnowCommand + } + `).toDeepEqual([ + { + message: + 'Fields "doesKnowCommand" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('conflicting arg values', () => { + expectErrors(` + fragment conflictingArgs on Dog { + doesKnowCommand(dogCommand: SIT) + doesKnowCommand(dogCommand: HEEL) + } + `).toDeepEqual([ + { + message: + 'Fields "doesKnowCommand" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('conflicting arg names', () => { + expectErrors(` + fragment conflictingArgs on Dog { + isAtLocation(x: 0) + isAtLocation(y: 0) + } + `).toDeepEqual([ + { + message: + 'Fields "isAtLocation" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 9 }, + ], + }, + ]) + }) + + it('allows different args where no conflict is possible', () => { + // This is valid since no object can be both a "Dog" and a "Cat", thus + // these fields can never overlap. + expectValid(` + fragment conflictingArgs on Pet { + ... on Dog { + name(surname: true) + } + ... on Cat { + name + } + } + `) + }) + + it('allows different order of args', () => { + const schema = buildSchema(` + type Query { + someField(a: String, b: String): String + } + `) + + // This is valid since arguments are unordered, see: + // https://spec.graphql.org/draft/#sec-Language.Arguments.Arguments-are-unordered + expectValidWithSchema( + schema, + ` + { + someField(a: null, b: null) + someField(b: null, a: null) + } + `, + ) + }) + + it('allows different order of input object fields in arg values', () => { + const schema = buildSchema(` + input SomeInput { + a: String + b: String + } + + type Query { + someField(arg: SomeInput): String + } + `) + + // This is valid since input object fields are unordered, see: + // https://spec.graphql.org/draft/#sec-Input-Object-Values.Input-object-fields-are-unordered + expectValidWithSchema( + schema, + ` + { + someField(arg: { a: null, b: null }) + someField(arg: { b: null, a: null }) + } + `, + ) + }) + + it('encounters conflict in fragments', () => { + expectErrors(` + { + ...A + ...B + } + fragment A on Type { + x: a + } + fragment B on Type { + x: b + } + `).toDeepEqual([ + { + message: + 'Fields "x" conflict because "a" and "b" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 7, column: 9 }, + { line: 10, column: 9 }, + ], + }, + ]) + }) + + it('reports each conflict once', () => { + expectErrors(` + { + f1 { + ...A + ...B + } + f2 { + ...B + ...A + } + f3 { + ...A + ...B + x: c + } + } + fragment A on Type { + x: a + } + fragment B on Type { + x: b + } + `).toDeepEqual([ + { + message: + 'Fields "x" conflict because "a" and "b" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 18, column: 9 }, + { line: 21, column: 9 }, + ], + }, + { + message: + 'Fields "x" conflict because "c" and "a" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 14, column: 11 }, + { line: 18, column: 9 }, + ], + }, + { + message: + 'Fields "x" conflict because "c" and "b" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 14, column: 11 }, + { line: 21, column: 9 }, + ], + }, + ]) + }) + + it('deep conflict', () => { + expectErrors(` + { + field { + x: a + }, + field { + x: b + } + } + `).toDeepEqual([ + { + message: + 'Fields "field" conflict because subfields "x" conflict because "a" and "b" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 11 }, + { line: 6, column: 9 }, + { line: 7, column: 11 }, + ], + }, + ]) + }) + + it('deep conflict with multiple issues', () => { + expectErrors(` + { + field { + x: a + y: c + }, + field { + x: b + y: d + } + } + `).toDeepEqual([ + { + message: + 'Fields "field" conflict because subfields "x" conflict because "a" and "b" are different fields and subfields "y" conflict because "c" and "d" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 11 }, + { line: 5, column: 11 }, + { line: 7, column: 9 }, + { line: 8, column: 11 }, + { line: 9, column: 11 }, + ], + }, + ]) + }) + + it('very deep conflict', () => { + expectErrors(` + { + field { + deepField { + x: a + } + }, + field { + deepField { + x: b + } + } + } + `).toDeepEqual([ + { + message: + 'Fields "field" conflict because subfields "deepField" conflict because subfields "x" conflict because "a" and "b" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 4, column: 11 }, + { line: 5, column: 13 }, + { line: 8, column: 9 }, + { line: 9, column: 11 }, + { line: 10, column: 13 }, + ], + }, + ]) + }) + + it('reports deep conflict to nearest common ancestor', () => { + expectErrors(` + { + field { + deepField { + x: a + } + deepField { + x: b + } + }, + field { + deepField { + y + } + } + } + `).toDeepEqual([ + { + message: + 'Fields "deepField" conflict because subfields "x" conflict because "a" and "b" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 4, column: 11 }, + { line: 5, column: 13 }, + { line: 7, column: 11 }, + { line: 8, column: 13 }, + ], + }, + ]) + }) + + it('reports deep conflict to nearest common ancestor in fragments', () => { + expectErrors(` + { + field { + ...F + } + field { + ...F + } + } + fragment F on T { + deepField { + deeperField { + x: a + } + deeperField { + x: b + } + }, + deepField { + deeperField { + y + } + } + } + `).toDeepEqual([ + { + message: + 'Fields "deeperField" conflict because subfields "x" conflict because "a" and "b" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 12, column: 11 }, + { line: 13, column: 13 }, + { line: 15, column: 11 }, + { line: 16, column: 13 }, + ], + }, + ]) + }) + + it('reports deep conflict in nested fragments', () => { + expectErrors(` + { + field { + ...F + } + field { + ...I + } + } + fragment F on T { + x: a + ...G + } + fragment G on T { + y: c + } + fragment I on T { + y: d + ...J + } + fragment J on T { + x: b + } + `).toDeepEqual([ + { + message: + 'Fields "field" conflict because subfields "x" conflict because "a" and "b" are different fields and subfields "y" conflict because "c" and "d" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 11, column: 9 }, + { line: 15, column: 9 }, + { line: 6, column: 9 }, + { line: 22, column: 9 }, + { line: 18, column: 9 }, + ], + }, + ]) + }) + + it('ignores unknown fragments', () => { + expectValid(` + { + field + ...Unknown + ...Known + } + + fragment Known on T { + field + ...OtherUnknown + } + `) + }) + + describe('return types must be unambiguous', () => { + const schema = buildSchema(` + interface SomeBox { + deepBox: SomeBox + unrelatedField: String + } + + type StringBox implements SomeBox { + scalar: String + deepBox: StringBox + unrelatedField: String + listStringBox: [StringBox] + stringBox: StringBox + intBox: IntBox + } + + type IntBox implements SomeBox { + scalar: Int + deepBox: IntBox + unrelatedField: String + listStringBox: [StringBox] + stringBox: StringBox + intBox: IntBox + } + + interface NonNullStringBox1 { + scalar: String! + } + + type NonNullStringBox1Impl implements SomeBox & NonNullStringBox1 { + scalar: String! + unrelatedField: String + deepBox: SomeBox + } + + interface NonNullStringBox2 { + scalar: String! + } + + type NonNullStringBox2Impl implements SomeBox & NonNullStringBox2 { + scalar: String! + unrelatedField: String + deepBox: SomeBox + } + + type Connection { + edges: [Edge] + } + + type Edge { + node: Node + } + + type Node { + id: ID + name: String + } + + type Query { + someBox: SomeBox + connection: Connection + } + `) + + it('conflicting return types which potentially overlap', () => { + // This is invalid since an object could potentially be both the Object + // type IntBox and the interface type NonNullStringBox1. While that + // condition does not exist in the current schema, the schema could + // expand in the future to allow this. Thus it is invalid. + expectErrorsWithSchema( + schema, + ` + { + someBox { + ...on IntBox { + scalar + } + ...on NonNullStringBox1 { + scalar + } + } + } + `, + ).toDeepEqual([ + { + message: + 'Fields "scalar" conflict because they return conflicting types "Int" and "String!". Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 5, column: 17 }, + { line: 8, column: 17 }, + ], + }, + ]) + }) + + it('compatible return shapes on different return types', () => { + // In this case `deepBox` returns `SomeBox` in the first usage, and + // `StringBox` in the second usage. These return types are not the same! + // however this is valid because the return *shapes* are compatible. + expectValidWithSchema( + schema, + ` + { + someBox { + ... on SomeBox { + deepBox { + unrelatedField + } + } + ... on StringBox { + deepBox { + unrelatedField + } + } + } + } + `, + ) + }) + + it('disallows differing return types despite no overlap', () => { + expectErrorsWithSchema( + schema, + ` + { + someBox { + ... on IntBox { + scalar + } + ... on StringBox { + scalar + } + } + } + `, + ).toDeepEqual([ + { + message: + 'Fields "scalar" conflict because they return conflicting types "Int" and "String". Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 5, column: 17 }, + { line: 8, column: 17 }, + ], + }, + ]) + }) + + it('reports correctly when a non-exclusive follows an exclusive', () => { + expectErrorsWithSchema( + schema, + ` + { + someBox { + ... on IntBox { + deepBox { + ...X + } + } + } + someBox { + ... on StringBox { + deepBox { + ...Y + } + } + } + memoed: someBox { + ... on IntBox { + deepBox { + ...X + } + } + } + memoed: someBox { + ... on StringBox { + deepBox { + ...Y + } + } + } + other: someBox { + ...X + } + other: someBox { + ...Y + } + } + fragment X on SomeBox { + scalar + } + fragment Y on SomeBox { + scalar: unrelatedField + } + `, + ).toDeepEqual([ + { + message: + 'Fields "other" conflict because subfields "scalar" conflict because "scalar" and "unrelatedField" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 31, column: 13 }, + { line: 39, column: 13 }, + { line: 34, column: 13 }, + { line: 42, column: 13 }, + ], + }, + ]) + }) + + it('disallows differing return type nullability despite no overlap', () => { + expectErrorsWithSchema( + schema, + ` + { + someBox { + ... on NonNullStringBox1 { + scalar + } + ... on StringBox { + scalar + } + } + } + `, + ).toDeepEqual([ + { + message: + 'Fields "scalar" conflict because they return conflicting types "String!" and "String". Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 5, column: 17 }, + { line: 8, column: 17 }, + ], + }, + ]) + }) + + it('disallows differing return type list despite no overlap', () => { + expectErrorsWithSchema( + schema, + ` + { + someBox { + ... on IntBox { + box: listStringBox { + scalar + } + } + ... on StringBox { + box: stringBox { + scalar + } + } + } + } + `, + ).toDeepEqual([ + { + message: + 'Fields "box" conflict because they return conflicting types "[StringBox]" and "StringBox". Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 5, column: 17 }, + { line: 10, column: 17 }, + ], + }, + ]) + + expectErrorsWithSchema( + schema, + ` + { + someBox { + ... on IntBox { + box: stringBox { + scalar + } + } + ... on StringBox { + box: listStringBox { + scalar + } + } + } + } + `, + ).toDeepEqual([ + { + message: + 'Fields "box" conflict because they return conflicting types "StringBox" and "[StringBox]". Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 5, column: 17 }, + { line: 10, column: 17 }, + ], + }, + ]) + }) + + it('disallows differing subfields', () => { + expectErrorsWithSchema( + schema, + ` + { + someBox { + ... on IntBox { + box: stringBox { + val: scalar + val: unrelatedField + } + } + ... on StringBox { + box: stringBox { + val: scalar + } + } + } + } + `, + ).toDeepEqual([ + { + message: + 'Fields "val" conflict because "scalar" and "unrelatedField" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 6, column: 19 }, + { line: 7, column: 19 }, + ], + }, + ]) + }) + + it('disallows differing deep return types despite no overlap', () => { + expectErrorsWithSchema( + schema, + ` + { + someBox { + ... on IntBox { + box: stringBox { + scalar + } + } + ... on StringBox { + box: intBox { + scalar + } + } + } + } + `, + ).toDeepEqual([ + { + message: + 'Fields "box" conflict because subfields "scalar" conflict because they return conflicting types "String" and "Int". Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 5, column: 17 }, + { line: 6, column: 19 }, + { line: 10, column: 17 }, + { line: 11, column: 19 }, + ], + }, + ]) + }) + + it('allows non-conflicting overlapping types', () => { + expectValidWithSchema( + schema, + ` + { + someBox { + ... on IntBox { + scalar: unrelatedField + } + ... on StringBox { + scalar + } + } + } + `, + ) + }) + + it('same wrapped scalar return types', () => { + expectValidWithSchema( + schema, + ` + { + someBox { + ...on NonNullStringBox1 { + scalar + } + ...on NonNullStringBox2 { + scalar + } + } + } + `, + ) + }) + + it('allows inline fragments without type condition', () => { + expectValidWithSchema( + schema, + ` + { + a + ... { + a + } + } + `, + ) + }) + + it('compares deep types including list', () => { + expectErrorsWithSchema( + schema, + ` + { + connection { + ...edgeID + edges { + node { + id: name + } + } + } + } + + fragment edgeID on Connection { + edges { + node { + id + } + } + } + `, + ).toDeepEqual([ + { + message: + 'Fields "edges" conflict because subfields "node" conflict because subfields "id" conflict because "name" and "id" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 5, column: 15 }, + { line: 6, column: 17 }, + { line: 7, column: 19 }, + { line: 14, column: 13 }, + { line: 15, column: 15 }, + { line: 16, column: 17 }, + ], + }, + ]) + }) + + it('ignores unknown types', () => { + expectValidWithSchema( + schema, + ` + { + someBox { + ...on UnknownType { + scalar + } + ...on NonNullStringBox2 { + scalar + } + } + } + `, + ) + }) + + it('works for field names that are JS keywords', () => { + const schemaWithKeywords = buildSchema(` + type Foo { + constructor: String + } + + type Query { + foo: Foo + } + `) + + expectValidWithSchema( + schemaWithKeywords, + ` + { + foo { + constructor + } + } + `, + ) + }) + }) + + it('does not infinite loop on recursive fragment', () => { + expectValid(` + { + ...fragA + } + + fragment fragA on Human { name, relatives { name, ...fragA } } + `) + }) + + it('does not infinite loop on immediately recursive fragment', () => { + expectValid(` + { + ...fragA + } + + fragment fragA on Human { name, ...fragA } + `) + }) + + it('does not infinite loop on recursive fragment with a field named after fragment', () => { + expectValid(` + { + ...fragA + fragA + } + + fragment fragA on Query { ...fragA } + `) + }) + + it('finds invalid cases even with field named after fragment', () => { + expectErrors(` + { + fragA + ...fragA + } + + fragment fragA on Type { + fragA: b + } + `).toDeepEqual([ + { + message: + 'Fields "fragA" conflict because "fragA" and "b" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 3, column: 9 }, + { line: 8, column: 9 }, + ], + }, + ]) + }) + + it('does not infinite loop on transitively recursive fragment', () => { + expectValid(` + { + ...fragA + fragB + } + + fragment fragA on Human { name, ...fragB } + fragment fragB on Human { name, ...fragC } + fragment fragC on Human { name, ...fragA } + `) + }) + + it('finds invalid case even with immediately recursive fragment', () => { + expectErrors(` + fragment sameAliasesWithDifferentFieldTargets on Dog { + ...sameAliasesWithDifferentFieldTargets + fido: name + fido: nickname + } + `).toDeepEqual([ + { + message: + 'Fields "fido" conflict because "name" and "nickname" are different fields. Use different aliases on the fields to fetch both if this was intentional.', + locations: [ + { line: 4, column: 9 }, + { line: 5, column: 9 }, + ], + }, + ]) + }) +}) diff --git a/packages/graphql-yoga/__tests__/validations/stream-directive-on-list-field.spec.ts b/packages/graphql-yoga/__tests__/validations/stream-directive-on-list-field.spec.ts new file mode 100644 index 0000000000..517cc56742 --- /dev/null +++ b/packages/graphql-yoga/__tests__/validations/stream-directive-on-list-field.spec.ts @@ -0,0 +1,76 @@ +import { StreamDirectiveOnListFieldRule } from '../../src/validations/stream-directive-on-list-field.js' +import { expectValidationErrors } from './harness.js' + +function expectErrors(queryStr: string) { + return expectValidationErrors(StreamDirectiveOnListFieldRule, queryStr) +} + +function expectValid(queryStr: string) { + expectErrors(queryStr).toDeepEqual([]) +} + +describe('Validate: Stream directive on list field', () => { + it('Stream on list field', () => { + expectValid(` + fragment objectFieldSelection on Human { + pets @stream(initialCount: 0) { + name + } + } + `) + }) + + it('Stream on non-null list field', () => { + expectValid(` + fragment objectFieldSelection on Human { + relatives @stream(initialCount: 0) { + name + } + } + `) + }) + + it("Doesn't validate other directives on list fields", () => { + expectValid(` + fragment objectFieldSelection on Human { + pets @include(if: true) { + name + } + } + `) + }) + + it("Doesn't validate other directives on non-list fields", () => { + expectValid(` + fragment objectFieldSelection on Human { + pets { + name @include(if: true) + } + } + `) + }) + + it("Doesn't validate misplaced stream directives", () => { + expectValid(` + fragment objectFieldSelection on Human { + ... @stream(initialCount: 0) { + name + } + } + `) + }) + + it('reports errors when stream is used on non-list field', () => { + expectErrors(` + fragment objectFieldSelection on Human { + name @stream(initialCount: 0) + } + `).toDeepEqual([ + { + message: + 'Stream directive cannot be used on non-list field "name" on type "Human".', + locations: [{ line: 3, column: 14 }], + }, + ]) + }) +}) diff --git a/packages/graphql-yoga/src/directives/defer.ts b/packages/graphql-yoga/src/directives/defer.ts new file mode 100644 index 0000000000..520a24133a --- /dev/null +++ b/packages/graphql-yoga/src/directives/defer.ts @@ -0,0 +1,28 @@ +import { + DirectiveLocation, + GraphQLBoolean, + GraphQLDirective, + GraphQLNonNull, + GraphQLString, +} from 'graphql' + +export const GraphQLDeferDirective = new GraphQLDirective({ + name: 'defer', + description: + 'Directs the executor to defer this fragment when the `if` argument is true or undefined.', + locations: [ + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new GraphQLNonNull(GraphQLBoolean), + description: 'Deferred when true or undefined.', + defaultValue: true, + }, + label: { + type: GraphQLString, + description: 'Unique name', + }, + }, +}) diff --git a/packages/graphql-yoga/src/directives/stream.ts b/packages/graphql-yoga/src/directives/stream.ts new file mode 100644 index 0000000000..5e1fd3d9c1 --- /dev/null +++ b/packages/graphql-yoga/src/directives/stream.ts @@ -0,0 +1,31 @@ +import { + DirectiveLocation, + GraphQLBoolean, + GraphQLDirective, + GraphQLInt, + GraphQLNonNull, + GraphQLString, +} from 'graphql' + +export const GraphQLStreamDirective = new GraphQLDirective({ + name: 'stream', + description: + 'Directs the executor to stream plural fields when the `if` argument is true or undefined.', + locations: [DirectiveLocation.FIELD], + args: { + if: { + type: new GraphQLNonNull(GraphQLBoolean), + description: 'Stream when true or undefined.', + defaultValue: true, + }, + label: { + type: GraphQLString, + description: 'Unique name', + }, + initialCount: { + defaultValue: 0, + type: GraphQLInt, + description: 'Number of items to return immediately', + }, + }, +}) diff --git a/packages/graphql-yoga/src/server.ts b/packages/graphql-yoga/src/server.ts index f78eaf0cc1..bad8701a17 100644 --- a/packages/graphql-yoga/src/server.ts +++ b/packages/graphql-yoga/src/server.ts @@ -80,6 +80,10 @@ import { useUnhandledRoute } from './plugins/useUnhandledRoute.js' import { yogaDefaultFormatError } from './utils/yoga-default-format-error.js' import { useSchema, YogaSchemaDefinition } from './plugins/useSchema.js' import { useLimitBatching } from './plugins/requestValidation/useLimitBatching.js' +import { OverlappingFieldsCanBeMergedRule } from './validations/overlapping-fields-can-be-merged.js' +import { DeferStreamDirectiveOnRootFieldRule } from './validations/defer-stream-directive-on-root-field.js' +import { DeferStreamDirectiveLabelRule } from './validations/defer-stream-directive-label.js' +import { StreamDirectiveOnListFieldRule } from './validations/stream-directive-on-list-field.js' /** * Configuration options for the server @@ -280,7 +284,16 @@ export class YogaServer< validate, execute: normalizedExecutor, subscribe: normalizedExecutor, - specifiedRules, + specifiedRules: [ + ...specifiedRules.filter( + // We do not want to use the default one cause it does not account for `@defer` and `@stream` + ({ name }) => !['OverlappingFieldsCanBeMergedRule'].includes(name), + ), + OverlappingFieldsCanBeMergedRule, + DeferStreamDirectiveOnRootFieldRule, + DeferStreamDirectiveLabelRule, + StreamDirectiveOnListFieldRule, + ], }), // Use the schema provided by the user !!options?.schema && useSchema(options.schema), diff --git a/packages/graphql-yoga/src/validations/defer-stream-directive-label.ts b/packages/graphql-yoga/src/validations/defer-stream-directive-label.ts new file mode 100644 index 0000000000..025accc7d9 --- /dev/null +++ b/packages/graphql-yoga/src/validations/defer-stream-directive-label.ts @@ -0,0 +1,47 @@ +import { GraphQLError, Kind, ASTVisitor, ValidationContext } from 'graphql' +import { GraphQLDeferDirective } from '../directives/defer.js' +import { GraphQLStreamDirective } from '../directives/stream.js' + +/** + * Stream directive on list field + * + * A GraphQL document is only valid if defer and stream directives' label argument is static and unique. + */ +export function DeferStreamDirectiveLabelRule( + context: ValidationContext, +): ASTVisitor { + const knownLabels = Object.create(null) + return { + Directive(node) { + if ( + node.name.value === GraphQLDeferDirective.name || + node.name.value === GraphQLStreamDirective.name + ) { + const labelArgument = node.arguments?.find( + (arg) => arg.name.value === 'label', + ) + const labelValue = labelArgument?.value + if (!labelValue) { + return + } + if (labelValue.kind !== Kind.STRING) { + context.reportError( + new GraphQLError( + `Directive "${node.name.value}"'s label argument must be a static string.`, + { nodes: node }, + ), + ) + } else if (knownLabels[labelValue.value]) { + context.reportError( + new GraphQLError( + 'Defer/Stream directive label argument must be unique.', + { nodes: [knownLabels[labelValue.value], node] }, + ), + ) + } else { + knownLabels[labelValue.value] = node + } + } + }, + } +} diff --git a/packages/graphql-yoga/src/validations/defer-stream-directive-on-root-field.ts b/packages/graphql-yoga/src/validations/defer-stream-directive-on-root-field.ts new file mode 100644 index 0000000000..f4115c7381 --- /dev/null +++ b/packages/graphql-yoga/src/validations/defer-stream-directive-on-root-field.ts @@ -0,0 +1,56 @@ +import { GraphQLError, ASTVisitor, ValidationContext } from 'graphql' +import { GraphQLDeferDirective } from '../directives/defer.js' +import { GraphQLStreamDirective } from '../directives/stream.js' + +/** + * Stream directive on list field + * + * A GraphQL document is only valid if defer directives are not used on root mutation or subscription types. + */ +export function DeferStreamDirectiveOnRootFieldRule( + context: ValidationContext, +): ASTVisitor { + return { + Directive(node) { + const mutationType = context.getSchema().getMutationType() + const subscriptionType = context.getSchema().getSubscriptionType() + const parentType = context.getParentType() + if (parentType && node.name.value === GraphQLDeferDirective.name) { + if (mutationType && parentType === mutationType) { + context.reportError( + new GraphQLError( + `Defer directive cannot be used on root mutation type "${parentType.name}".`, + { nodes: node }, + ), + ) + } + if (subscriptionType && parentType === subscriptionType) { + context.reportError( + new GraphQLError( + `Defer directive cannot be used on root subscription type "${parentType.name}".`, + { nodes: node }, + ), + ) + } + } + if (parentType && node.name.value === GraphQLStreamDirective.name) { + if (mutationType && parentType === mutationType) { + context.reportError( + new GraphQLError( + `Stream directive cannot be used on root mutation type "${parentType.name}".`, + { nodes: node }, + ), + ) + } + if (subscriptionType && parentType === subscriptionType) { + context.reportError( + new GraphQLError( + `Stream directive cannot be used on root subscription type "${parentType.name}".`, + { nodes: node }, + ), + ) + } + } + }, + } +} diff --git a/packages/graphql-yoga/src/validations/overlapping-fields-can-be-merged.ts b/packages/graphql-yoga/src/validations/overlapping-fields-can-be-merged.ts new file mode 100644 index 0000000000..e86f966fff --- /dev/null +++ b/packages/graphql-yoga/src/validations/overlapping-fields-can-be-merged.ts @@ -0,0 +1,849 @@ +import { + GraphQLError, + DirectiveNode, + FieldNode, + FragmentDefinitionNode, + ObjectValueNode, + SelectionSetNode, + Kind, + print, + ASTVisitor, + GraphQLField, + GraphQLNamedType, + GraphQLOutputType, + getNamedType, + isInterfaceType, + isLeafType, + isListType, + isNonNullType, + isObjectType, + typeFromAST, + ValidationContext, +} from 'graphql' +import { inspect } from 'graphql/jsutils/inspect.js' +import type { Maybe } from 'graphql/jsutils/Maybe.js' +import type { ObjMap } from 'graphql/jsutils/ObjMap.js' +import { sortValueNode } from 'graphql/utilities/sortValueNode.js' + +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. + * + * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging + */ +export function OverlappingFieldsCanBeMergedRule( + 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) { + const reasonMsg = reasonMessage(reason) + context.reportError( + new GraphQLError( + `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, + { nodes: fields1.concat(fields2) }, + ), + ) + } + }, + } +} + +type Conflict = [ConflictReason, Array, Array] +// Field name and reason. +type ConflictReason = [string, ConflictReasonMessage] +// Reason is a string, or a nested list of conflicts. +type ConflictReasonMessage = string | Array +// Tuple defining a field node in a context. +type NodeAndDef = [ + Maybe, + FieldNode, + Maybe>, +] +// Map of array of those. +type NodeAndDefCollection = ObjMap> +type FragmentNames = ReadonlyArray +type FieldsAndFragmentNames = readonly [NodeAndDefCollection, FragmentNames] + +/** + * 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: Map, + comparedFragmentPairs: PairSet, + parentType: Maybe, + selectionSet: SelectionSetNode, +): Array { + const conflicts: Array = [] + + 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. + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, + fieldMap, + fragmentNames[i], + ) + // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + for (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, + cachedFieldsAndFragmentNames: Map, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + fieldMap: NodeAndDefCollection, + fragmentName: string, +): void { + const fragment = context.getFragment(fragmentName) + if (!fragment) { + return + } + + const [fieldMap2, referencedFragmentNames] = + 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 (const referencedFragmentName of referencedFragmentNames) { + // Memoize so two fragments are not compared for conflicts more than once. + if ( + comparedFragmentPairs.has( + referencedFragmentName, + fragmentName, + areMutuallyExclusive, + ) + ) { + continue + } + comparedFragmentPairs.add( + referencedFragmentName, + fragmentName, + areMutuallyExclusive, + ) + + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + referencedFragmentName, + ) + } +} + +// Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. +function collectConflictsBetweenFragments( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames: Map, + 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, referencedFragmentNames1] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment1, + ) + const [fieldMap2, referencedFragmentNames2] = + 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 (const referencedFragmentName2 of referencedFragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + referencedFragmentName2, + ) + } + + // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + for (const referencedFragmentName1 of referencedFragmentNames1) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + referencedFragmentName1, + 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: Map, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + parentType1: Maybe, + selectionSet1: SelectionSetNode, + parentType2: Maybe, + selectionSet2: SelectionSetNode, +): Array { + const conflicts: Array = [] + + 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. + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fragmentName2, + ) + } + + // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + for (const fragmentName1 of fragmentNames1) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap2, + fragmentName1, + ) + } + + // (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 (const fragmentName1 of fragmentNames1) { + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2, + ) + } + } + return conflicts +} + +// Collect all Conflicts "within" one collection of fields. +function collectConflictsWithin( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames: Map, + 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 Object.entries(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, + cachedFieldsAndFragmentNames: Map, + 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, fields1] of Object.entries(fieldMap1)) { + const fields2 = fieldMap2[responseName] + if (fields2) { + for (const field1 of fields1) { + for (const field2 of fields2) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2, + ) + 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: Map, + comparedFragmentPairs: PairSet, + parentFieldsAreMutuallyExclusive: boolean, + responseName: string, + field1: NodeAndDef, + field2: NodeAndDef, +): Maybe { + 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)) + + 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 (stringifyArguments(node1) !== stringifyArguments(node2)) { + return [[responseName, 'they have differing arguments'], [node1], [node2]] + } + } + + // FIXME https://github.com/graphql/graphql-js/issues/2203 + const directives1 = /* c8 ignore next */ node1.directives ?? [] + const directives2 = /* c8 ignore next */ node2.directives ?? [] + if (!sameStreams(directives1, directives2)) { + return [ + [responseName, 'they have differing stream directives'], + [node1], + [node2], + ] + } + + // The return type for each field. + const type1 = def1?.type + const type2 = def2?.type + + 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) + } + return +} + +function stringifyArguments(fieldNode: FieldNode | DirectiveNode): string { + // FIXME https://github.com/graphql/graphql-js/issues/2203 + const args = /* c8 ignore next */ fieldNode.arguments ?? [] + + const inputObjectWithArgs: ObjectValueNode = { + kind: Kind.OBJECT, + fields: args.map((argNode) => ({ + kind: Kind.OBJECT_FIELD, + name: argNode.name, + value: argNode.value, + })), + } + return print(sortValueNode(inputObjectWithArgs)) +} + +function getStreamDirective( + directives: ReadonlyArray, +): DirectiveNode | undefined { + return directives.find((directive) => directive.name.value === 'stream') +} + +function sameStreams( + directives1: ReadonlyArray, + directives2: ReadonlyArray, +): boolean { + const stream1 = getStreamDirective(directives1) + const stream2 = getStreamDirective(directives2) + if (!stream1 && !stream2) { + // both fields do not have streams + return true + } + if (stream1 && stream2) { + // check if both fields have equivalent streams + return stringifyArguments(stream1) === stringifyArguments(stream2) + } + // fields have a mix of stream and no stream + return false +} + +// 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: Map, + parentType: Maybe, + selectionSet: SelectionSetNode, +): FieldsAndFragmentNames { + const cached = cachedFieldsAndFragmentNames.get(selectionSet) + if (cached) { + return cached + } + const nodeAndDefs: NodeAndDefCollection = Object.create(null) + const fragmentNames = new Set() + _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, + ) + const result = [nodeAndDefs, [...fragmentNames]] as const + cachedFieldsAndFragmentNames.set(selectionSet, result) + return result +} + +// 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: Map, + 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: Maybe, + selectionSet: SelectionSetNode, + nodeAndDefs: NodeAndDefCollection, + fragmentNames: Set, +): 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.add(selection.name.value) + 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, + responseName: string, + node1: FieldNode, + node2: FieldNode, +): Maybe { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + [node1, ...conflicts.map(([, fields1]) => fields1).flat()], + [node2, ...conflicts.map(([, , fields2]) => fields2).flat()], + ] + } + return +} + +/** + * A way to keep track of pairs of things when the ordering of the pair does not matter. + */ +class PairSet { + _data: Map> + + constructor() { + this._data = new Map() + } + + has(a: string, b: string, areMutuallyExclusive: boolean): boolean { + const [key1, key2] = a < b ? [a, b] : [b, a] + + const result = this._data.get(key1)?.get(key2) + 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. + return areMutuallyExclusive ? true : areMutuallyExclusive === result + } + + add(a: string, b: string, areMutuallyExclusive: boolean): void { + const [key1, key2] = a < b ? [a, b] : [b, a] + + const map = this._data.get(key1) + if (map === undefined) { + this._data.set(key1, new Map([[key2, areMutuallyExclusive]])) + } else { + map.set(key2, areMutuallyExclusive) + } + } +} diff --git a/packages/graphql-yoga/src/validations/stream-directive-on-list-field.ts b/packages/graphql-yoga/src/validations/stream-directive-on-list-field.ts new file mode 100644 index 0000000000..f3679e32a9 --- /dev/null +++ b/packages/graphql-yoga/src/validations/stream-directive-on-list-field.ts @@ -0,0 +1,41 @@ +import { + ValidationContext, + isListType, + isWrappingType, + DirectiveNode, + ASTVisitor, + GraphQLError, +} from 'graphql' +import { GraphQLStreamDirective } from '../directives/stream.js' + +/** + * Stream directive on list field + * + * A GraphQL document is only valid if stream directives are used on list fields. + */ +export function StreamDirectiveOnListFieldRule( + context: ValidationContext, +): ASTVisitor { + return { + Directive(node: DirectiveNode) { + const fieldDef = context.getFieldDef() + const parentType = context.getParentType() + if ( + fieldDef && + parentType && + node.name.value === GraphQLStreamDirective.name && + !( + isListType(fieldDef.type) || + (isWrappingType(fieldDef.type) && isListType(fieldDef.type.ofType)) + ) + ) { + context.reportError( + new GraphQLError( + `Stream directive cannot be used on non-list field "${fieldDef.name}" on type "${parentType.name}".`, + { nodes: node }, + ), + ) + } + }, + } +}