// THE GRAPHQL WIRE — a vendor's GraphQL API served from its published schema over the pack's state // (docs/contributing/architecture.md, "Other wires: lanes, headers and line protocols": GraphQL). A query is parsed and // validated against the vendor's own schema, so an unknown field is the GraphQL error the vendor gives. A field resolves // from the pack's resolver when it writes one (`semantics/graphql.ts`), else from the object its parent resolved: the // field's own name, its snake_case form, or the pack's alias for it. A list answering a `…Connection` field is a Relay // connection, and an enum resolves case-insensitively. The wire takes a query only when every field it selects is // modeled; any other is answered by the manifest's `graphql.unmodeled`, naming the first field nothing models. An error // a resolver throws (`GraphqlError`) carries its `type`, as GitHub's GraphQL errors do. // // The generated pack fetch supplies a lazy pack-local loader for the `graphql` protocol library installed by the pack's // package.json. Each endpoint caches its library on the first request; callers without a loader keep the kernel-relative // lazy import fallback. The kernel's own dependencies stay B1's, and importing the kernel loads nothing. /** A resolver of one field, `Type.field`: its parent object, its arguments, and the request's handler context. */ export type GraphqlResolver = (source: Record, args: Record, ctx: C) => unknown; /** What a pack's `semantics/graphql.ts` exports as `graphql`. */ export type GraphqlPart = { /** The root operations derived from the SDL, for dispatch ownership and gap reporting. */ operations?: ReadonlyArray<{ id: string; kind: 'query' | 'mutation'; field: string }>; /** resolvers by `Type.field` (`Query.repository`, `PullRequest.state`) */ resolvers: Record>; /** per type, a GraphQL field name → the object's field that holds it (`nameWithOwner` → `full_name`) */ aliases?: Record>; /** per type, the object's fields the default resolver may read as they are */ stored?: Record; }; /** An error a resolver answers, with the vendor's `type` for it (GitHub's NOT_FOUND, UNPROCESSABLE). */ export class GraphqlError extends Error { constructor(message: string, readonly type?: string) { super(message); this.name = 'GraphqlError'; } } type GraphqlLib = typeof import('graphql'); export type GraphqlLibraryLoader = () => Promise; const snake = (s: string): string => s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`); /** A list as a Relay connection, paged by `first`/`last` and `after`. */ function connection(items: unknown[], args: Record): Record { const first = typeof args.first === 'number' ? args.first : undefined; const last = typeof args.last === 'number' ? args.last : undefined; const after = typeof args.after === 'string' ? Number(atob(args.after)) + 1 : 0; let slice = items.slice(after); if (first !== undefined) slice = slice.slice(0, first); if (last !== undefined) slice = slice.slice(-last); const start = after + (last !== undefined ? Math.max(0, items.slice(after).length - last) : 0); const cursor = (i: number): string => btoa(String(start + i)); return { totalCount: items.length, nodes: slice, edges: slice.map((node, i) => ({ node, cursor: cursor(i) })), pageInfo: { hasNextPage: start + slice.length < items.length, hasPreviousPage: start > 0, startCursor: slice.length ? cursor(0) : null, endCursor: slice.length ? cursor(slice.length - 1) : null }, }; } /** A GraphQL endpoint over a schema and a pack's part: answers a request's `{query, variables, operationName}`. The * context each resolver receives is made per request (the handler context). `unmodeled` answers a query selecting a * field nothing models; `mutationRefused`, when given, a mutation the World may not make (a read-only twin). */ export function graphqlEndpoint(options: { sdl: string; part: GraphqlPart; /** The generated pack fetch's lazy import, resolving the library from the pack that declares it. */ loadLibrary?: GraphqlLibraryLoader; context: (request: Request) => Promise; unmodeled: (field: { type: string; field: string }) => Response; mutationRefused?: (request: Request) => Response | undefined; }): (request: Request) => Promise { let lib: Promise | undefined; const loadLibrary = options.loadLibrary ?? (() => import('graphql')); let schema: import('graphql').GraphQLSchema | undefined; const { resolvers, aliases, stored } = options.part; // introspection (`__typename`, `__type`, `__schema` and the `__Type`/`__Field`/… meta types) is the vendor's schema // describing itself, answered by graphql-js from the SDL: modeled as the schema is (gh asks `__type(name:"PullRequest")` // before it merges) const modeled = (type: string, field: string): boolean => field.startsWith('__') || type.startsWith('__') || `${type}.${field}` in resolvers || !!aliases?.[type]?.[field] || !!stored?.[type]?.includes(field) || !!stored?.[type]?.includes(snake(field)); return async (request) => { const g = await (lib ??= loadLibrary()); schema ??= g.buildSchema(options.sdl, { assumeValidSDL: true }); const payload = (await request.clone().json().catch(() => ({}))) as { query?: string; variables?: Record; operationName?: string }; let document: import('graphql').DocumentNode; try { document = g.parse(payload.query ?? ''); } catch (error) { return Response.json({ errors: [{ message: error instanceof Error ? error.message : String(error) }] }); } const invalid = g.validate(schema, document); if (invalid.length) return Response.json({ errors: invalid.map((e) => ({ message: e.message, locations: e.locations })) }); const mutation = document.definitions.some((d) => d.kind === 'OperationDefinition' && d.operation === 'mutation'); if (mutation) { const refused = options.mutationRefused?.(request); if (refused) return refused; } const typeInfo = new g.TypeInfo(schema); let unmodeled: { type: string; field: string } | undefined; g.visit(document, g.visitWithTypeInfo(typeInfo, { Field(node) { const parent = typeInfo.getParentType(); if (!unmodeled && parent && g.isObjectType(parent) && !parent.name.endsWith('Connection') && !parent.name.endsWith('Edge') && parent.name !== 'PageInfo' && !modeled(parent.name, node.name.value)) unmodeled = { type: parent.name, field: node.name.value }; }, })); if (unmodeled) return options.unmodeled(unmodeled); const ctx = await options.context(request); const result = await g.execute({ schema, document, variableValues: payload.variables ?? {}, ...(payload.operationName ? { operationName: payload.operationName } : {}), contextValue: ctx, fieldResolver: async (source, args, context, info) => { const own = resolvers[`${info.parentType.name}.${info.fieldName}`]; const obj = (source ?? {}) as Record; let value = own ? await own(obj, args as Record, context as C) : (obj[aliases?.[info.parentType.name]?.[info.fieldName] ?? info.fieldName] ?? obj[snake(info.fieldName)] ?? null); const named = g.getNamedType(info.returnType); if (Array.isArray(value) && g.isObjectType(named) && named.name.endsWith('Connection')) value = connection(value, args as Record); if (typeof value === 'string' && g.isEnumType(named)) value = named.getValues().find((v) => v.name.toLowerCase() === String(value).toLowerCase())?.name ?? value; return value; }, }); const errors = (result.errors ?? []).map((e) => { const type = e.originalError instanceof GraphqlError ? e.originalError.type : typeof e.extensions?.type === 'string' ? e.extensions.type : undefined; return { ...(type ? { type } : {}), message: e.message, ...(e.path ? { path: e.path } : {}), ...(e.locations ? { locations: e.locations } : {}) }; }); return Response.json({ ...(result.data !== undefined ? { data: result.data } : {}), ...(errors.length ? { errors } : {}) }); }; }