From c2fb7b912a9c8427397389f96794e245ceb874c9 Mon Sep 17 00:00:00 2001 From: dariuszkuc <9501705+dariuszkuc@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:13:53 -0600 Subject: [PATCH 1/5] fix: align @link handling with composition - Honour `@link(as: ...)` on the federation link: elements that aren't imported are namespaced under the alias instead of `federation__`. - Follow the link spec's own `@link(url: ".../link/v1.0", import: [...])` for `Import` / `Purpose` instead of always using `link__Import` / `link__Purpose`, and reject imports it doesn't define. - Reject a trailing slash after the version in `@link` URLs, as composition does. - Share `@link` parsing (`linksTo`, `parseVersion`, `specLink`) so other specifications can reuse it; `UnsupportedLinkImportError.unknownName` now takes the specification description instead of a version. Co-Authored-By: Claude Opus 5.5 --- .changeset/link-handling-fixes.md | 9 ++ src/__tests__/buildSubgraphSchema.test.ts | 78 +++++++++++++++ src/buildSubgraphSchema.ts | 8 +- src/errors.ts | 5 +- src/link.ts | 114 +++++++++++++++++----- src/specs.ts | 6 +- 6 files changed, 187 insertions(+), 33 deletions(-) create mode 100644 .changeset/link-handling-fixes.md diff --git a/.changeset/link-handling-fixes.md b/.changeset/link-handling-fixes.md new file mode 100644 index 0000000..68c5dff --- /dev/null +++ b/.changeset/link-handling-fixes.md @@ -0,0 +1,9 @@ +--- +'@apollo/subgraph': patch +--- + +Align `@link` handling with composition: + +- `@link(as: ...)` is now honoured for the federation link, so elements that aren't imported are namespaced under the alias instead of `federation__`. +- `@link(url: "https://specs.apollo.dev/link/v1.0", import: [...])` now names `Import` and `Purpose` after its imports instead of always using `link__Import` / `link__Purpose`. +- A `@link` URL with a trailing slash after the version (`.../federation/v2.9/`) is now rejected, matching composition. diff --git a/src/__tests__/buildSubgraphSchema.test.ts b/src/__tests__/buildSubgraphSchema.test.ts index 046ae7c..eae79ff 100644 --- a/src/__tests__/buildSubgraphSchema.test.ts +++ b/src/__tests__/buildSubgraphSchema.test.ts @@ -341,6 +341,14 @@ describe('@link', () => { ).toThrow(UnsupportedFederationVersionError); }); + it('rejects a federation @link url with a trailing slash', () => { + expect(() => + buildSubgraphSchema( + parse(`${fed2('v2.9/')} type Query { hello: String }`), + ), + ).toThrow(UnsupportedFederationVersionError); + }); + it('rejects an import the linked version does not define', () => { expect(() => buildSubgraphSchema( @@ -363,6 +371,76 @@ describe('@link', () => { ).toThrow(MultipleFederationLinksError); }); + it('namespaces federation definitions under the @link alias', () => { + const schema = buildSubgraphSchema( + parse(` + extend schema @link(url: "https://specs.apollo.dev/federation/v2.9", as: "fed") + type Product @fed__key(fields: "id") { id: ID! } + `), + ); + + expect(schema.getDirective('fed__key')).toBeDefined(); + expect(schema.getDirective('federation__key')).toBeUndefined(); + expect(schema.getType('fed__FieldSet')).toBeDefined(); + expect( + (schema.getType('_Entity') as GraphQLUnionType).getTypes(), + ).toHaveLength(1); + }); + + it('names link specification types after the link spec imports', () => { + const schema = buildSubgraphSchema( + parse(` + schema @link(url: "https://specs.apollo.dev/link/v1.0", import: ["Import", { name: "Purpose", as: "LinkPurpose" }]) { + query: Query + } + extend schema @link(url: "https://specs.apollo.dev/federation/v2.9", import: ["@key"]) + type Query { hello: String } + `), + ); + + expect(schema.getType('Import')).toBeDefined(); + expect(schema.getType('LinkPurpose')).toBeDefined(); + expect(schema.getType('link__Import')).toBeUndefined(); + expect(schema.getType('link__Purpose')).toBeUndefined(); + expect( + schema + .getDirective('link')! + .args.map((arg) => `${arg.name}: ${arg.type}`), + ).toEqual([ + 'url: String', + 'as: String', + 'for: LinkPurpose', + 'import: [Import]', + ]); + }); + + it('namespaces link specification types that are not imported', () => { + const schema = buildSubgraphSchema( + parse(` + schema @link(url: "https://specs.apollo.dev/link/v1.0") { query: Query } + extend schema @link(url: "https://specs.apollo.dev/federation/v2.9", import: ["@key"]) + type Query { hello: String } + `), + ); + + expect(schema.getType('link__Import')).toBeDefined(); + expect(schema.getType('link__Purpose')).toBeDefined(); + }); + + it('rejects an import the link specification does not define', () => { + expect(() => + buildSubgraphSchema( + parse(` + schema @link(url: "https://specs.apollo.dev/link/v1.0", import: ["FieldSet"]) { query: Query } + extend schema @link(url: "https://specs.apollo.dev/federation/v2.9") + type Query { hello: String } + `), + ), + ).toThrow( + 'Cannot import "FieldSet": it is not part of the link specification v1.0.', + ); + }); + it('defines @link for a schema that only links a custom specification', () => { const schema = buildSubgraphSchema( parse(` diff --git a/src/buildSubgraphSchema.ts b/src/buildSubgraphSchema.ts index fe323a4..6902947 100644 --- a/src/buildSubgraphSchema.ts +++ b/src/buildSubgraphSchema.ts @@ -17,10 +17,10 @@ import { } from 'graphql'; import { GraphQLSchemaValidationError } from './errors'; import { - FEDERATION_NAMESPACE, LINK_NAMESPACE, applyLinkNaming, findFederationLink, + findLinkSpecImports, hasLinkDirective, linkedDirectiveName, } from './link'; @@ -313,13 +313,13 @@ function buildSubgraph(inputDocument: DocumentNode): Subgraph { if (link) { const linkSpec = applyLinkNaming( linkSpecDocument(), - new Map([['@link', '@link']]), + findLinkSpecImports(userDocument), LINK_NAMESPACE, ); const federationSpec = applyLinkNaming( federationSpecDocument(link.version), link.imports, - FEDERATION_NAMESPACE, + link.namespace, ); specDefinitions.push( ...linkSpec.definitions, @@ -346,7 +346,7 @@ function buildSubgraph(inputDocument: DocumentNode): Subgraph { }); const keyDirectiveName = link - ? linkedDirectiveName(link.imports, FEDERATION_NAMESPACE, 'key') + ? linkedDirectiveName(link.imports, link.namespace, 'key') : 'key'; const synthesizedDefinitions = synthesizeMissingDefinitions(userDocument); diff --git a/src/errors.ts b/src/errors.ts index 80b19da..32bd64b 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -42,12 +42,13 @@ export class UnsupportedLinkImportError extends FederationError { super(message); } + /** `specification` names what was linked, e.g. `federation specification v2.5`. */ static unknownName( name: string, - version: string, + specification: string, ): UnsupportedLinkImportError { return new UnsupportedLinkImportError( - `Cannot import "${name}": it is not part of the federation specification ${version}.`, + `Cannot import "${name}": it is not part of the ${specification}.`, ); } diff --git a/src/link.ts b/src/link.ts index cdd6f31..41d783f 100644 --- a/src/link.ts +++ b/src/link.ts @@ -19,7 +19,10 @@ import { import { FEDERATION_SPEC_IDENTITY, LATEST_FEDERATION_VERSION, + LINK_SPEC_IDENTITY, SpecVersion, + federationSpecDocument, + linkSpecDocument, importableNames, printVersion, versionCode, @@ -30,9 +33,15 @@ const LINK_DIRECTIVE_NAME = 'link'; export const FEDERATION_NAMESPACE = 'federation'; export const LINK_NAMESPACE = 'link'; -export interface FederationLink { +/** A schema's `@link` to one of the specifications this library knows. */ +export interface SpecLink { url: string; version: SpecVersion; + /** + * Prefix given to elements that are not explicitly imported: the `as` + * argument of the `@link`, or the specification's own name. + */ + namespace: string; /** * Maps a canonical specification name to the name it takes in this schema. * Directives are keyed with their leading `@`, as they are written in `import`. @@ -43,6 +52,8 @@ export interface FederationLink { node: ConstDirectiveNode; } +export type FederationLink = SpecLink; + function schemaLevelDirectives(document: DocumentNode): ConstDirectiveNode[] { const directives: ConstDirectiveNode[] = []; for (const definition of document.definitions) { @@ -73,6 +84,43 @@ export function hasLinkDirective(document: DocumentNode): boolean { ); } +/** Every schema-level `@link` whose `url` points at the specification `identity`. */ +function linksTo( + document: DocumentNode, + identity: string, +): ConstDirectiveNode[] { + return schemaLevelDirectives(document).filter((directive) => { + if (directive.name.value !== LINK_DIRECTIVE_NAME) return false; + const url = stringArgument(directive, 'url'); + return url !== undefined && url.startsWith(`${identity}/`); + }); +} + +/** Reads the `vX.Y` suffix of a specification URL. */ +function parseVersion(url: string): SpecVersion | null { + const match = /\/v(\d+)\.(\d+)$/.exec(url); + if (!match) return null; + return { major: Number(match[1]), minor: Number(match[2]) }; +} + +function specLink( + node: ConstDirectiveNode, + version: SpecVersion, + defaultNamespace: string, + specDocument: DocumentNode, + specification: string, +): SpecLink { + // Callers only pass links whose `url` matched, so it is present. + const url = stringArgument(node, 'url')!; + const imports = parseImports( + node, + importableNames(specDocument), + `${specification} ${printVersion(version)}`, + ); + const namespace = stringArgument(node, 'as') ?? defaultNamespace; + return { url, version, namespace, imports, node }; +} + /** * Finds the `@link` pointing at the federation specification, if any. A document * without one is treated as a Federation 1 subgraph. @@ -80,41 +128,61 @@ export function hasLinkDirective(document: DocumentNode): boolean { export function findFederationLink( document: DocumentNode, ): FederationLink | null { - const links = schemaLevelDirectives(document).filter((directive) => { - if (directive.name.value !== LINK_DIRECTIVE_NAME) return false; - const url = stringArgument(directive, 'url'); - return url !== undefined && url.startsWith(`${FEDERATION_SPEC_IDENTITY}/`); - }); - + const links = linksTo(document, FEDERATION_SPEC_IDENTITY); if (links.length === 0) return null; if (links.length > 1) throw new MultipleFederationLinksError(links); const node = links[0]; - // `stringArgument` already matched, so `url` is present. const url = stringArgument(node, 'url')!; - const version = parseFederationVersion(url); - const imports = parseImports(node, version); - - return { url, version, imports, node }; -} - -function parseFederationVersion(url: string): SpecVersion { - const match = /\/v(\d+)\.(\d+)\/?$/.exec(url); - if (!match) throw new UnsupportedFederationVersionError(url); - - const version = { major: Number(match[1]), minor: Number(match[2]) }; + const version = parseVersion(url); if ( + !version || version.major !== LATEST_FEDERATION_VERSION.major || versionCode(version) > versionCode(LATEST_FEDERATION_VERSION) ) { throw new UnsupportedFederationVersionError(url); } - return version; + + return specLink( + node, + version, + FEDERATION_NAMESPACE, + federationSpecDocument(version), + 'federation specification', + ); +} + +/** + * The names the link specification's own elements take in this schema. `@link` + * itself is never renamed, but `Import` and `Purpose` follow the `import` list of + * the schema's `@link(url: "https://specs.apollo.dev/link/v1.0")`, if any, and + * are otherwise namespaced (`link__Import`). + */ +export function findLinkSpecImports( + document: DocumentNode, +): Map { + const imports = new Map([['@link', '@link']]); + const [bootstrap] = linksTo(document, LINK_SPEC_IDENTITY); + if (!bootstrap) return imports; + + const version = parseVersion(stringArgument(bootstrap, 'url')!); + const specification = version + ? `link specification ${printVersion(version)}` + : 'link specification'; + for (const [name, alias] of parseImports( + bootstrap, + importableNames(linkSpecDocument()), + specification, + )) { + if (name !== '@link') imports.set(name, alias); + } + return imports; } function parseImports( link: ConstDirectiveNode, - version: SpecVersion, + importable: Set, + specification: string, ): Map { const imports = new Map(); const importArgument = link.arguments?.find( @@ -125,12 +193,10 @@ function parseImports( throw UnsupportedLinkImportError.malformed(importArgument.value); } - const importable = importableNames(version); - for (const entry of importArgument.value.values) { const { name, alias } = parseImportEntry(entry); if (!importable.has(name)) { - throw UnsupportedLinkImportError.unknownName(name, printVersion(version)); + throw UnsupportedLinkImportError.unknownName(name, specification); } imports.set(name, alias); } diff --git a/src/specs.ts b/src/specs.ts index 6d642ce..5fc1d77 100644 --- a/src/specs.ts +++ b/src/specs.ts @@ -242,12 +242,12 @@ export function federation1SpecDocument(): DocumentNode { } /** - * The names a `@link(import: [...])` may legally reference for `version`. + * The names a `@link(import: [...])` may legally reference from `specDocument`. * Directives are keyed with their leading `@`, matching the `import` syntax. */ -export function importableNames(version: SpecVersion): Set { +export function importableNames(specDocument: DocumentNode): Set { const names = new Set(); - for (const definition of federationSpecDocument(version).definitions) { + for (const definition of specDocument.definitions) { switch (definition.kind) { case Kind.DIRECTIVE_DEFINITION: names.add(`@${definition.name.value}`); From a1482878f95e5cb52bd1f19372e0eaeb356c03dd Mon Sep 17 00:00:00 2001 From: dariuszkuc <9501705+dariuszkuc@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:00:57 -0600 Subject: [PATCH 2/5] fix: read extra path segments under a spec as a custom specification A `@link` url is only a link to a known specification when its version directly follows the specification identity. As in composition, the last path segment is the version and the one before it the specification name, so `https://specs.apollo.dev/federation/extra/v1.0` links a custom specification named `extra`. It was read as a federation link, which rejected schemas that also linked federation (MultipleFederationLinksError) even though they compose. A trailing slash after the version is still matched, and rejected. Co-Authored-By: Claude Opus 5.5 --- .changeset/link-handling-fixes.md | 1 + src/__tests__/buildSubgraphSchema.test.ts | 16 ++++++++++++++ src/link.ts | 27 +++++++++++++++++------ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/.changeset/link-handling-fixes.md b/.changeset/link-handling-fixes.md index 68c5dff..1958839 100644 --- a/.changeset/link-handling-fixes.md +++ b/.changeset/link-handling-fixes.md @@ -7,3 +7,4 @@ Align `@link` handling with composition: - `@link(as: ...)` is now honoured for the federation link, so elements that aren't imported are namespaced under the alias instead of `federation__`. - `@link(url: "https://specs.apollo.dev/link/v1.0", import: [...])` now names `Import` and `Purpose` after its imports instead of always using `link__Import` / `link__Purpose`. - A `@link` URL with a trailing slash after the version (`.../federation/v2.9/`) is now rejected, matching composition. +- A `@link` URL with extra path segments under a known specification (`https://specs.apollo.dev/federation/extra/v1.0`) now links a custom specification (`extra`), as in composition, instead of being read as a federation link. diff --git a/src/__tests__/buildSubgraphSchema.test.ts b/src/__tests__/buildSubgraphSchema.test.ts index eae79ff..564288f 100644 --- a/src/__tests__/buildSubgraphSchema.test.ts +++ b/src/__tests__/buildSubgraphSchema.test.ts @@ -349,6 +349,22 @@ describe('@link', () => { ).toThrow(UnsupportedFederationVersionError); }); + it('treats a url with extra path segments under federation as a custom specification', () => { + const schema = buildSubgraphSchema( + parse(` + ${fed2('v2.9', '"@key"')} + extend schema @link(url: "https://specs.apollo.dev/federation/extra/v1.0", import: ["@foo"]) + directive @foo on FIELD_DEFINITION + type Product @key(fields: "id") { id: ID! name: String @foo } + `), + ); + + expect(schema.getDirective('key')).toBeDefined(); + expect( + (schema.getType('_Entity') as GraphQLUnionType).getTypes(), + ).toHaveLength(1); + }); + it('rejects an import the linked version does not define', () => { expect(() => buildSubgraphSchema( diff --git a/src/link.ts b/src/link.ts index 41d783f..248b477 100644 --- a/src/link.ts +++ b/src/link.ts @@ -84,7 +84,16 @@ export function hasLinkDirective(document: DocumentNode): boolean { ); } -/** Every schema-level `@link` whose `url` points at the specification `identity`. */ +/** + * Every schema-level `@link` whose `url` points at the specification `identity`. + * + * As in composition, the last path segment of a `url` is the version and the one + * before it is the specification name, so only the version may follow the + * identity: `https://specs.apollo.dev/federation/extra/v2.9` links a custom + * specification named `extra`, not federation. A trailing slash is still + * matched, so that a malformed version (`.../federation/v2.9/`) is reported + * against this specification rather than silently ignored. + */ function linksTo( document: DocumentNode, identity: string, @@ -92,13 +101,14 @@ function linksTo( return schemaLevelDirectives(document).filter((directive) => { if (directive.name.value !== LINK_DIRECTIVE_NAME) return false; const url = stringArgument(directive, 'url'); - return url !== undefined && url.startsWith(`${identity}/`); + if (url === undefined || !url.startsWith(`${identity}/`)) return false; + return /^[^/]*\/?$/.test(url.slice(identity.length + 1)); }); } -/** Reads the `vX.Y` suffix of a specification URL. */ -function parseVersion(url: string): SpecVersion | null { - const match = /\/v(\d+)\.(\d+)$/.exec(url); +/** Reads the `vX.Y` version following `identity` in a specification `url`. */ +function parseVersion(url: string, identity: string): SpecVersion | null { + const match = /^v(\d+)\.(\d+)$/.exec(url.slice(identity.length + 1)); if (!match) return null; return { major: Number(match[1]), minor: Number(match[2]) }; } @@ -134,7 +144,7 @@ export function findFederationLink( const node = links[0]; const url = stringArgument(node, 'url')!; - const version = parseVersion(url); + const version = parseVersion(url, FEDERATION_SPEC_IDENTITY); if ( !version || version.major !== LATEST_FEDERATION_VERSION.major || @@ -165,7 +175,10 @@ export function findLinkSpecImports( const [bootstrap] = linksTo(document, LINK_SPEC_IDENTITY); if (!bootstrap) return imports; - const version = parseVersion(stringArgument(bootstrap, 'url')!); + const version = parseVersion( + stringArgument(bootstrap, 'url')!, + LINK_SPEC_IDENTITY, + ); const specification = version ? `link specification ${printVersion(version)}` : 'link specification'; From 4ac75b2dbea4e35f21d74b59cb9b94cf65118a16 Mon Sep 17 00:00:00 2001 From: dariuszkuc <9501705+dariuszkuc@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:14:13 -0600 Subject: [PATCH 3/5] feat: add Apollo Connectors spec definitions A subgraph that `@link`s `https://specs.apollo.dev/connect/v0.1` through `v0.4` gets the `@connect` and `@source` directives and their supporting types, following the link's `import` list and `as` namespace. - Definitions match what composition v2.15+ expects (e.g. `URLTemplate`). - `@connect` takes the namespace as its name when it isn't imported (`@connect`, or `@`), as composition names it. - A connectors subgraph's `_service { sdl }` leaves out the `_service` / `_entities` machinery, which composition rejects there. - Connector usage itself is still validated by composition. Co-Authored-By: Claude Opus 5.5 --- .changeset/connect-spec-definitions.md | 7 + README.md | 20 ++ src/__tests__/buildSubgraphSchema.test.ts | 344 ++++++++++++++++++++++ src/buildSubgraphSchema.ts | 29 +- src/errors.ts | 28 +- src/index.ts | 4 + src/link.ts | 60 +++- src/specs.ts | 77 ++++- 8 files changed, 559 insertions(+), 10 deletions(-) create mode 100644 .changeset/connect-spec-definitions.md diff --git a/.changeset/connect-spec-definitions.md b/.changeset/connect-spec-definitions.md new file mode 100644 index 0000000..5322d3b --- /dev/null +++ b/.changeset/connect-spec-definitions.md @@ -0,0 +1,7 @@ +--- +'@apollo/subgraph': minor +--- + +Add Apollo Connectors spec definitions. A subgraph that `@link`s `https://specs.apollo.dev/connect/v0.1` through `v0.4` now gets the `@connect` and `@source` directives and their supporting types, following the link's `import` list and `as` namespace, with the definitions composition (v2.15+) expects. Connector usage itself is still validated by composition. + +A connectors subgraph's `_service { sdl }` leaves out the `_service` / `_entities` fields and the `_Service`, `_Any` and `_Entity` types, which composition rejects in a connectors subgraph. The schema still serves them. diff --git a/README.md b/README.md index 5afccba..61a2347 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,26 @@ await startStandaloneServer(server, { listen: { port: 4001 } }); Entity references are resolved through `__resolveReference`, either from a resolver map or from `extensions.apollo.subgraph.resolveReference` on the type. +### Apollo Connectors + +Schemas that `@link` the [Apollo Connectors](https://www.apollographql.com/docs/graphos/connectors) +specification (`https://specs.apollo.dev/connect/v0.1` through `v0.4`) get the +`@connect` and `@source` directives and their supporting types, so connectors +schemas can be built, printed and inspected: + +```graphql +extend schema + @link(url: "https://specs.apollo.dev/federation/v2.12", import: ["@key"]) + @link(url: "https://specs.apollo.dev/connect/v0.3", import: ["@connect", "@source"]) + @source(name: "api", http: { baseURL: "https://api.example.com" }) +``` + +Connectors are executed by the router, not by this library, and whether they are +used correctly is validated by composition. Because composition requires every +field of a connectors subgraph to be resolved by a connector, `_service { sdl }` +leaves out the `_service` / `_entities` fields and their `_Service`, `_Any` and +`_Entity` types; the schema still serves them. + ## Development ```sh diff --git a/src/__tests__/buildSubgraphSchema.test.ts b/src/__tests__/buildSubgraphSchema.test.ts index 564288f..3f80a3d 100644 --- a/src/__tests__/buildSubgraphSchema.test.ts +++ b/src/__tests__/buildSubgraphSchema.test.ts @@ -2,7 +2,9 @@ import { GraphQLObjectType, GraphQLUnionType, graphql, parse } from 'graphql'; import gql from 'graphql-tag'; import { buildSubgraphSchema } from '../buildSubgraphSchema'; import { + MultipleConnectLinksError, MultipleFederationLinksError, + UnsupportedConnectVersionError, UnsupportedFederationVersionError, UnsupportedLinkImportError, } from '../errors'; @@ -470,6 +472,348 @@ describe('@link', () => { }); }); +describe('Apollo Connectors', () => { + const connect = ( + version = 'v0.3', + linkArguments = 'import: ["@connect", "@source"]', + ) => ` + extend schema + @link(url: "https://specs.apollo.dev/federation/v2.12", import: ["@key"]) + @link(url: "https://specs.apollo.dev/connect/${version}", ${linkArguments}) + `; + + const usersSchema = ` + extend schema + @source(name: "api", http: { baseURL: "https://api.example.com", headers: [{ name: "x-api-key", from: "x-api-key" }] }) + + type Query { + user(id: ID!): User + @connect( + source: "api" + http: { GET: "/users/{$args.id}" } + selection: "id name" + entity: true + ) + } + + type User @key(fields: "id") { + id: ID! + name: String + } + `; + + it('defines the imported connect directives', () => { + const schema = buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)); + + const connectDirective = schema.getDirective('connect')!; + expect(connectDirective.isRepeatable).toBe(true); + expect(connectDirective.locations).toEqual(['FIELD_DEFINITION', 'OBJECT']); + expect( + connectDirective.args.map((arg) => `${arg.name}: ${arg.type}`), + ).toEqual([ + 'source: String', + 'id: String', + 'http: connect__ConnectHTTP', + 'batch: connect__ConnectBatch', + 'errors: connect__ConnectorErrors', + 'selection: connect__JSONSelection!', + 'entity: Boolean', + 'isSuccess: connect__JSONSelection', + ]); + expect(schema.getDirective('source')!.locations).toEqual(['SCHEMA']); + }); + + it('publishes the connect definitions composition expects', async () => { + const sdl = await serviceSdl( + buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)), + ); + + expect(sdl).toContain( + 'directive @connect(source: String, id: String, http: connect__ConnectHTTP, batch: connect__ConnectBatch, errors: connect__ConnectorErrors, selection: connect__JSONSelection!, entity: Boolean = false, isSuccess: connect__JSONSelection) repeatable on FIELD_DEFINITION | OBJECT', + ); + expect(sdl).toContain( + 'directive @source(name: String!, http: connect__SourceHTTP!, errors: connect__ConnectorErrors, isSuccess: connect__JSONSelection) repeatable on SCHEMA', + ); + expect(sdl).toContain('scalar connect__JSONSelection'); + expect(sdl).toContain('scalar connect__URLTemplate'); + expect(sdl).toContain( + [ + 'input connect__ConnectorErrors {', + ' message: connect__JSONSelection', + ' extensions: connect__JSONSelection', + '}', + ].join('\n'), + ); + expect(sdl).toContain( + [ + 'input connect__HTTPHeaderMapping {', + ' name: String!', + ' from: String', + ' value: String', + '}', + ].join('\n'), + ); + expect(sdl).toContain( + ['input connect__ConnectBatch {', ' maxSize: Int', '}'].join('\n'), + ); + expect(sdl).toContain( + [ + 'input connect__SourceHTTP {', + ' baseURL: String!', + ' headers: [connect__HTTPHeaderMapping!]', + ' path: connect__JSONSelection', + ' queryParams: connect__JSONSelection', + '}', + ].join('\n'), + ); + expect(sdl).toContain( + [ + 'input connect__ConnectHTTP {', + ' GET: connect__URLTemplate', + ' POST: connect__URLTemplate', + ' PUT: connect__URLTemplate', + ' PATCH: connect__URLTemplate', + ' DELETE: connect__URLTemplate', + ' body: connect__JSONSelection', + ' headers: [connect__HTTPHeaderMapping!]', + ' path: connect__JSONSelection', + ' queryParams: connect__JSONSelection', + '}', + ].join('\n'), + ); + }); + + it('leaves the _service and _entities machinery out of _service { sdl }', async () => { + const schema = buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)); + const sdl = await serviceSdl(schema); + + // Still served by the subgraph... + expect(schema.getQueryType()!.getFields()._service).toBeDefined(); + expect(schema.getQueryType()!.getFields()._entities).toBeDefined(); + // ...but composition rejects them in a connectors subgraph. + expect(sdl).not.toMatch(/_service|_entities|_Service|_Entity|_Any/); + expect(sdl).toMatch(/type User @key\(fields: "id"\)/); + expect(sdl).toMatch(/directive @connect\(/); + }); + + it('namespaces connect definitions that are not imported', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: ["@connect"]')} + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('connect')).toBeDefined(); + expect(schema.getDirective('source')).toBeUndefined(); + expect(schema.getDirective('connect__source')).toBeDefined(); + }); + + it('names @connect after the namespace when it is not imported', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: []')} + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('connect')).toBeDefined(); + expect(schema.getDirective('connect__connect')).toBeUndefined(); + expect(schema.getDirective('connect__source')).toBeDefined(); + expect(schema.getType('connect__ConnectHTTP')).toBeDefined(); + }); + + it('namespaces connect definitions under the @link alias', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'as: "rest"')} + type Query { + hello: String @rest(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('rest')).toBeDefined(); + expect(schema.getDirective('rest__connect')).toBeUndefined(); + expect(schema.getDirective('connect')).toBeUndefined(); + expect(schema.getDirective('rest__source')).toBeDefined(); + expect(schema.getType('rest__ConnectHTTP')).toBeDefined(); + }); + + it('supports renamed connect imports', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: [{ name: "@connect", as: "@http" }, "JSONSelection"]')} + type Query { + hello: String @http(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('http')).toBeDefined(); + expect(schema.getDirective('connect')).toBeUndefined(); + expect(schema.getType('JSONSelection')).toBeDefined(); + expect(String(schema.getDirective('http')!.args[5].type)).toBe( + 'JSONSelection!', + ); + }); + + it('accepts connectors on types and connectors without http', () => { + expect(() => + buildSubgraphSchema( + parse(` + ${connect('v0.4')} + type Query { + greeting(name: String!): String! @connect(selection: "$args.name") + } + type User + @connect(http: { GET: "https://api.example.com/users/{$this.id}" }, selection: "id name") + @connect(http: { GET: "https://api.example.com/users/{$this.id}/details" }, selection: "id email") + { + id: ID! + name: String + email: String + } + `), + ), + ).not.toThrow(); + }); + + it.each(['v0.1', 'v0.2', 'v0.3', 'v0.4'])( + 'supports connect %s', + (version) => { + const schema = buildSubgraphSchema( + parse(`${connect(version)} ${usersSchema}`), + ); + expect(schema.getDirective('connect')).toBeDefined(); + }, + ); + + it.each(['v0.0', 'v0.5', 'v1.0', 'latest', 'v0.3/'])( + 'rejects connect %s', + (version) => { + expect(() => + buildSubgraphSchema(parse(`${connect(version)} ${usersSchema}`)), + ).toThrow(UnsupportedConnectVersionError); + }, + ); + + it('imports the URLTemplate scalar under the name composition uses', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: ["@connect", "URLTemplate"]')} + type Query { hello: String } + `), + ); + + expect(schema.getType('URLTemplate')).toBeDefined(); + expect(() => + buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: ["@connect", "URLPathTemplate"]')} + type Query { hello: String } + `), + ), + ).toThrow(UnsupportedLinkImportError); + }); + + it('rejects an import the connect specification does not define', () => { + expect(() => + buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: ["@connect", "@key"]')} + type Query { hello: String } + `), + ), + ).toThrow( + 'Cannot import "@key": it is not part of the connect specification v0.3.', + ); + }); + + it('rejects more than one connect @link', () => { + expect(() => + buildSubgraphSchema( + parse(` + ${connect()} + extend schema @link(url: "https://specs.apollo.dev/connect/v0.2") + type Query { hello: String } + `), + ), + ).toThrow(MultipleConnectLinksError); + }); + + it('leaves user-provided connect definitions alone', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect()} + directive @connect(http: connect__ConnectHTTP, selection: String!) on FIELD_DEFINITION + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('connect')!.args.map((arg) => arg.name)).toEqual( + ['http', 'selection'], + ); + }); + + it('defines the connect directives without a federation @link', () => { + const schema = buildSubgraphSchema( + parse(` + extend schema @link(url: "https://specs.apollo.dev/connect/v0.3", import: ["@connect"]) + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('connect')).toBeDefined(); + expect(schema.getDirective('link')).toBeDefined(); + }); + + it('leaves validating connector usage to composition', () => { + // Two HTTP methods and `entity: true` on a non-`Query` field are both + // invalid connectors, but only composition reports that. + expect(() => + buildSubgraphSchema( + parse(` + ${connect()} + type Query { user: User } + type User { + id: ID! + name: String + @connect( + http: { GET: "https://a.example.com", POST: "https://b.example.com" } + selection: "name" + entity: true + ) + } + `), + ), + ).not.toThrow(); + }); + + it('still reports GraphQL errors in connect directive applications', () => { + expect(() => + buildSubgraphSchema( + parse(` + ${connect()} + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }) + } + `), + ), + ).toThrow( + /Directive "@connect" argument "selection" of type "connect__JSONSelection!" is required/, + ); + }); +}); + describe('Federation 1', () => { const fed1Schema = () => buildSubgraphSchema( diff --git a/src/buildSubgraphSchema.ts b/src/buildSubgraphSchema.ts index 6902947..5cfda1d 100644 --- a/src/buildSubgraphSchema.ts +++ b/src/buildSubgraphSchema.ts @@ -17,8 +17,10 @@ import { } from 'graphql'; import { GraphQLSchemaValidationError } from './errors'; import { + CONNECT_NAMESPACE, LINK_NAMESPACE, applyLinkNaming, + findConnectLink, findFederationLink, findLinkSpecImports, hasLinkDirective, @@ -30,6 +32,7 @@ import { modulesFromSDL, } from './resolvers'; import { + connectSpecDocument, federation1SpecDocument, federationSpecDocument, linkSpecDocument, @@ -336,6 +339,22 @@ function buildSubgraph(inputDocument: DocumentNode): Subgraph { collectDefinedNames(specDefinitions, specNames); + // Connectors are run by the router, so only their definitions are provided + // here; validating how they are used is left to composition. Added after + // `specNames` is collected: these are not federation elements, so a + // Federation 1 subgraph's own connect definitions stay in `_service { sdl }`. + const connectLink = findConnectLink(userDocument); + if (connectLink) { + specDefinitions.push( + ...applyLinkNaming( + connectSpecDocument(), + connectLink.imports, + connectLink.namespace, + CONNECT_NAMESPACE, + ).definitions, + ); + } + // Only contribute what the schema has not already declared for itself. const injectedSpecDefinitions = specDefinitions.filter((definition) => { const name = definitionName(definition); @@ -385,11 +404,17 @@ function buildSubgraph(inputDocument: DocumentNode): Subgraph { // Federation 2 composition reads a subgraph's `@link`s to interpret it, so the // whole assembled document is published. Federation 1 composition predates // `@link` and fails if a subgraph declares the federation directives itself, - // so those are held back for it. + // so those are held back for it. A connectors subgraph also leaves out the + // `_service` / `_entities` machinery: composition requires every field of it + // to be resolved by a connector and rejects unions such as `_Entity`. const serviceSdl = () => printDefinitions( isFederation2 - ? document.definitions + ? connectLink + ? document.definitions.filter( + (definition) => !machineryDefinitions.includes(definition), + ) + : document.definitions : withoutFederationElements( [...userDocument.definitions, ...synthesizedDefinitions], federationElementNames, diff --git a/src/errors.ts b/src/errors.ts index 32bd64b..a84ef96 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,5 +1,10 @@ import { ASTNode, GraphQLError, print } from 'graphql'; -import { LATEST_FEDERATION_VERSION, printVersion } from './specs'; +import { + EARLIEST_CONNECT_VERSION, + LATEST_CONNECT_VERSION, + LATEST_FEDERATION_VERSION, + printVersion, +} from './specs'; /** Thrown when the assembled subgraph schema is not a valid GraphQL schema. */ export class GraphQLSchemaValidationError extends Error { @@ -37,6 +42,27 @@ export class UnsupportedFederationVersionError extends FederationError { } } +export class MultipleConnectLinksError extends FederationError { + constructor(links: ReadonlyArray) { + super( + `Schema links the connect specification more than once. Only a single ` + + `@link to https://specs.apollo.dev/connect is allowed, found:\n` + + links.map((link) => `\t${print(link)}`).join('\n'), + ); + } +} + +export class UnsupportedConnectVersionError extends FederationError { + constructor(url: string) { + super( + `Unsupported connect version linked from "${url}". Expected a URL of the ` + + `form https://specs.apollo.dev/connect/v0.x, from ` + + `${printVersion(EARLIEST_CONNECT_VERSION)} up to ` + + `${printVersion(LATEST_CONNECT_VERSION)}.`, + ); + } +} + export class UnsupportedLinkImportError extends FederationError { constructor(message: string) { super(message); diff --git a/src/index.ts b/src/index.ts index dac64b4..a13eee7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,13 +16,17 @@ export { entitiesResolver } from './types'; export { FederationError, GraphQLSchemaValidationError, + MultipleConnectLinksError, MultipleFederationLinksError, + UnsupportedConnectVersionError, UnsupportedFederationVersionError, UnsupportedLinkImportError, } from './errors'; export { + CONNECT_SPEC_IDENTITY, FEDERATION_SPEC_IDENTITY, + LATEST_CONNECT_VERSION, LATEST_FEDERATION_VERSION, LINK_SPEC_IDENTITY, type SpecVersion, diff --git a/src/link.ts b/src/link.ts index 248b477..dc94011 100644 --- a/src/link.ts +++ b/src/link.ts @@ -1,7 +1,7 @@ /** - * `@link` handling: finding the federation link in a subgraph document, reading - * its `import` list, and applying the resulting naming to the specification - * definitions this library injects. + * `@link` handling: finding the federation and connect links in a subgraph + * document, reading their `import` lists, and applying the resulting naming to + * the specification definitions this library injects. */ import { ConstDirectiveNode, @@ -12,15 +12,21 @@ import { visit, } from 'graphql'; import { + MultipleConnectLinksError, MultipleFederationLinksError, + UnsupportedConnectVersionError, UnsupportedFederationVersionError, UnsupportedLinkImportError, } from './errors'; import { + CONNECT_SPEC_IDENTITY, + EARLIEST_CONNECT_VERSION, FEDERATION_SPEC_IDENTITY, + LATEST_CONNECT_VERSION, LATEST_FEDERATION_VERSION, LINK_SPEC_IDENTITY, SpecVersion, + connectSpecDocument, federationSpecDocument, linkSpecDocument, importableNames, @@ -32,6 +38,7 @@ const LINK_DIRECTIVE_NAME = 'link'; export const FEDERATION_NAMESPACE = 'federation'; export const LINK_NAMESPACE = 'link'; +export const CONNECT_NAMESPACE = 'connect'; /** A schema's `@link` to one of the specifications this library knows. */ export interface SpecLink { @@ -53,6 +60,7 @@ export interface SpecLink { } export type FederationLink = SpecLink; +export type ConnectLink = SpecLink; function schemaLevelDirectives(document: DocumentNode): ConstDirectiveNode[] { const directives: ConstDirectiveNode[] = []; @@ -162,6 +170,37 @@ export function findFederationLink( ); } +/** + * Finds the `@link` pointing at the Apollo Connectors specification, if any. + * + * Only the definitions are provided: whether connectors are used correctly, and + * whether the linked federation version supports them, is composition's job. + */ +export function findConnectLink(document: DocumentNode): ConnectLink | null { + const links = linksTo(document, CONNECT_SPEC_IDENTITY); + if (links.length === 0) return null; + if (links.length > 1) throw new MultipleConnectLinksError(links); + + const node = links[0]; + const url = stringArgument(node, 'url')!; + const version = parseVersion(url, CONNECT_SPEC_IDENTITY); + if ( + !version || + versionCode(version) < versionCode(EARLIEST_CONNECT_VERSION) || + versionCode(version) > versionCode(LATEST_CONNECT_VERSION) + ) { + throw new UnsupportedConnectVersionError(url); + } + + return specLink( + node, + version, + CONNECT_NAMESPACE, + connectSpecDocument(), + 'connect specification', + ); +} + /** * The names the link specification's own elements take in this schema. `@link` * itself is never renamed, but `Import` and `Purpose` follow the `import` list of @@ -245,14 +284,20 @@ function parseImportEntry(entry: ConstValueNode): { /** * The name a canonical specification element takes in this schema: its alias if * it was imported, otherwise the namespaced form (`@key` -> `@federation__key`). + * A directive named after its specification (`@connect` in `connect/v0.x`) is + * the exception: it takes the namespace itself (`@connect`, or `@`). */ export function linkedName( imports: Map, namespace: string, canonical: string, + specName?: string, ): string { const alias = imports.get(canonical); if (alias) return alias; + if (specName !== undefined && canonical === `@${specName}`) { + return `@${namespace}`; + } return canonical.startsWith('@') ? `@${namespace}__${canonical.slice(1)}` : `${namespace}__${canonical}`; @@ -276,9 +321,10 @@ export function applyLinkNaming( document: DocumentNode, imports: Map, namespace: string, + specName?: string, ): DocumentNode { const rename = (canonical: string) => - linkedName(imports, namespace, canonical); + linkedName(imports, namespace, canonical, specName); return visit(document, { DirectiveDefinition(node) { @@ -297,6 +343,12 @@ export function applyLinkNaming( name: { ...node.name, value: rename(node.name.value) }, }; }, + InputObjectTypeDefinition(node) { + return { + ...node, + name: { ...node.name, value: rename(node.name.value) }, + }; + }, NamedType(node) { if (specifiedScalarTypes.some((type) => type.name === node.name.value)) return undefined; diff --git a/src/specs.ts b/src/specs.ts index 5fc1d77..92287fb 100644 --- a/src/specs.ts +++ b/src/specs.ts @@ -1,8 +1,8 @@ /** - * The Apollo Federation and `@link` specification definitions. + * The Apollo Federation, `@link` and Apollo Connectors specification definitions. * - * This module is the only place in the library that knows what the federation - * specification contains. Everything else works with plain `graphql-js` AST and + * This module is the only place in the library that knows what those + * specifications contain. Everything else works with plain `graphql-js` AST and * schema objects. * * The definitions are kept as one entry per SDL definition, tagged with the @@ -14,6 +14,7 @@ import { DocumentNode, Kind, parse } from 'graphql'; export const FEDERATION_SPEC_IDENTITY = 'https://specs.apollo.dev/federation'; export const LINK_SPEC_IDENTITY = 'https://specs.apollo.dev/link'; +export const CONNECT_SPEC_IDENTITY = 'https://specs.apollo.dev/connect'; export interface SpecVersion { major: number; @@ -32,6 +33,10 @@ export function printVersion({ major, minor }: SpecVersion): string { /** The most recent federation version this library knows how to link against. */ export const LATEST_FEDERATION_VERSION: SpecVersion = { major: 2, minor: 15 }; +/** The oldest and most recent connect versions this library knows how to link against. */ +export const EARLIEST_CONNECT_VERSION: SpecVersion = { major: 0, minor: 1 }; +export const LATEST_CONNECT_VERSION: SpecVersion = { major: 0, minor: 4 }; + const version = (major: number, minor: number) => versionCode({ major, minor }); interface VersionedDefinition { @@ -202,6 +207,62 @@ directive @extends on OBJECT | INTERFACE directive @tag(name: String!) repeatable on ${TAG_LOCATIONS} `; +/** + * The Apollo Connectors specification, `https://specs.apollo.dev/connect/v0.x`. + * + * Every released version shares the same definitions: the differences between + * versions (connectors on types, virtual connectors, mapping grammar, ...) are + * enforced by composition, not by the SDL. This must stay identical to the + * definitions composition (v2.15+) expects, which rejects unknown or retyped + * input fields: e.g. `ConnectHTTP.GET` must be `URLTemplate`, not the + * `URLPathTemplate` used by the older JavaScript composition. + * + * @see {@link https://www.apollographql.com/docs/graphos/connectors/reference/directives Apollo Connectors} for details. + */ +const CONNECT_SPEC_SDL = ` +directive @connect(source: String, id: String, http: ConnectHTTP, batch: ConnectBatch, errors: ConnectorErrors, selection: JSONSelection!, entity: Boolean = false, isSuccess: JSONSelection) repeatable on FIELD_DEFINITION | OBJECT + +directive @source(name: String!, http: SourceHTTP!, errors: ConnectorErrors, isSuccess: JSONSelection) repeatable on SCHEMA + +scalar JSONSelection + +scalar URLTemplate + +input ConnectorErrors { + message: JSONSelection + extensions: JSONSelection +} + +input HTTPHeaderMapping { + name: String! + from: String + value: String +} + +input ConnectBatch { + maxSize: Int +} + +input SourceHTTP { + baseURL: String! + headers: [HTTPHeaderMapping!] + path: JSONSelection + queryParams: JSONSelection +} + +input ConnectHTTP { + GET: URLTemplate + POST: URLTemplate + PUT: URLTemplate + PATCH: URLTemplate + DELETE: URLTemplate + body: JSONSelection + headers: [HTTPHeaderMapping!] + path: JSONSelection + queryParams: JSONSelection +} +`; + function documentFrom(sdl: string): DocumentNode { return parse(sdl, { noLocation: true }); } @@ -241,6 +302,16 @@ export function federation1SpecDocument(): DocumentNode { return (federation1Document ??= documentFrom(FEDERATION_1_SDL)); } +let connectDocument: DocumentNode | undefined; + +/** + * The connect specification definitions, under their canonical names. The same + * for every supported connect version. + */ +export function connectSpecDocument(): DocumentNode { + return (connectDocument ??= documentFrom(CONNECT_SPEC_SDL)); +} + /** * The names a `@link(import: [...])` may legally reference from `specDocument`. * Directives are keyed with their leading `@`, matching the `import` syntax. From f9e2ae1fdf4290bc3223ead80155f0514ac8b754 Mon Sep 17 00:00:00 2001 From: dariuszkuc <9501705+dariuszkuc@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:13:47 -0600 Subject: [PATCH 4/5] test: move Apollo Connectors tests to their own file Co-Authored-By: Claude Opus 5.5 --- src/__tests__/buildSubgraphSchema.test.ts | 344 --------------------- src/__tests__/connectors.test.ts | 356 ++++++++++++++++++++++ 2 files changed, 356 insertions(+), 344 deletions(-) create mode 100644 src/__tests__/connectors.test.ts diff --git a/src/__tests__/buildSubgraphSchema.test.ts b/src/__tests__/buildSubgraphSchema.test.ts index 3f80a3d..564288f 100644 --- a/src/__tests__/buildSubgraphSchema.test.ts +++ b/src/__tests__/buildSubgraphSchema.test.ts @@ -2,9 +2,7 @@ import { GraphQLObjectType, GraphQLUnionType, graphql, parse } from 'graphql'; import gql from 'graphql-tag'; import { buildSubgraphSchema } from '../buildSubgraphSchema'; import { - MultipleConnectLinksError, MultipleFederationLinksError, - UnsupportedConnectVersionError, UnsupportedFederationVersionError, UnsupportedLinkImportError, } from '../errors'; @@ -472,348 +470,6 @@ describe('@link', () => { }); }); -describe('Apollo Connectors', () => { - const connect = ( - version = 'v0.3', - linkArguments = 'import: ["@connect", "@source"]', - ) => ` - extend schema - @link(url: "https://specs.apollo.dev/federation/v2.12", import: ["@key"]) - @link(url: "https://specs.apollo.dev/connect/${version}", ${linkArguments}) - `; - - const usersSchema = ` - extend schema - @source(name: "api", http: { baseURL: "https://api.example.com", headers: [{ name: "x-api-key", from: "x-api-key" }] }) - - type Query { - user(id: ID!): User - @connect( - source: "api" - http: { GET: "/users/{$args.id}" } - selection: "id name" - entity: true - ) - } - - type User @key(fields: "id") { - id: ID! - name: String - } - `; - - it('defines the imported connect directives', () => { - const schema = buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)); - - const connectDirective = schema.getDirective('connect')!; - expect(connectDirective.isRepeatable).toBe(true); - expect(connectDirective.locations).toEqual(['FIELD_DEFINITION', 'OBJECT']); - expect( - connectDirective.args.map((arg) => `${arg.name}: ${arg.type}`), - ).toEqual([ - 'source: String', - 'id: String', - 'http: connect__ConnectHTTP', - 'batch: connect__ConnectBatch', - 'errors: connect__ConnectorErrors', - 'selection: connect__JSONSelection!', - 'entity: Boolean', - 'isSuccess: connect__JSONSelection', - ]); - expect(schema.getDirective('source')!.locations).toEqual(['SCHEMA']); - }); - - it('publishes the connect definitions composition expects', async () => { - const sdl = await serviceSdl( - buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)), - ); - - expect(sdl).toContain( - 'directive @connect(source: String, id: String, http: connect__ConnectHTTP, batch: connect__ConnectBatch, errors: connect__ConnectorErrors, selection: connect__JSONSelection!, entity: Boolean = false, isSuccess: connect__JSONSelection) repeatable on FIELD_DEFINITION | OBJECT', - ); - expect(sdl).toContain( - 'directive @source(name: String!, http: connect__SourceHTTP!, errors: connect__ConnectorErrors, isSuccess: connect__JSONSelection) repeatable on SCHEMA', - ); - expect(sdl).toContain('scalar connect__JSONSelection'); - expect(sdl).toContain('scalar connect__URLTemplate'); - expect(sdl).toContain( - [ - 'input connect__ConnectorErrors {', - ' message: connect__JSONSelection', - ' extensions: connect__JSONSelection', - '}', - ].join('\n'), - ); - expect(sdl).toContain( - [ - 'input connect__HTTPHeaderMapping {', - ' name: String!', - ' from: String', - ' value: String', - '}', - ].join('\n'), - ); - expect(sdl).toContain( - ['input connect__ConnectBatch {', ' maxSize: Int', '}'].join('\n'), - ); - expect(sdl).toContain( - [ - 'input connect__SourceHTTP {', - ' baseURL: String!', - ' headers: [connect__HTTPHeaderMapping!]', - ' path: connect__JSONSelection', - ' queryParams: connect__JSONSelection', - '}', - ].join('\n'), - ); - expect(sdl).toContain( - [ - 'input connect__ConnectHTTP {', - ' GET: connect__URLTemplate', - ' POST: connect__URLTemplate', - ' PUT: connect__URLTemplate', - ' PATCH: connect__URLTemplate', - ' DELETE: connect__URLTemplate', - ' body: connect__JSONSelection', - ' headers: [connect__HTTPHeaderMapping!]', - ' path: connect__JSONSelection', - ' queryParams: connect__JSONSelection', - '}', - ].join('\n'), - ); - }); - - it('leaves the _service and _entities machinery out of _service { sdl }', async () => { - const schema = buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)); - const sdl = await serviceSdl(schema); - - // Still served by the subgraph... - expect(schema.getQueryType()!.getFields()._service).toBeDefined(); - expect(schema.getQueryType()!.getFields()._entities).toBeDefined(); - // ...but composition rejects them in a connectors subgraph. - expect(sdl).not.toMatch(/_service|_entities|_Service|_Entity|_Any/); - expect(sdl).toMatch(/type User @key\(fields: "id"\)/); - expect(sdl).toMatch(/directive @connect\(/); - }); - - it('namespaces connect definitions that are not imported', () => { - const schema = buildSubgraphSchema( - parse(` - ${connect('v0.3', 'import: ["@connect"]')} - type Query { - hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") - } - `), - ); - - expect(schema.getDirective('connect')).toBeDefined(); - expect(schema.getDirective('source')).toBeUndefined(); - expect(schema.getDirective('connect__source')).toBeDefined(); - }); - - it('names @connect after the namespace when it is not imported', () => { - const schema = buildSubgraphSchema( - parse(` - ${connect('v0.3', 'import: []')} - type Query { - hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") - } - `), - ); - - expect(schema.getDirective('connect')).toBeDefined(); - expect(schema.getDirective('connect__connect')).toBeUndefined(); - expect(schema.getDirective('connect__source')).toBeDefined(); - expect(schema.getType('connect__ConnectHTTP')).toBeDefined(); - }); - - it('namespaces connect definitions under the @link alias', () => { - const schema = buildSubgraphSchema( - parse(` - ${connect('v0.3', 'as: "rest"')} - type Query { - hello: String @rest(http: { GET: "https://api.example.com/hello" }, selection: "$") - } - `), - ); - - expect(schema.getDirective('rest')).toBeDefined(); - expect(schema.getDirective('rest__connect')).toBeUndefined(); - expect(schema.getDirective('connect')).toBeUndefined(); - expect(schema.getDirective('rest__source')).toBeDefined(); - expect(schema.getType('rest__ConnectHTTP')).toBeDefined(); - }); - - it('supports renamed connect imports', () => { - const schema = buildSubgraphSchema( - parse(` - ${connect('v0.3', 'import: [{ name: "@connect", as: "@http" }, "JSONSelection"]')} - type Query { - hello: String @http(http: { GET: "https://api.example.com/hello" }, selection: "$") - } - `), - ); - - expect(schema.getDirective('http')).toBeDefined(); - expect(schema.getDirective('connect')).toBeUndefined(); - expect(schema.getType('JSONSelection')).toBeDefined(); - expect(String(schema.getDirective('http')!.args[5].type)).toBe( - 'JSONSelection!', - ); - }); - - it('accepts connectors on types and connectors without http', () => { - expect(() => - buildSubgraphSchema( - parse(` - ${connect('v0.4')} - type Query { - greeting(name: String!): String! @connect(selection: "$args.name") - } - type User - @connect(http: { GET: "https://api.example.com/users/{$this.id}" }, selection: "id name") - @connect(http: { GET: "https://api.example.com/users/{$this.id}/details" }, selection: "id email") - { - id: ID! - name: String - email: String - } - `), - ), - ).not.toThrow(); - }); - - it.each(['v0.1', 'v0.2', 'v0.3', 'v0.4'])( - 'supports connect %s', - (version) => { - const schema = buildSubgraphSchema( - parse(`${connect(version)} ${usersSchema}`), - ); - expect(schema.getDirective('connect')).toBeDefined(); - }, - ); - - it.each(['v0.0', 'v0.5', 'v1.0', 'latest', 'v0.3/'])( - 'rejects connect %s', - (version) => { - expect(() => - buildSubgraphSchema(parse(`${connect(version)} ${usersSchema}`)), - ).toThrow(UnsupportedConnectVersionError); - }, - ); - - it('imports the URLTemplate scalar under the name composition uses', () => { - const schema = buildSubgraphSchema( - parse(` - ${connect('v0.3', 'import: ["@connect", "URLTemplate"]')} - type Query { hello: String } - `), - ); - - expect(schema.getType('URLTemplate')).toBeDefined(); - expect(() => - buildSubgraphSchema( - parse(` - ${connect('v0.3', 'import: ["@connect", "URLPathTemplate"]')} - type Query { hello: String } - `), - ), - ).toThrow(UnsupportedLinkImportError); - }); - - it('rejects an import the connect specification does not define', () => { - expect(() => - buildSubgraphSchema( - parse(` - ${connect('v0.3', 'import: ["@connect", "@key"]')} - type Query { hello: String } - `), - ), - ).toThrow( - 'Cannot import "@key": it is not part of the connect specification v0.3.', - ); - }); - - it('rejects more than one connect @link', () => { - expect(() => - buildSubgraphSchema( - parse(` - ${connect()} - extend schema @link(url: "https://specs.apollo.dev/connect/v0.2") - type Query { hello: String } - `), - ), - ).toThrow(MultipleConnectLinksError); - }); - - it('leaves user-provided connect definitions alone', () => { - const schema = buildSubgraphSchema( - parse(` - ${connect()} - directive @connect(http: connect__ConnectHTTP, selection: String!) on FIELD_DEFINITION - type Query { - hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") - } - `), - ); - - expect(schema.getDirective('connect')!.args.map((arg) => arg.name)).toEqual( - ['http', 'selection'], - ); - }); - - it('defines the connect directives without a federation @link', () => { - const schema = buildSubgraphSchema( - parse(` - extend schema @link(url: "https://specs.apollo.dev/connect/v0.3", import: ["@connect"]) - type Query { - hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") - } - `), - ); - - expect(schema.getDirective('connect')).toBeDefined(); - expect(schema.getDirective('link')).toBeDefined(); - }); - - it('leaves validating connector usage to composition', () => { - // Two HTTP methods and `entity: true` on a non-`Query` field are both - // invalid connectors, but only composition reports that. - expect(() => - buildSubgraphSchema( - parse(` - ${connect()} - type Query { user: User } - type User { - id: ID! - name: String - @connect( - http: { GET: "https://a.example.com", POST: "https://b.example.com" } - selection: "name" - entity: true - ) - } - `), - ), - ).not.toThrow(); - }); - - it('still reports GraphQL errors in connect directive applications', () => { - expect(() => - buildSubgraphSchema( - parse(` - ${connect()} - type Query { - hello: String @connect(http: { GET: "https://api.example.com/hello" }) - } - `), - ), - ).toThrow( - /Directive "@connect" argument "selection" of type "connect__JSONSelection!" is required/, - ); - }); -}); - describe('Federation 1', () => { const fed1Schema = () => buildSubgraphSchema( diff --git a/src/__tests__/connectors.test.ts b/src/__tests__/connectors.test.ts new file mode 100644 index 0000000..0ec152d --- /dev/null +++ b/src/__tests__/connectors.test.ts @@ -0,0 +1,356 @@ +import { graphql, parse } from 'graphql'; +import { buildSubgraphSchema } from '../buildSubgraphSchema'; +import { + MultipleConnectLinksError, + UnsupportedConnectVersionError, + UnsupportedLinkImportError, +} from '../errors'; + +function serviceSdl(schema: Parameters[0]['schema']) { + return graphql({ schema, source: '{ _service { sdl } }' }).then((result) => { + expect(result.errors).toBeUndefined(); + return (result.data as any)._service.sdl as string; + }); +} + +describe('Apollo Connectors', () => { + const connect = ( + version = 'v0.3', + linkArguments = 'import: ["@connect", "@source"]', + ) => ` + extend schema + @link(url: "https://specs.apollo.dev/federation/v2.12", import: ["@key"]) + @link(url: "https://specs.apollo.dev/connect/${version}", ${linkArguments}) + `; + + const usersSchema = ` + extend schema + @source(name: "api", http: { baseURL: "https://api.example.com", headers: [{ name: "x-api-key", from: "x-api-key" }] }) + + type Query { + user(id: ID!): User + @connect( + source: "api" + http: { GET: "/users/{$args.id}" } + selection: "id name" + entity: true + ) + } + + type User @key(fields: "id") { + id: ID! + name: String + } + `; + + it('defines the imported connect directives', () => { + const schema = buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)); + + const connectDirective = schema.getDirective('connect')!; + expect(connectDirective.isRepeatable).toBe(true); + expect(connectDirective.locations).toEqual(['FIELD_DEFINITION', 'OBJECT']); + expect( + connectDirective.args.map((arg) => `${arg.name}: ${arg.type}`), + ).toEqual([ + 'source: String', + 'id: String', + 'http: connect__ConnectHTTP', + 'batch: connect__ConnectBatch', + 'errors: connect__ConnectorErrors', + 'selection: connect__JSONSelection!', + 'entity: Boolean', + 'isSuccess: connect__JSONSelection', + ]); + expect(schema.getDirective('source')!.locations).toEqual(['SCHEMA']); + }); + + it('publishes the connect definitions composition expects', async () => { + const sdl = await serviceSdl( + buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)), + ); + + expect(sdl).toContain( + 'directive @connect(source: String, id: String, http: connect__ConnectHTTP, batch: connect__ConnectBatch, errors: connect__ConnectorErrors, selection: connect__JSONSelection!, entity: Boolean = false, isSuccess: connect__JSONSelection) repeatable on FIELD_DEFINITION | OBJECT', + ); + expect(sdl).toContain( + 'directive @source(name: String!, http: connect__SourceHTTP!, errors: connect__ConnectorErrors, isSuccess: connect__JSONSelection) repeatable on SCHEMA', + ); + expect(sdl).toContain('scalar connect__JSONSelection'); + expect(sdl).toContain('scalar connect__URLTemplate'); + expect(sdl).toContain( + [ + 'input connect__ConnectorErrors {', + ' message: connect__JSONSelection', + ' extensions: connect__JSONSelection', + '}', + ].join('\n'), + ); + expect(sdl).toContain( + [ + 'input connect__HTTPHeaderMapping {', + ' name: String!', + ' from: String', + ' value: String', + '}', + ].join('\n'), + ); + expect(sdl).toContain( + ['input connect__ConnectBatch {', ' maxSize: Int', '}'].join('\n'), + ); + expect(sdl).toContain( + [ + 'input connect__SourceHTTP {', + ' baseURL: String!', + ' headers: [connect__HTTPHeaderMapping!]', + ' path: connect__JSONSelection', + ' queryParams: connect__JSONSelection', + '}', + ].join('\n'), + ); + expect(sdl).toContain( + [ + 'input connect__ConnectHTTP {', + ' GET: connect__URLTemplate', + ' POST: connect__URLTemplate', + ' PUT: connect__URLTemplate', + ' PATCH: connect__URLTemplate', + ' DELETE: connect__URLTemplate', + ' body: connect__JSONSelection', + ' headers: [connect__HTTPHeaderMapping!]', + ' path: connect__JSONSelection', + ' queryParams: connect__JSONSelection', + '}', + ].join('\n'), + ); + }); + + it('leaves the _service and _entities machinery out of _service { sdl }', async () => { + const schema = buildSubgraphSchema(parse(`${connect()} ${usersSchema}`)); + const sdl = await serviceSdl(schema); + + // Still served by the subgraph... + expect(schema.getQueryType()!.getFields()._service).toBeDefined(); + expect(schema.getQueryType()!.getFields()._entities).toBeDefined(); + // ...but composition rejects them in a connectors subgraph. + expect(sdl).not.toMatch(/_service|_entities|_Service|_Entity|_Any/); + expect(sdl).toMatch(/type User @key\(fields: "id"\)/); + expect(sdl).toMatch(/directive @connect\(/); + }); + + it('namespaces connect definitions that are not imported', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: ["@connect"]')} + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('connect')).toBeDefined(); + expect(schema.getDirective('source')).toBeUndefined(); + expect(schema.getDirective('connect__source')).toBeDefined(); + }); + + it('names @connect after the namespace when it is not imported', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: []')} + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('connect')).toBeDefined(); + expect(schema.getDirective('connect__connect')).toBeUndefined(); + expect(schema.getDirective('connect__source')).toBeDefined(); + expect(schema.getType('connect__ConnectHTTP')).toBeDefined(); + }); + + it('namespaces connect definitions under the @link alias', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'as: "rest"')} + type Query { + hello: String @rest(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('rest')).toBeDefined(); + expect(schema.getDirective('rest__connect')).toBeUndefined(); + expect(schema.getDirective('connect')).toBeUndefined(); + expect(schema.getDirective('rest__source')).toBeDefined(); + expect(schema.getType('rest__ConnectHTTP')).toBeDefined(); + }); + + it('supports renamed connect imports', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: [{ name: "@connect", as: "@http" }, "JSONSelection"]')} + type Query { + hello: String @http(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('http')).toBeDefined(); + expect(schema.getDirective('connect')).toBeUndefined(); + expect(schema.getType('JSONSelection')).toBeDefined(); + expect(String(schema.getDirective('http')!.args[5].type)).toBe( + 'JSONSelection!', + ); + }); + + it('accepts connectors on types and connectors without http', () => { + expect(() => + buildSubgraphSchema( + parse(` + ${connect('v0.4')} + type Query { + greeting(name: String!): String! @connect(selection: "$args.name") + } + type User + @connect(http: { GET: "https://api.example.com/users/{$this.id}" }, selection: "id name") + @connect(http: { GET: "https://api.example.com/users/{$this.id}/details" }, selection: "id email") + { + id: ID! + name: String + email: String + } + `), + ), + ).not.toThrow(); + }); + + it.each(['v0.1', 'v0.2', 'v0.3', 'v0.4'])( + 'supports connect %s', + (version) => { + const schema = buildSubgraphSchema( + parse(`${connect(version)} ${usersSchema}`), + ); + expect(schema.getDirective('connect')).toBeDefined(); + }, + ); + + it.each(['v0.0', 'v0.5', 'v1.0', 'latest', 'v0.3/'])( + 'rejects connect %s', + (version) => { + expect(() => + buildSubgraphSchema(parse(`${connect(version)} ${usersSchema}`)), + ).toThrow(UnsupportedConnectVersionError); + }, + ); + + it('imports the URLTemplate scalar under the name composition uses', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: ["@connect", "URLTemplate"]')} + type Query { hello: String } + `), + ); + + expect(schema.getType('URLTemplate')).toBeDefined(); + expect(() => + buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: ["@connect", "URLPathTemplate"]')} + type Query { hello: String } + `), + ), + ).toThrow(UnsupportedLinkImportError); + }); + + it('rejects an import the connect specification does not define', () => { + expect(() => + buildSubgraphSchema( + parse(` + ${connect('v0.3', 'import: ["@connect", "@key"]')} + type Query { hello: String } + `), + ), + ).toThrow( + 'Cannot import "@key": it is not part of the connect specification v0.3.', + ); + }); + + it('rejects more than one connect @link', () => { + expect(() => + buildSubgraphSchema( + parse(` + ${connect()} + extend schema @link(url: "https://specs.apollo.dev/connect/v0.2") + type Query { hello: String } + `), + ), + ).toThrow(MultipleConnectLinksError); + }); + + it('leaves user-provided connect definitions alone', () => { + const schema = buildSubgraphSchema( + parse(` + ${connect()} + directive @connect(http: connect__ConnectHTTP, selection: String!) on FIELD_DEFINITION + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('connect')!.args.map((arg) => arg.name)).toEqual( + ['http', 'selection'], + ); + }); + + it('defines the connect directives without a federation @link', () => { + const schema = buildSubgraphSchema( + parse(` + extend schema @link(url: "https://specs.apollo.dev/connect/v0.3", import: ["@connect"]) + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }, selection: "$") + } + `), + ); + + expect(schema.getDirective('connect')).toBeDefined(); + expect(schema.getDirective('link')).toBeDefined(); + }); + + it('leaves validating connector usage to composition', () => { + // Two HTTP methods and `entity: true` on a non-`Query` field are both + // invalid connectors, but only composition reports that. + expect(() => + buildSubgraphSchema( + parse(` + ${connect()} + type Query { user: User } + type User { + id: ID! + name: String + @connect( + http: { GET: "https://a.example.com", POST: "https://b.example.com" } + selection: "name" + entity: true + ) + } + `), + ), + ).not.toThrow(); + }); + + it('still reports GraphQL errors in connect directive applications', () => { + expect(() => + buildSubgraphSchema( + parse(` + ${connect()} + type Query { + hello: String @connect(http: { GET: "https://api.example.com/hello" }) + } + `), + ), + ).toThrow( + /Directive "@connect" argument "selection" of type "connect__JSONSelection!" is required/, + ); + }); +}); From 0caa694dc3e55e153fd920e87e2f1162c6f14dbb Mon Sep 17 00:00:00 2001 From: dariuszkuc <9501705+dariuszkuc@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:38:02 -0600 Subject: [PATCH 5/5] test: accept graphql v17 wording for missing required directive argument Co-Authored-By: Claude Opus 5.5 --- src/__tests__/connectors.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/__tests__/connectors.test.ts b/src/__tests__/connectors.test.ts index 0ec152d..473323d 100644 --- a/src/__tests__/connectors.test.ts +++ b/src/__tests__/connectors.test.ts @@ -350,7 +350,8 @@ describe('Apollo Connectors', () => { `), ), ).toThrow( - /Directive "@connect" argument "selection" of type "connect__JSONSelection!" is required/, + // graphql v16 and v17 word this error differently + /(Directive "@connect" argument "selection"|Argument "@connect\(selection:\)") of type "connect__JSONSelection!" is required/, ); }); });