@znight/graphql 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-BssB7wtn.mjs","names":["show","isRecord","identity"],"sources":["../src/loaders.ts","../src/pubsub.ts","../src/memory-pubsub.ts","../src/decisions.ts","../src/engine.ts","../src/options.ts","../src/pipeline.ts","../src/scalars.ts","../src/schema.ts","../src/results.ts","../src/transport/builtin.ts","../src/plugin.ts"],"sourcesContent":["/**\n * Loaders (RFC 0005 §5.5, §8.6): the DataLoader of a `BatchLoad` provider for one execution, and\n * `orderByKeys()`.\n *\n * The registry of an execution (`Map<token, DataLoader>`) lives in its `GraphQLContext` and is\n * created on the first `loader()` call: operations that use no loader allocate nothing.\n */\nimport type { Container, Token } from '@znight/core'\nimport type { BatchLoad, BatchLoader, LoaderOptions } from './types.ts'\n\nimport { ErrorCode, ZnightError } from '@znight/core'\nimport DataLoader from 'dataloader'\n\nimport { GraphQLErrorCode, GraphQLException } from './errors.ts'\n\n/** DataLoader options of a loader class, read once. */\ntype ResolvedLoaderOptions = DataLoader.Options<unknown, unknown, unknown>\n\n/**\n * Creates the per-execution DataLoaders of loader providers: the provider is resolved in the\n * current scope (loaders may be request-scoped), its `options` are read once per token.\n */\nexport class LoaderFactory {\n readonly #container: Container\n readonly #options = new Map<Token, ResolvedLoaderOptions>()\n\n constructor(container: Container) {\n this.#container = container\n }\n\n /** A new DataLoader for the loader provider `token`, bound to the instance of the current scope. */\n create(token: Token): BatchLoader<unknown, unknown> {\n const provider = this.#container.get(token) as Partial<BatchLoad<unknown, unknown>> | undefined\n if (provider === null || typeof provider !== 'object' || typeof provider.load !== 'function') {\n throw new ZnightError(\n ErrorCode.InvalidLoader,\n `The loader ${token} does not implement BatchLoad (no load(keys) method)`,\n { hints: ['A loader is a provider implementing BatchLoad<K, V>: async load(keys) { ... }'] },\n )\n }\n let options = this.#options.get(token)\n if (options === undefined) {\n options = readOptions(token, provider.options)\n this.#options.set(token, options)\n }\n return new DataLoader<unknown, unknown, unknown>(\n keys => loadBatch(token, keys, provider as BatchLoad<unknown, unknown>),\n options,\n ) as BatchLoader<unknown, unknown>\n }\n}\n\n/**\n * The values of a batch, or ZNIGHT065 (failing every key) when there is not one value per key.\n * `async` so that a `load()` throwing synchronously rejects with its own error (DataLoader would\n * replace it with a TypeError).\n */\nasync function loadBatch(\n token: Token,\n keys: readonly unknown[],\n provider: BatchLoad<unknown, unknown>,\n): Promise<readonly unknown[]> {\n const values: unknown = await provider.load(keys)\n if (Array.isArray(values) && values.length === keys.length) return values\n throw new ZnightError(\n ErrorCode.InvalidLoader,\n `The loader ${token} returned ${Array.isArray(values) ? `${values.length} values` : 'no array'} for ${keys.length} keys`,\n { hints: ['load(keys) returns one value (or Error) per key, in the order of the keys: use orderByKeys()'] },\n )\n}\n\nfunction readOptions(token: Token, options: LoaderOptions | undefined): ResolvedLoaderOptions {\n if (options === undefined) return {}\n const invalid = (reason: string): ZnightError =>\n new ZnightError(ErrorCode.InvalidLoader, `Invalid options of the loader ${token}: ${reason}`, {\n hints: ['options: { maxBatchSize?: positive integer, cache?: boolean, cacheKeyFn?: (key) => unknown }'],\n })\n if (options === null || typeof options !== 'object') throw invalid('expected an object')\n const { maxBatchSize, cache, cacheKeyFn } = options\n if (maxBatchSize !== undefined && !(Number.isSafeInteger(maxBatchSize) && maxBatchSize >= 1)) {\n throw invalid(`maxBatchSize must be a positive integer (received ${String(maxBatchSize)})`)\n }\n if (cache !== undefined && typeof cache !== 'boolean') throw invalid('cache must be a boolean')\n if (cacheKeyFn !== undefined && typeof cacheKeyFn !== 'function') throw invalid('cacheKeyFn must be a function')\n return {\n ...(maxBatchSize === undefined ? {} : { maxBatchSize }),\n ...(cache === undefined ? {} : { cache }),\n ...(cacheKeyFn === undefined ? {} : { cacheKeyFn: (key: unknown) => cacheKeyFn.call(options, key) }),\n }\n}\n\n/** Options of {@link orderByKeys}. */\nexport interface OrderByKeysOptions {\n /**\n * What a key without value gets: `'error'` (default) a `NOT_FOUND` `GraphQLException` failing that\n * key only, `'null'` the value `null`.\n */\n readonly missing?: 'error' | 'null'\n}\n\n/**\n * Reorders `values` (rows in any order, some keys possibly missing) to match `keys`, what a\n * `BatchLoad.load()` must return. Keys are compared with `Map` semantics (`===`, `NaN` equal).\n *\n * ```ts\n * async load(ids: readonly ID[]): Promise<readonly (Author | Error)[]> {\n * return orderByKeys(ids, await this.authors.findMany(ids), author => author.id)\n * }\n * ```\n */\nexport function orderByKeys<K, V>(\n keys: readonly K[],\n values: Iterable<V>,\n keyOf: (value: V) => K,\n options?: OrderByKeysOptions & { readonly missing?: 'error' },\n): (V | Error)[]\nexport function orderByKeys<K, V>(\n keys: readonly K[],\n values: Iterable<V>,\n keyOf: (value: V) => K,\n options: OrderByKeysOptions & { readonly missing: 'null' },\n): (V | null)[]\nexport function orderByKeys<K, V>(\n keys: readonly K[],\n values: Iterable<V>,\n keyOf: (value: V) => K,\n options: OrderByKeysOptions = {},\n): (V | Error | null)[] {\n const missing = options.missing ?? 'error'\n if (missing !== 'error' && missing !== 'null') {\n throw new TypeError(`orderByKeys(): missing must be 'error' or 'null' (received ${String(missing)})`)\n }\n const byKey = new Map<K, V>()\n for (const value of values) byKey.set(keyOf(value), value)\n const result: (V | Error | null)[] = new Array(keys.length)\n for (let index = 0; index < keys.length; index++) {\n const key = keys[index] as K\n const value = byKey.get(key)\n if (value !== undefined || byKey.has(key)) result[index] = value as V\n else result[index] = missing === 'null' ? null : notFound(key)\n }\n return result\n}\n\nfunction notFound(key: unknown): GraphQLException {\n return new GraphQLException(`Not found: ${typeof key === 'string' ? key : String(key)}`, {\n code: GraphQLErrorCode.NotFound,\n })\n}\n","/**\n * The `PubSub` contract (RFC 0005 §5.6, §8.7): topics and payloads of subscriptions. `PubSub` is\n * an injectable external of `GraphQLPlugin` (`@znight/graphql#PubSub`, singleton), in memory by\n * default; multi-instance deployments supply their own implementation through the `pubsub` option.\n */\n\n/** Options of {@link PubSub.subscribe}. */\nexport interface SubscribeOptions {\n /** Ends the subscription when it aborts (client gone, shutdown, `maxDuration`): pass `ctx.signal`. */\n readonly signal?: AbortSignal\n}\n\n/**\n * Publishes events to the subscribers of a topic. `Events` maps each topic to its payload type.\n *\n * ```ts\n * interface CatalogEvents {\n * bookAdded: Book\n * }\n *\n * constructor(private readonly events: PubSub<CatalogEvents>) {}\n *\n * await this.events.publish('bookAdded', book)\n * for await (const book of this.events.subscribe('bookAdded', { signal: ctx.signal })) yield book\n * ```\n */\nexport abstract class PubSub<Events extends object = Record<string, unknown>> {\n /** Delivers `payload` to the current subscribers of `topic`. */\n abstract publish<K extends keyof Events & string>(topic: K, payload: Events[K]): Promise<void>\n\n /** The events of `topic` published from now on, until `options.signal` aborts or the iterator returns. */\n abstract subscribe<K extends keyof Events & string>(\n topic: K,\n options?: SubscribeOptions,\n ): AsyncIterableIterator<Events[K]>\n}\n","/**\n * `MemoryPubSub` (RFC 0005 §5.6, §8.7): the in-process `PubSub` of `GraphQLPlugin`, one RFC 0006\n * `EventChannel` per subscriber.\n */\nimport type { SubscribeOptions } from './pubsub.ts'\n\nimport { EventChannel } from '@znight/http'\n\nimport { GraphQLErrorCode, GraphQLException } from './errors.ts'\nimport { PubSub } from './pubsub.ts'\n\n/** Options of {@link MemoryPubSub}. */\nexport interface MemoryPubSubOptions {\n /**\n * Events buffered per subscriber. A subscriber that falls further behind gets a final\n * `SUBSCRIPTION_OVERFLOW` error and its subscription ends. Default 100.\n */\n readonly bufferSize?: number\n}\n\nconst DEFAULT_BUFFER_SIZE = 100\nconst PUBLISHED: Promise<void> = Promise.resolve()\n\n/** One subscriber: its channel, and whether it overflowed. */\nclass Subscriber<T> implements AsyncIterableIterator<T> {\n readonly channel: EventChannel<T>\n readonly #iterator: AsyncIterator<T>\n overflowed = false\n\n constructor(channel: EventChannel<T>) {\n this.channel = channel\n this.#iterator = channel[Symbol.asyncIterator]()\n }\n\n async next(): Promise<IteratorResult<T>> {\n const step = await this.#iterator.next()\n if (step.done === true && this.overflowed) {\n this.overflowed = false\n throw new GraphQLException('The subscriber fell behind the events: the subscription ended', {\n code: GraphQLErrorCode.SubscriptionOverflow,\n })\n }\n return step\n }\n\n return(): Promise<IteratorResult<T>> {\n this.overflowed = false\n return this.#iterator.return?.() ?? Promise.resolve({ done: true, value: undefined })\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<T> {\n return this\n }\n}\n\n/**\n * In-process fan-out of events to subscribers: what `GraphQLPlugin` provides as `PubSub` by default.\n * Deployments with several instances supply their own `PubSub` (`pubsub` option).\n *\n * ```ts\n * GraphQLPlugin.configure({ pubsub: new MemoryPubSub({ bufferSize: 500 }) })\n * ```\n */\nexport class MemoryPubSub<Events extends object = Record<string, unknown>> extends PubSub<Events> {\n readonly #bufferSize: number\n readonly #topics = new Map<string, Set<Subscriber<unknown>>>()\n #closed = false\n\n constructor(options: MemoryPubSubOptions = {}) {\n super()\n const bufferSize = options.bufferSize ?? DEFAULT_BUFFER_SIZE\n if (!(Number.isSafeInteger(bufferSize) && bufferSize >= 1)) {\n throw new TypeError(`MemoryPubSub: bufferSize must be a positive integer (received ${String(bufferSize)})`)\n }\n this.#bufferSize = bufferSize\n }\n\n /** Subscribers of every topic. */\n get subscribers(): number {\n let count = 0\n for (const subscribers of this.#topics.values()) count += subscribers.size\n return count\n }\n\n publish<K extends keyof Events & string>(topic: K, payload: Events[K]): Promise<void> {\n const subscribers = this.#topics.get(topic)\n if (subscribers !== undefined) {\n for (const subscriber of subscribers) {\n const channel = subscriber.channel\n // `false` from an open channel is an overflow ('close'): it closes after its buffered events\n if (!channel.closed && !channel.push(payload)) subscriber.overflowed = true\n }\n }\n return PUBLISHED\n }\n\n subscribe<K extends keyof Events & string>(\n topic: K,\n options: SubscribeOptions = {},\n ): AsyncIterableIterator<Events[K]> {\n const channel = new EventChannel<Events[K]>({\n capacity: this.#bufferSize,\n overflow: 'close',\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n const subscriber = new Subscriber(channel)\n if (this.#closed) {\n channel.close()\n return subscriber\n }\n let subscribers = this.#topics.get(topic)\n if (subscribers === undefined) {\n subscribers = new Set()\n this.#topics.set(topic, subscribers)\n }\n const set = subscribers\n set.add(subscriber as Subscriber<unknown>)\n channel.onClose(() => {\n set.delete(subscriber as Subscriber<unknown>)\n if (set.size === 0 && this.#topics.get(topic) === set) this.#topics.delete(topic)\n })\n return subscriber\n }\n\n /** Ends every subscription; later subscriptions end at once. */\n close(): void {\n this.#closed = true\n for (const subscribers of [...this.#topics.values()]) {\n for (const subscriber of [...subscribers]) subscriber.channel.close()\n }\n this.#topics.clear()\n }\n}\n","/**\n * The boot check of route decisions on GraphQL fields (RFC 0001 §5.2, RFC 0005 §5.9): every root\n * field decides every required group, and every decision of a required or enforced group is\n * enforced by a guard of the field's chain (`static enforces`). Problems are one ZNIGHT023 error\n * (`enforcement: 'error'`) or one warning per group.\n *\n * A small re-implementation of `@znight/http`'s internal checker for fields instead of routes.\n */\nimport type { CoreLogger } from '@znight/core'\nimport type { HttpRouteGroupDefinition, RouteDecoratorInfo } from '@znight/http'\n\nimport { ErrorCode, ZnightError } from '@znight/core'\n\n/** A resolver-backed field as seen by the check. */\nexport interface CheckedField {\n /** `Query.books (BookResolver.books)`. */\n readonly description: string\n /** Root fields must decide every required group. */\n readonly root: boolean\n /** Effective metadata. */\n readonly meta: Readonly<Record<string, unknown>>\n /** Guard classes of its chain (global when they apply, class, method); instances give their constructor. */\n readonly guards: readonly { readonly cls: unknown; readonly name: string }[]\n}\n\ninterface GroupInfo {\n readonly group: string\n readonly required: boolean\n}\n\n/** The groups listed by `static enforces` of a guard class (ZNIGHT005 when malformed). */\nexport function enforcedBy(guard: unknown, name: string): readonly RouteDecoratorInfo[] {\n if (typeof guard !== 'function') return []\n let enforces: unknown\n try {\n enforces = (guard as { enforces?: unknown }).enforces\n } catch (error) {\n throw invalidEnforces(name, 'reading it threw', error)\n }\n if (enforces === undefined) return []\n if (!Array.isArray(enforces)) throw invalidEnforces(name, 'expected an array of route decorators')\n for (const entry of enforces as unknown[]) {\n const info = (typeof entry === 'function' || (typeof entry === 'object' && entry !== null) ? entry : {}) as {\n key?: unknown\n group?: unknown\n required?: unknown\n }\n if (typeof info.key !== 'string' || typeof info.group !== 'string' || typeof info.required !== 'boolean') {\n throw invalidEnforces(name, 'every entry must be a route decorator ({ key, group, required })')\n }\n }\n return enforces as readonly RouteDecoratorInfo[]\n}\n\nfunction invalidEnforces(name: string, reason: string, cause?: unknown): ZnightError {\n return new ZnightError(\n ErrorCode.InvalidDecorator,\n `GraphQLPlugin: invalid static enforces of the guard ${name}: ${reason}`,\n {\n hints: [\n 'static readonly enforces = [Public, Authenticated, Roles] (decorators created with createRouteDecorator)',\n ],\n ...(cause === undefined ? {} : { cause }),\n },\n )\n}\n\n/** Runs the check. `groups`: `metadata.extensions.graphql.groups`. */\nexport function checkFieldDecisions(\n fields: readonly CheckedField[],\n groups: Readonly<Record<string, HttpRouteGroupDefinition>> | undefined,\n mode: 'error' | 'warn',\n logger: CoreLogger,\n): void {\n const keys = new Map<string, GroupInfo>()\n const required = new Set<string>()\n for (const [group, definition] of Object.entries(groups ?? {})) {\n for (const key of definition.keys) keys.set(key, { group, required: definition.required })\n if (definition.required) required.add(group)\n }\n const enforcedOf = new Map<unknown, ReadonlySet<string>>()\n const enforced = (guard: { readonly cls: unknown; readonly name: string }): ReadonlySet<string> => {\n let groupsOf = enforcedOf.get(guard.cls)\n if (groupsOf === undefined) {\n const infos = enforcedBy(guard.cls, guard.name)\n for (const info of infos) {\n if (!keys.has(info.key)) keys.set(info.key, { group: info.group, required: info.required })\n if (info.required) required.add(info.group)\n }\n groupsOf = new Set(infos.map(info => info.group))\n enforcedOf.set(guard.cls, groupsOf)\n }\n return groupsOf\n }\n const chains = fields.map(field => {\n const set = new Set<string>()\n for (const guard of field.guards) for (const group of enforced(guard)) set.add(group)\n return set\n })\n const known = new Set<string>()\n for (const chain of chains) for (const group of chain) known.add(group)\n const groupOf = (key: string): string => keys.get(key)?.group ?? key\n\n const problems = new Map<string, { missing: string[]; unenforced: string[] }>()\n const problem = (group: string): { missing: string[]; unenforced: string[] } => {\n let entry = problems.get(group)\n if (entry === undefined) {\n entry = { missing: [], unenforced: [] }\n problems.set(group, entry)\n }\n return entry\n }\n fields.forEach((field, index) => {\n const decided = new Set(Object.keys(field.meta).map(groupOf))\n if (field.root) {\n for (const group of required) if (!decided.has(group)) problem(group).missing.push(field.description)\n }\n const chain = chains[index] as Set<string>\n for (const group of decided) {\n if ((required.has(group) || known.has(group)) && !chain.has(group))\n problem(group).unenforced.push(field.description)\n }\n })\n if (problems.size === 0) return\n const messages: string[] = []\n const hints: string[] = []\n for (const group of [...problems.keys()].sort()) {\n const entry = problems.get(group) as { missing: string[]; unenforced: string[] }\n const members = [...keys]\n .filter(([, info]) => info.group === group)\n .map(([key]) => key)\n .sort()\n const parts: string[] = []\n if (entry.missing.length > 0) {\n parts.push(\n `${count(entry.missing.length)} ${entry.missing.length === 1 ? 'has' : 'have'} no \"${group}\" decision: ${entry.missing.join(', ')}`,\n )\n hints.push(\n `Add a decision of the \"${group}\" group (${members.join(', ') || group}) to the resolver method or to its class`,\n )\n }\n if (entry.unenforced.length > 0) {\n parts.push(\n `no guard enforces the \"${group}\" group on ${count(entry.unenforced.length)}: ${entry.unenforced.join(', ')}`,\n )\n hints.push(\n `Register a GraphQL guard declaring \\`static enforces\\` with the decorators of the \"${group}\" group: GraphQLPlugin.configure({ guards: [...] }) or @UseGuard(...)`,\n )\n }\n const message = parts.join('; ')\n if (mode === 'warn') logger.warn(`GraphQLPlugin: ${message}`, { code: ErrorCode.MissingRouteDecision, group })\n else messages.push(message)\n }\n if (mode === 'error') {\n hints.push(\"Tests that deliberately run without guards can set enforcement: 'warn'\")\n const text = messages.join('; ')\n throw new ZnightError(\n ErrorCode.MissingRouteDecision,\n `GraphQLPlugin: ${text.charAt(0).toUpperCase()}${text.slice(1)}`,\n {\n hints,\n },\n )\n }\n}\n\nfunction count(fields: number): string {\n return fields === 1 ? '1 field' : `${fields} fields`\n}\n","/**\n * The GraphQL engine (RFC 0009 §4.2): what a GraphQL server (a driver) calls to run Znight's\n * schema. Its functions have the shape of graphql-js's (`parse`, `validate`, `execute`,\n * `subscribe`), so they fit Envelop's `useEngine`, `graphql-ws`, `graphql-sse` and `graphql-http`\n * handlers as they are, and they keep everything `GraphQLPlugin` guarantees: the document cache and\n * limits, the request scope and `GraphQLContext`, guards, loaders, result mappers, error mapping\n * and masking, the subscriptions cap and the `graphql:operation` hook.\n *\n * A layer over the internal `GraphQLExecutor`: the built-in transport keeps calling the executor\n * directly, so the engine costs nothing to an application without driver.\n */\nimport type { ByteSize } from '@znight/http'\nimport type {\n DocumentNode,\n ExecutionArgs,\n ExecutionResult,\n GraphQLError,\n GraphQLSchema,\n Source,\n ValidationRule,\n} from 'graphql'\nimport type { EngineStream, ExecuteOptions, GraphQLExecutor } from './execution.ts'\n\n/** A value of type `T` or a promise of it (graphql-js `PromiseOrValue`). */\ntype PromiseOrValue<T> = T | Promise<T>\n\n/** Options of {@link GraphQLEngine.execute} and {@link GraphQLEngine.subscribe}. */\nexport interface EngineExecuteOptions {\n /**\n * The protocol that carried the operation (`GraphQLOperationEvent.transport`,\n * `GraphQLContext.transport`): `'http'` (default), `'sse'` for an event stream, `'ws'` for\n * `graphql-ws`.\n */\n readonly transport?: 'http' | 'sse' | 'ws'\n /**\n * Cancels the operation (graphql-js `abortSignal`, `GraphQLContext.signal`). Default:\n * `ExecutionArgs.abortSignal`, else the signal of the HTTP request of the current scope.\n */\n readonly signal?: AbortSignal\n /** `GraphQLContext.requestId`. Default: the request id of the HTTP request of the scope. */\n readonly requestId?: string\n}\n\n/** The resolved options a GraphQL server needs to configure itself (read-only). */\nexport interface GraphQLEngineSettings {\n /** The endpoint path, the `HttpPlugin` prefix included (`/api/graphql`). */\n readonly path: string\n readonly introspection: boolean\n /** The `graphiql` option: serve the server's IDE. */\n readonly ide: boolean\n readonly exposeErrors: boolean\n /** `limits.maxTokens`, for servers that parse documents themselves. */\n readonly maxTokens: number | undefined\n readonly subscriptions: false | { readonly maxActive: number }\n readonly http: false | { readonly get: boolean; readonly bodyLimit: ByteSize }\n}\n\n/**\n * The engine of a bootstrapped `GraphQLPlugin` (`plugin.engine`, and the first argument of\n * `GraphQLDriver.start()`). Its functions are bound: pass them around as they are.\n *\n * ```ts\n * const handler = createHandler({\n * schema: engine.schema,\n * parse: engine.parse,\n * validate: engine.validate,\n * execute: args => engine.execute(args),\n * })\n * ```\n */\nexport interface GraphQLEngine {\n /** The executable schema: its resolvers are Znight's pipelines. */\n readonly schema: GraphQLSchema\n readonly settings: GraphQLEngineSettings\n /**\n * graphql-js `parse` through the document cache: `maxTokens`, then the depth, aliases and\n * directives limits. Throws a `GraphQLError` (`GRAPHQL_PARSE_FAILED`, `QUERY_TOO_COMPLEX`), like\n * graphql-js. A text the engine validated returns the same `DocumentNode`.\n */\n parse(source: string | Source): DocumentNode\n /**\n * graphql-js `validate` with `rules` (default: graphql-js `specifiedRules`), to which the engine\n * adds its own ({@link rules}), with `hideSuggestions` when introspection is off. With the\n * default rules on {@link schema}, a document is validated once (then cached).\n */\n validate(schema: GraphQLSchema, document: DocumentNode, rules?: readonly ValidationRule[]): readonly GraphQLError[]\n /** The engine's own rules (limits, introspection), for servers that validate documents themselves. */\n readonly rules: readonly ValidationRule[]\n /**\n * Executes a validated query or mutation in the current request scope (or a scope of its own),\n * with the operation's `GraphQLContext` as `contextValue` (`args.contextValue` becomes\n * `GraphQLContext.serverContext`). Errors are mapped and masked, as `GraphQLError` instances.\n */\n execute(args: ExecutionArgs, options?: EngineExecuteOptions): PromiseOrValue<ExecutionResult>\n /**\n * Starts a validated subscription: a stream of results, or a single error result (rejected, past\n * `subscriptions.maxActive`, a source that could not start). The plugin ends the stream when the\n * application stops.\n */\n subscribe(\n args: ExecutionArgs,\n options?: EngineExecuteOptions,\n ): PromiseOrValue<AsyncGenerator<ExecutionResult, void, void> | ExecutionResult>\n}\n\n/** The engine of a plugin: bound functions over its executor. */\nexport class Engine implements GraphQLEngine {\n readonly schema: GraphQLSchema\n readonly settings: GraphQLEngineSettings\n readonly rules: readonly ValidationRule[]\n readonly parse: (source: string | Source) => DocumentNode\n readonly validate: (\n schema: GraphQLSchema,\n document: DocumentNode,\n rules?: readonly ValidationRule[],\n ) => readonly GraphQLError[]\n readonly execute: (args: ExecutionArgs, options?: EngineExecuteOptions) => PromiseOrValue<ExecutionResult>\n readonly subscribe: (args: ExecutionArgs, options?: EngineExecuteOptions) => Promise<EngineStream | ExecutionResult>\n\n constructor(executor: GraphQLExecutor, settings: GraphQLEngineSettings, driver: string) {\n this.schema = executor.schema\n this.settings = Object.freeze({ ...settings })\n this.rules = executor.engineRules\n // extra arguments of graphql-js (parse options, validation options) are not used: the engine's apply\n this.parse = source => executor.parseDocument(source, driver)\n this.validate = (schema, document, rules) => executor.validateDocument(schema, document, rules, driver)\n this.execute = (args, options) => executor.executeDocument(args, executeOptions(args, options, driver))\n this.subscribe = (args, options) => executor.subscribeDocument(args, executeOptions(args, options, driver))\n }\n}\n\nfunction executeOptions(\n args: ExecutionArgs,\n options: EngineExecuteOptions | undefined,\n driver: string,\n): ExecuteOptions {\n const signal = options?.signal ?? args?.abortSignal ?? undefined\n const requestId = options?.requestId\n return {\n transport: options?.transport ?? 'http',\n driver,\n serverContext: args?.contextValue,\n ...(signal === undefined ? {} : { signal }),\n ...(requestId === undefined ? {} : { requestId }),\n }\n}\n","/**\n * Options of `GraphQLPlugin` (RFC 0005 §5.11): their types, defaults and validation (ZNIGHT066).\n */\nimport type { ByteSize, GuardRef, RouteMetaEntry } from '@znight/http'\nimport type { GraphQLDriver } from './driver.ts'\nimport type { SubscribeOptions } from './pubsub.ts'\nimport type {\n GraphQLErrorMapper,\n GraphQLErrorMapperClass,\n GraphQLGuard,\n GraphQLGuardClass,\n GraphQLResultMapper,\n GraphQLResultMapperClass,\n GraphQLResultTypes,\n} from './types.ts'\n\nimport { ErrorCode, ZnightError } from '@znight/core'\nimport { parseByteSize } from '@znight/http'\n\n/**\n * A `PubSub` of any event map, for the `pubsub` option: `PubSub<Events>` types are not assignable\n * to each other (generic methods over `keyof Events`), so the option accepts the structure.\n */\nexport interface AnyPubSub {\n publish(topic: never, payload: never): Promise<void>\n subscribe(topic: never, options?: SubscribeOptions): AsyncIterableIterator<unknown>\n}\n\n/** A global GraphQL guard: a provider class or an instance. */\nexport type GraphQLGuardRef = GraphQLGuardClass | GraphQLGuard\n\n/** An error mapper: a provider class or an instance. */\nexport type GraphQLErrorMapperRef = GraphQLErrorMapperClass | GraphQLErrorMapper\n\n/**\n * A result mapper: a provider class with `static types`, or an instance (its `types` property, or the\n * `static types` of its class).\n */\nexport type GraphQLResultMapperRef = GraphQLResultMapperClass | (GraphQLResultMapper & Partial<GraphQLResultTypes>)\n\n/** Options of the GraphQL-over-HTTP endpoint. */\nexport interface GraphQLHttpOptions {\n /** Route metadata of the endpoint (`[Public.meta()]`), seen by HTTP guards and the route decision check. */\n readonly meta?: readonly RouteMetaEntry[]\n /** Guards of the endpoint (HTTP `CanActivate`), after the global `HttpPlugin` guards. */\n readonly guards?: readonly GuardRef[]\n /** Body limit of the endpoint. Default `'100kb'`. */\n readonly bodyLimit?: ByteSize\n /** Queries over `GET`. Default `true`. */\n readonly get?: boolean\n}\n\n/** Request limits; `false` disables one. */\nexport interface GraphQLLimits {\n /** Tokens of a document (`parse`). Default 2 000. */\n readonly maxTokens?: number | false\n /** Field nesting of an operation (introspection fields exempt). Default 12. */\n readonly maxDepth?: number | false\n /**\n * Aliases of a document, as written and as one operation executes them (a fragment spread several\n * times counts each time). Default 30.\n */\n readonly maxAliases?: number | false\n /** Directives of a document. Default 50. */\n readonly maxDirectives?: number | false\n}\n\n/** Subscription options. */\nexport interface GraphQLSubscriptionOptions {\n /** Active subscriptions cap (every transport); beyond it, 503. Default 10 000. */\n readonly maxActive?: number\n /** Events buffered per subscriber by the default `MemoryPubSub`. Default 100. */\n readonly bufferSize?: number\n /**\n * SSE heartbeat (ms), `false` for none. Default: the `HttpPlugin` `sse` option. Built-in transport\n * only: with a `driver`, its own keep-alive options apply (ZNIGHT066).\n */\n readonly heartbeat?: number | false\n /** SSE maximum duration (ms). Default: none. Built-in transport only (ZNIGHT066 with a `driver`). */\n readonly maxDuration?: number\n}\n\n/** Options of `GraphQLPlugin.configure()`. */\nexport interface GraphQLPluginOptions {\n /** Path of the endpoint, joined with the `HttpPlugin` prefix. Default `'/graphql'`. */\n readonly path?: string\n /** `false`: no HTTP transport (schema, `execute()` and `subscribe()` only). Default `{}`. */\n readonly http?: GraphQLHttpOptions | false\n /** Global GraphQL guards (classes or instances): root fields, and field resolvers with metadata. */\n readonly guards?: readonly GraphQLGuardRef[]\n /** Error mappers (classes or instances), tried in order. */\n readonly errorMappers?: readonly GraphQLErrorMapperRef[]\n /**\n * Result mappers (classes or instances), tried in order: errors as data (RFC 0008), on the fields\n * whose union holds one of their `types`.\n */\n readonly resultMappers?: readonly GraphQLResultMapperRef[]\n /** Unmasked messages for unexpected errors (development). Default `false`. */\n readonly exposeErrors?: boolean\n /** Introspection; off, suggestions are hidden too. Default `NODE_ENV !== 'production'`. */\n readonly introspection?: boolean\n /**\n * GraphiQL on `GET path` with `accept: text/html`; with a `driver`, the driver's IDE. Default\n * `NODE_ENV === 'development'`.\n */\n readonly graphiql?: boolean\n readonly limits?: GraphQLLimits\n /** Distinct documents kept parsed and validated (LRU); 0 disables the cache. Default 1 000. */\n readonly documentCache?: number\n /** `false` disables subscriptions over SSE (with a `driver`, subscriptions altogether). */\n readonly subscriptions?: GraphQLSubscriptionOptions | false\n /** The `PubSub` provided to the container. Default: a `MemoryPubSub` (closed with the application). */\n readonly pubsub?: AnyPubSub\n /**\n * How the boot check of route decisions on GraphQL fields (RFC 0001, ZNIGHT023) reports problems:\n * `'error'` (default) fails the boot, `'warn'` logs.\n */\n readonly enforcement?: 'error' | 'warn'\n /**\n * The GraphQL server serving the schema (RFC 0009): a driver of a subpath (`yogaDriver()`) or a\n * third party's. Default: the built-in GraphQL-over-HTTP and SSE transport, the fastest.\n */\n readonly driver?: GraphQLDriver\n}\n\n/** Options with their defaults, validated. */\nexport interface ResolvedGraphQLOptions {\n readonly path: string\n readonly http: Required<GraphQLHttpOptions> | false\n readonly guards: readonly GraphQLGuardRef[]\n readonly errorMappers: readonly GraphQLErrorMapperRef[]\n readonly resultMappers: readonly GraphQLResultMapperRef[]\n readonly exposeErrors: boolean\n readonly introspection: boolean\n readonly graphiql: boolean\n readonly limits: {\n readonly maxTokens: number | undefined\n readonly maxDepth: number | undefined\n readonly maxAliases: number | undefined\n readonly maxDirectives: number | undefined\n }\n readonly documentCache: number\n readonly subscriptions:\n | {\n readonly maxActive: number\n readonly bufferSize: number\n readonly heartbeat: number | false | undefined\n readonly maxDuration: number | undefined\n }\n | false\n readonly bufferSize: number\n readonly pubsub: AnyPubSub | undefined\n readonly enforcement: 'error' | 'warn'\n /** `undefined`: the built-in transport. */\n readonly driver: GraphQLDriver | undefined\n}\n\nconst KEYS: ReadonlySet<string> = new Set([\n 'path',\n 'http',\n 'guards',\n 'errorMappers',\n 'resultMappers',\n 'exposeErrors',\n 'introspection',\n 'graphiql',\n 'limits',\n 'documentCache',\n 'subscriptions',\n 'pubsub',\n 'enforcement',\n 'driver',\n])\nconst PATH = /^\\/[A-Za-z0-9\\-._~!$&'()*+,;=:@/]*$/\nconst LIMIT_DEFAULTS = { maxTokens: 2000, maxDepth: 12, maxAliases: 30, maxDirectives: 50 } as const\n\nfunction show(value: unknown): string {\n if (typeof value === 'function') return 'a function'\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return typeof value\n }\n}\n\n/** ZNIGHT066 for an invalid option. */\nexport function invalidOption(name: string, expected: string, received: unknown): ZnightError {\n return new ZnightError(\n ErrorCode.InvalidGraphQLSetup,\n `GraphQLPlugin: invalid option ${name}: expected ${expected} (received ${show(received)})`,\n { hints: ['See the options of GraphQLPlugin.configure() (RFC 0005 §5.11)'] },\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction boolean(name: string, value: unknown, fallback: boolean): boolean {\n if (value === undefined) return fallback\n if (typeof value !== 'boolean') throw invalidOption(name, 'a boolean', value)\n return value\n}\n\nfunction positiveInteger(name: string, value: unknown, fallback: number): number {\n if (value === undefined) return fallback\n if (!(Number.isSafeInteger(value) && (value as number) >= 1)) throw invalidOption(name, 'a positive integer', value)\n return value as number\n}\n\nfunction limit(name: keyof typeof LIMIT_DEFAULTS, value: unknown): number | undefined {\n if (value === false) return undefined\n return positiveInteger(`limits.${name}`, value, LIMIT_DEFAULTS[name])\n}\n\n/** Refs given as classes or instances with `method`. */\nfunction refs<T>(name: string, value: unknown, method: string): readonly T[] {\n if (value === undefined) return []\n if (!Array.isArray(value))\n throw invalidOption(name, `an array of classes or objects with a ${method}() method`, value)\n for (const ref of value) {\n const ok =\n typeof ref === 'function' ||\n (ref !== null && typeof ref === 'object' && typeof (ref as Record<string, unknown>)[method] === 'function')\n if (!ok) throw invalidOption(name, `classes or objects with a ${method}() method`, ref)\n }\n return value as readonly T[]\n}\n\n/** Validates the options and applies the defaults (`env`: `process.env`). */\nexport function resolveGraphQLOptions(\n options: unknown,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedGraphQLOptions {\n if (!isRecord(options)) throw invalidOption('options', 'an object', options)\n for (const key of Object.keys(options)) {\n if (!KEYS.has(key)) throw invalidOption(key, `one of ${[...KEYS].join(', ')}`, key)\n }\n const nodeEnv = env['NODE_ENV']\n const path = options['path'] ?? '/graphql'\n if (typeof path !== 'string' || !PATH.test(path)) throw invalidOption('path', \"a path starting with '/'\", path)\n\n const rawHttp = options['http'] ?? {}\n let http: ResolvedGraphQLOptions['http']\n if (rawHttp === false) {\n http = false\n } else {\n if (!isRecord(rawHttp)) throw invalidOption('http', 'false or { meta?, guards?, bodyLimit?, get? }', rawHttp)\n const meta = rawHttp['meta'] ?? []\n if (\n !Array.isArray(meta) ||\n !meta.every(entry => isRecord(entry) && typeof entry['key'] === 'string' && entry['key'] !== '')\n ) {\n throw invalidOption('http.meta', 'an array of route metadata entries (Decorator.meta())', meta)\n }\n const bodyLimit = rawHttp['bodyLimit'] ?? '100kb'\n if (parseByteSize(bodyLimit) === undefined)\n throw invalidOption('http.bodyLimit', \"a byte size ('100kb', 1048576)\", bodyLimit)\n http = {\n meta: meta as readonly RouteMetaEntry[],\n guards: refs<GuardRef>('http.guards', rawHttp['guards'], 'canActivate'),\n bodyLimit: bodyLimit as ByteSize,\n get: boolean('http.get', rawHttp['get'], true),\n }\n }\n\n const rawLimits = options['limits'] ?? {}\n if (!isRecord(rawLimits))\n throw invalidOption('limits', '{ maxTokens?, maxDepth?, maxAliases?, maxDirectives? }', rawLimits)\n for (const key of Object.keys(rawLimits)) {\n if (!(key in LIMIT_DEFAULTS))\n throw invalidOption(`limits.${key}`, 'maxTokens, maxDepth, maxAliases or maxDirectives', key)\n }\n\n const documentCache = options['documentCache'] ?? 1000\n if (!(Number.isSafeInteger(documentCache) && (documentCache as number) >= 0)) {\n throw invalidOption('documentCache', 'a non-negative integer', documentCache)\n }\n\n const rawSubscriptions = options['subscriptions'] ?? {}\n let subscriptions: ResolvedGraphQLOptions['subscriptions']\n let bufferSize = 100\n if (rawSubscriptions === false) {\n subscriptions = false\n } else {\n if (!isRecord(rawSubscriptions)) {\n throw invalidOption(\n 'subscriptions',\n 'false or { maxActive?, bufferSize?, heartbeat?, maxDuration? }',\n rawSubscriptions,\n )\n }\n bufferSize = positiveInteger('subscriptions.bufferSize', rawSubscriptions['bufferSize'], 100)\n const heartbeat = rawSubscriptions['heartbeat']\n if (heartbeat !== undefined && heartbeat !== false && !(typeof heartbeat === 'number' && heartbeat > 0)) {\n throw invalidOption('subscriptions.heartbeat', 'a positive number of milliseconds or false', heartbeat)\n }\n const maxDuration = rawSubscriptions['maxDuration']\n if (maxDuration !== undefined && !(typeof maxDuration === 'number' && maxDuration > 0)) {\n throw invalidOption('subscriptions.maxDuration', 'a positive number of milliseconds', maxDuration)\n }\n subscriptions = {\n maxActive: positiveInteger('subscriptions.maxActive', rawSubscriptions['maxActive'], 10_000),\n bufferSize,\n heartbeat: heartbeat as number | false | undefined,\n maxDuration: maxDuration as number | undefined,\n }\n }\n\n const pubsub = options['pubsub']\n if (\n pubsub !== undefined &&\n !(\n isRecord(pubsub) &&\n typeof (pubsub as { publish?: unknown }).publish === 'function' &&\n typeof (pubsub as { subscribe?: unknown }).subscribe === 'function'\n )\n ) {\n throw invalidOption('pubsub', 'a PubSub (publish() and subscribe() methods)', pubsub)\n }\n const enforcement = options['enforcement'] ?? 'error'\n if (enforcement !== 'error' && enforcement !== 'warn')\n throw invalidOption('enforcement', \"'error' or 'warn'\", enforcement)\n\n const driver = resolveDriver(options['driver'])\n if (driver !== undefined && subscriptions !== false) {\n for (const key of ['heartbeat', 'maxDuration'] as const) {\n if (subscriptions[key] !== undefined) {\n throw new ZnightError(\n ErrorCode.InvalidGraphQLSetup,\n `GraphQLPlugin: subscriptions.${key} configures the built-in SSE transport, not the ${driver.name} driver`,\n { hints: [`Remove subscriptions.${key}: the ${driver.name} driver's own keep-alive options apply`] },\n )\n }\n }\n }\n\n return {\n path,\n http,\n guards: refs<GraphQLGuardRef>('guards', options['guards'], 'canResolve'),\n errorMappers: refs<GraphQLErrorMapperRef>('errorMappers', options['errorMappers'], 'map'),\n resultMappers: refs<GraphQLResultMapperRef>('resultMappers', options['resultMappers'], 'toResult'),\n exposeErrors: boolean('exposeErrors', options['exposeErrors'], false),\n introspection: boolean('introspection', options['introspection'], nodeEnv !== 'production'),\n graphiql: boolean('graphiql', options['graphiql'], nodeEnv === 'development'),\n limits: {\n maxTokens: limit('maxTokens', rawLimits['maxTokens']),\n maxDepth: limit('maxDepth', rawLimits['maxDepth']),\n maxAliases: limit('maxAliases', rawLimits['maxAliases']),\n maxDirectives: limit('maxDirectives', rawLimits['maxDirectives']),\n },\n documentCache: documentCache as number,\n subscriptions,\n bufferSize,\n pubsub: pubsub as AnyPubSub | undefined,\n enforcement,\n driver,\n }\n}\n\n/** The `driver` option: an object with a `name` (not `builtin`) and `start()`, `routes()` and `stop()` functions when present. */\nfunction resolveDriver(value: unknown): GraphQLDriver | undefined {\n if (value === undefined) return undefined\n const expected = 'a GraphQL driver ({ name, start(), routes?(), stop?() }, from yogaDriver() for instance)'\n if (value === null || typeof value !== 'object') throw invalidOption('driver', expected, value)\n const driver = value as Record<string, unknown>\n const name = driver['name']\n if (typeof name !== 'string' || name === '') throw invalidOption('driver', `${expected} with a name`, value)\n if (name === 'builtin') {\n throw invalidOption('driver.name', \"a name other than 'builtin' (reserved for the built-in transport)\", name)\n }\n if (typeof driver['start'] !== 'function') throw invalidOption('driver', `${expected} with a start() method`, value)\n for (const method of ['routes', 'stop']) {\n if (driver[method] !== undefined && typeof driver[method] !== 'function') {\n throw invalidOption(`driver.${method}`, 'a function', driver[method])\n }\n }\n return value as GraphQLDriver\n}\n","/**\n * The resolver pipeline (RFC 0005 §5.9, §7.3, §8.5): the resolve function of every resolver-backed\n * field, decided once at boot.\n *\n * 1. the resolver instance: the singleton resolved at boot, or `container.get(token)` in the\n * current scope (request-scoped and transient resolvers);\n * 2. guards: global ones (on root fields, and on field resolvers carrying their own metadata), class\n * `@UseGuard`, method `@UseGuard`; `false` fails the field with `FORBIDDEN`;\n * 3. null handling of arguments (`nullAsUndefined`), only where a flag is reachable;\n * 4. `invoke(resolver, parent, args, context, info)`.\n *\n * A field without guards nor normaliser calls `invoke` from the closure graphql-js needs anyway:\n * no extra wrapper, no promise, no `await`. Plain property fields keep graphql-js' default resolver.\n * A field that carries results (RFC 0008, `results.ts`) gets one wrapper around the whole pipeline,\n * catching its errors to turn them into values; no other field does.\n */\nimport type { Container, Token } from '@znight/core'\nimport type { GraphQLFieldResolver, GraphQLResolveInfo } from 'graphql'\nimport type { OperationContext } from './context.ts'\nimport type { Resolvable } from './format.ts'\nimport type {\n GraphQLArgumentDefinition,\n GraphQLFieldDefinition,\n GraphQLInputTypeDefinition,\n GraphQLObjectTypeDefinition,\n GraphQLResolverBinding,\n} from './metadata.ts'\nimport type { Recover } from './results.ts'\nimport type { FieldFunctions, FieldFunctionsFactory } from './schema.ts'\nimport type { GraphQLTypeRef } from './type-ref.ts'\nimport type { GraphQLArgs, GraphQLContext, GraphQLGuard, ResolverContext } from './types.ts'\n\nimport { isThenable } from '@znight/http'\n\nimport { GraphQLErrorCode, GraphQLException } from './errors.ts'\nimport { resolveIn } from './format.ts'\nimport { parseTypeRef } from './type-ref.ts'\n\n/** What the pipeline needs, resolved at boot. */\nexport interface PipelineOptions {\n readonly container: Container\n /** Global guards (plugin option), in order. */\n readonly globalGuards: readonly Resolvable<GraphQLGuard>[]\n /** The guard provider of a `@UseGuard` token (memoised by the caller). */\n readonly guard: (token: Token, coordinate: string) => Resolvable<GraphQLGuard>\n /** The resolver provider of a binding (memoised by the caller). */\n readonly resolver: (binding: GraphQLResolverBinding, coordinate: string) => Resolvable<object>\n /** The provider of a custom parameter resolver class (RFC 0010; memoised by the caller). */\n readonly paramResolver?: (token: Token, coordinate: string) => Resolvable<object>\n /** Input object types by name (null handling of nested input values). */\n readonly inputs: ReadonlyMap<string, GraphQLInputTypeDefinition>\n /** The {@link Recover} function of a field that carries results (RFC 0008), `undefined` for the others. */\n readonly results?: (field: GraphQLFieldDefinition, coordinate: string) => Recover | undefined\n}\n\n/** The generated invoker of a binding. */\ntype Invoke = (\n resolver: object,\n parent: unknown,\n args: GraphQLArgs,\n context: GraphQLContext,\n info: GraphQLResolveInfo,\n field?: ResolverContext,\n resolvers?: readonly object[],\n) => unknown\n\n/** Mutates a coerced argument or input value in place: `null` → `undefined` where flagged. */\ntype Normalize = (value: unknown) => void\n\n/** Whether global guards run on a field: root fields always, field resolvers when they carry metadata (§5.9). */\nexport function globalGuardsApply(binding: GraphQLResolverBinding): boolean {\n return binding.operation !== 'field' || Object.keys(binding.meta).length > 0\n}\n\n/** The {@link FieldFunctionsFactory} of the plugin. */\nexport function pipelineFactory(options: PipelineOptions): FieldFunctionsFactory {\n const normalizers = new NormalizerBuilder(options.inputs)\n return (binding, coordinate, field, parent) =>\n fieldFunctions(options, normalizers, binding, coordinate, field, parent)\n}\n\nfunction fieldFunctions(\n options: PipelineOptions,\n normalizers: NormalizerBuilder,\n binding: GraphQLResolverBinding,\n coordinate: string,\n field: GraphQLFieldDefinition,\n parent: GraphQLObjectTypeDefinition,\n): FieldFunctions {\n const container = options.container\n const target = options.resolver(binding, coordinate)\n const guards: Resolvable<GraphQLGuard>[] = [\n ...(globalGuardsApply(binding) ? options.globalGuards : []),\n ...binding.guards.map(token => options.guard(token, coordinate)),\n ]\n const normalize = field.args === undefined ? undefined : normalizers.args(field.args)\n const recover = options.results?.(field, coordinate)\n const custom = binding.context === true\n const route =\n guards.length === 0 && recover === undefined && !custom\n ? undefined\n : Object.freeze({ meta: binding.meta, coordinate })\n const parentType = parent.name\n const fieldName = field.name\n const invoke: Invoke = custom\n ? customInvoke(options, binding, coordinate, route as ResolverContext['route'], parentType, fieldName)\n : (binding.invoke as Invoke)\n\n let resolve: GraphQLFieldResolver<unknown, unknown>\n if (guards.length === 0) {\n // the common case: one closure, invoke called directly (no promise, no await)\n if (target.token === undefined) {\n const instance = target.instance\n resolve =\n normalize === undefined\n ? (p, a, c, i) => invoke(instance, p, a as GraphQLArgs, c as GraphQLContext, i)\n : (p, a, c, i) => {\n normalize(a)\n return invoke(instance, p, a as GraphQLArgs, c as GraphQLContext, i)\n }\n } else {\n const token = target.token\n resolve =\n normalize === undefined\n ? (p, a, c, i) => invoke(container.get(token), p, a as GraphQLArgs, c as GraphQLContext, i)\n : (p, a, c, i) => {\n normalize(a)\n return invoke(container.get(token), p, a as GraphQLArgs, c as GraphQLContext, i)\n }\n }\n } else {\n const forbidden = (): never => {\n throw new GraphQLException(`Not allowed to resolve ${coordinate}`, { code: GraphQLErrorCode.Forbidden })\n }\n resolve = (p, a, c, i) => {\n const operation = c as OperationContext\n const args = a as GraphQLArgs\n const fieldContext = new FieldContext(\n route as ResolverContext['route'],\n operation,\n parentType,\n fieldName,\n args,\n p,\n i,\n )\n const allowed = runGuards(container, guards, fieldContext)\n // §8.5: guards (they see the coerced arguments), then null handling, then invoke (custom\n // parameters share the guards' ResolverContext)\n const call = (): unknown => {\n if (normalize !== undefined) normalize(args)\n return invoke(resolveIn(container, target), p, args, operation, i, fieldContext)\n }\n if (allowed === true) return call()\n if (allowed === false) return forbidden()\n return allowed.then(ok => (ok ? call() : forbidden()))\n }\n }\n const subscription = binding.operation === 'subscription'\n if (recover !== undefined) {\n resolve = withResults(resolve, recover, route as ResolverContext['route'], parentType, fieldName, subscription)\n }\n if (subscription) {\n // the method gives the source event stream; each event is the field value\n return { subscribe: resolve, resolve: identity }\n }\n return { resolve }\n}\n\nfunction identity(payload: unknown): unknown {\n return payload\n}\n\n/**\n * The invoke of a method with custom parameters (RFC 0010): the generated `invoke` receives the\n * field's `ResolverContext` (the guards' one when the field has guards, else a new one) and the\n * instances of its parameter resolvers: one frozen array resolved at boot when they are all\n * singletons, otherwise resolved in the operation scope on every call.\n */\nfunction customInvoke(\n options: PipelineOptions,\n binding: GraphQLResolverBinding,\n coordinate: string,\n route: ResolverContext['route'],\n parentType: string,\n fieldName: string,\n): Invoke {\n const generated = binding.invoke as Invoke\n const container = options.container\n const tokens = binding.paramResolvers ?? []\n const resolvers = tokens.map(token => {\n if (options.paramResolver === undefined) throw new TypeError(`No parameter resolver for ${coordinate}`)\n return options.paramResolver(token, coordinate)\n })\n const context = (p: unknown, a: GraphQLArgs, c: GraphQLContext, i: GraphQLResolveInfo, f?: ResolverContext) =>\n f ?? new FieldContext(route, c as OperationContext, parentType, fieldName, a, p, i)\n if (resolvers.length === 0) {\n return (r, p, a, c, i, f) => generated(r, p, a, c, i, context(p, a, c, i, f))\n }\n if (resolvers.every(resolver => resolver.token === undefined)) {\n const instances = Object.freeze(resolvers.map(resolver => resolveIn(container, resolver)))\n return (r, p, a, c, i, f) => generated(r, p, a, c, i, context(p, a, c, i, f), instances)\n }\n return (r, p, a, c, i, f) =>\n generated(\n r,\n p,\n a,\n c,\n i,\n context(p, a, c, i, f),\n resolvers.map(resolver => resolveIn(container, resolver)),\n )\n}\n\n/**\n * The resolve function of a field that carries results (RFC 0008): errors of the whole pipeline\n * (guards, null handling, `invoke`), thrown or rejected, go through `recover`. Synchronous results\n * stay synchronous; a promise gets one rejection handler. For a subscription, a value is a source\n * stream of that single event.\n */\nfunction withResults(\n resolve: GraphQLFieldResolver<unknown, unknown>,\n recover: Recover,\n route: ResolverContext['route'],\n parentType: string,\n fieldName: string,\n subscription: boolean,\n): GraphQLFieldResolver<unknown, unknown> {\n const fail = (error: unknown, p: unknown, a: unknown, c: unknown, i: GraphQLResolveInfo): unknown => {\n const value = recover(\n error,\n new FieldContext(route, c as OperationContext, parentType, fieldName, a as GraphQLArgs, p, i),\n )\n return subscription ? once(value) : value\n }\n // captures nothing per call: the rejection handler is created in recoverAsync, on the promise path only\n return (p, a, c, i) => {\n let result: unknown\n try {\n result = resolve(p, a, c, i)\n } catch (error) {\n return fail(error, p, a, c, i)\n }\n return isThenable(result) ? recoverAsync(result, fail, p, a, c, i) : result\n }\n}\n\nfunction recoverAsync(\n result: PromiseLike<unknown>,\n fail: (error: unknown, p: unknown, a: unknown, c: unknown, i: GraphQLResolveInfo) => unknown,\n p: unknown,\n a: unknown,\n c: unknown,\n i: GraphQLResolveInfo,\n): Promise<unknown> {\n return Promise.resolve(result).then(undefined, error => fail(error, p, a, c, i))\n}\n\n/** A source event stream of one event. */\n// biome-ignore lint/suspicious/useAwait: an async generator is the shortest AsyncIterable of one value\nasync function* once(value: unknown): AsyncGenerator<unknown> {\n yield value\n}\n\n/** Runs guards in order, synchronously until one returns a promise. */\nfunction runGuards(\n container: Container,\n guards: readonly Resolvable<GraphQLGuard>[],\n ctx: ResolverContext,\n start = 0,\n): boolean | Promise<boolean> {\n for (let index = start; index < guards.length; index++) {\n const result = resolveIn(container, guards[index] as Resolvable<GraphQLGuard>).canResolve(ctx)\n if (isThenable(result)) {\n return Promise.resolve(result).then(ok => (ok ? runGuards(container, guards, ctx, index + 1) : false))\n }\n if (!result) return false\n }\n return true\n}\n\n/** What a guard receives (§5.9): a `RouteMetaCarrier` with the field's effective metadata. */\nclass FieldContext implements ResolverContext {\n readonly route: ResolverContext['route']\n readonly operation: OperationContext\n readonly parentType: string\n readonly field: string\n readonly args: GraphQLArgs\n readonly parent: unknown\n readonly info: GraphQLResolveInfo\n\n constructor(\n route: ResolverContext['route'],\n operation: OperationContext,\n parentType: string,\n field: string,\n args: GraphQLArgs,\n parent: unknown,\n info: GraphQLResolveInfo,\n ) {\n this.route = route\n this.operation = operation\n this.parentType = parentType\n this.field = field\n this.args = args\n this.parent = parent\n this.info = info\n }\n\n get http(): ResolverContext['http'] {\n return this.operation.http\n }\n}\n\n/** One step of a normaliser: an argument or input field. */\ninterface Step {\n readonly name: string\n /** The value itself: `null` → `undefined`. */\n readonly own: boolean\n /** Nested input values. */\n readonly nested: Normalize | undefined\n}\n\n/**\n * Builds normalisers (§7.3) at boot. Values are mutated in place: graphql-js creates the argument\n * object of every call and the coerced input objects, and the flags of an input type are the same\n * wherever it is used, so a value shared through a variable is normalised the same way twice.\n */\nclass NormalizerBuilder {\n readonly #inputs: ReadonlyMap<string, GraphQLInputTypeDefinition>\n /** Input type → its normaliser (`null`: nothing to do), `PENDING` while being built (cycles). */\n readonly #types = new Map<string, Normalize | null | typeof PENDING>()\n\n constructor(inputs: ReadonlyMap<string, GraphQLInputTypeDefinition>) {\n this.#inputs = inputs\n }\n\n /** The normaliser of a field's arguments, `undefined` when no flag is reachable. */\n args(args: readonly GraphQLArgumentDefinition[]): ((args: unknown) => void) | undefined {\n const steps = this.#steps(args)\n return steps === undefined ? undefined : record => applySteps(record, steps)\n }\n\n #steps(values: readonly GraphQLArgumentDefinition[]): readonly Step[] | undefined {\n const steps: Step[] = []\n for (const value of values) {\n const own = value.nullAsUndefined === true\n const ref = parseTypeRef(value.type)\n const nested = ref === undefined ? undefined : this.#value(ref)\n if (own || nested !== undefined) steps.push({ name: value.name, own, nested })\n }\n return steps.length === 0 ? undefined : steps\n }\n\n #value(ref: GraphQLTypeRef): Normalize | undefined {\n if (ref.kind === 'list') {\n const item = this.#value(ref.of)\n return item === undefined\n ? undefined\n : value => {\n if (Array.isArray(value)) for (const entry of value) item(entry)\n }\n }\n return this.#input(ref.name)\n }\n\n #input(name: string): Normalize | undefined {\n const known = this.#types.get(name)\n if (known === PENDING) {\n // a cycle through this type: delegate to its normaliser once built\n return value => {\n const normalize = this.#types.get(name)\n if (typeof normalize === 'function') normalize(value)\n }\n }\n if (known !== undefined) return known ?? undefined\n const type = this.#inputs.get(name)\n if (type === undefined) return undefined\n this.#types.set(name, PENDING)\n const steps = this.#steps(type.fields)\n const normalize: Normalize | null = steps === undefined ? null : value => applySteps(value, steps)\n this.#types.set(name, normalize)\n return normalize ?? undefined\n }\n}\n\nconst PENDING: unique symbol = Symbol('pending')\n\nfunction applySteps(value: unknown, steps: readonly Step[]): void {\n if (value === null || typeof value !== 'object') return\n const record = value as Record<string, unknown>\n for (const step of steps) {\n const entry = record[step.name]\n if (entry === null) {\n if (step.own) record[step.name] = undefined\n } else if (entry !== undefined && step.nested !== undefined) {\n step.nested(entry)\n }\n }\n}\n","/**\n * Scalars of `@znight/graphql` (RFC 0005 §5.7): the built-in `DateTime`, `BigInt` and `JSON`, and\n * the graphql-js 17 scalar built from a user `ScalarDefinition` (`scalar<T>(name, definition)`).\n *\n * Built-in scalars have no description and no `valueToLiteral`, with the `specifiedByURL` of\n * `BUILTIN_SCALARS`, so that graphql-js `printSchema()` prints what `printSdl()` prints (§7.3).\n */\nimport type { ConstValueNode } from 'graphql'\nimport type { ScalarDefinition } from './types.ts'\n\nimport { GraphQLScalarType, Kind, valueFromASTUntyped } from 'graphql'\n\nimport { BUILTIN_SCALARS } from './names.ts'\n\n/** RFC 3339 date-time with a mandatory offset (`2026-11-02T10:00:00Z`, `...+01:00`). */\nconst DATE_TIME =\n /^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])[Tt]([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d|60)(\\.\\d+)?([Zz]|[+-]([01]\\d|2[0-3]):[0-5]\\d)$/\n\n/** An integer in decimal notation (`BigInt` on the wire). */\nconst DECIMAL_INTEGER = /^-?\\d+$/\n\nfunction describe(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'bigint') return `${value}n`\n if (value === null || typeof value !== 'object') return String(value)\n return Array.isArray(value) ? 'a list' : 'an object'\n}\n\nfunction parseDateTime(value: unknown): Date {\n if (typeof value === 'string' && DATE_TIME.test(value)) {\n const date = new Date(value)\n if (!Number.isNaN(date.getTime())) return date\n }\n throw new TypeError(`DateTime cannot represent ${describe(value)}: expected an RFC 3339 date-time with an offset`)\n}\n\nfunction serializeDateTime(value: unknown): string {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) throw new TypeError('DateTime cannot represent an invalid Date')\n return value.toISOString()\n }\n if (typeof value === 'string' && DATE_TIME.test(value) && !Number.isNaN(Date.parse(value))) return value\n throw new TypeError(`DateTime cannot represent ${describe(value)}: expected a Date`)\n}\n\nfunction parseBigInt(value: unknown): bigint {\n if (typeof value === 'string' && DECIMAL_INTEGER.test(value)) return BigInt(value)\n if (typeof value === 'number' && Number.isSafeInteger(value)) return BigInt(value)\n throw new TypeError(`BigInt cannot represent ${describe(value)}: expected an integer as a decimal string`)\n}\n\nfunction serializeBigInt(value: unknown): string {\n if (typeof value === 'bigint') return value.toString()\n if (typeof value === 'number' && Number.isSafeInteger(value)) return String(value)\n if (typeof value === 'string' && DECIMAL_INTEGER.test(value)) return value\n throw new TypeError(`BigInt cannot represent ${describe(value)}: expected a bigint`)\n}\n\nfunction identity(value: unknown): unknown {\n return value\n}\n\nfunction specifiedBy(name: string): { specifiedByURL?: string } {\n const url = BUILTIN_SCALARS.get(name)?.specifiedByURL\n return url === undefined ? {} : { specifiedByURL: url }\n}\n\nfunction createBuiltin(name: string): GraphQLScalarType | undefined {\n switch (name) {\n case 'DateTime':\n return new GraphQLScalarType<Date, string>({\n name,\n ...specifiedBy(name),\n coerceOutputValue: serializeDateTime,\n coerceInputValue: parseDateTime,\n coerceInputLiteral: (node: ConstValueNode) => parseDateTime(node.kind === Kind.STRING ? node.value : node),\n })\n case 'BigInt':\n return new GraphQLScalarType<bigint, string>({\n name,\n ...specifiedBy(name),\n coerceOutputValue: serializeBigInt,\n coerceInputValue: parseBigInt,\n coerceInputLiteral: (node: ConstValueNode) =>\n parseBigInt(node.kind === Kind.STRING || node.kind === Kind.INT ? node.value : node),\n })\n case 'JSON':\n return new GraphQLScalarType<unknown, unknown>({\n name,\n ...specifiedBy(name),\n coerceOutputValue: identity,\n coerceInputValue: identity,\n coerceInputLiteral: (node: ConstValueNode) => valueFromASTUntyped(node),\n })\n default:\n return undefined\n }\n}\n\n/** Built-in scalars, created on first use and shared by every schema (they hold no state). */\nconst builtins = new Map<string, GraphQLScalarType>()\n\n/** The built-in scalar `name` (`DateTime`, `BigInt`, `JSON`), `undefined` for another name. */\nexport function builtinScalar(name: string): GraphQLScalarType | undefined {\n let scalar = builtins.get(name)\n if (scalar === undefined) {\n scalar = createBuiltin(name)\n if (scalar !== undefined) builtins.set(name, scalar)\n }\n return scalar\n}\n\n/**\n * The graphql-js scalar of a {@link ScalarDefinition}: `serialize` → `coerceOutputValue`,\n * `parseValue` → `coerceInputValue`, `parseLiteral` → `coerceInputLiteral` (default: `parseValue`\n * of the literal's JSON value). The definition's methods are called on the definition.\n */\nexport function definitionScalar(\n name: string,\n definition: ScalarDefinition<unknown>,\n overrides: { readonly description?: string; readonly specifiedByURL?: string } = {},\n): GraphQLScalarType {\n const parseLiteral = definition.parseLiteral\n // a key present in `overrides` wins, even undefined (schema-first: the SDL is the truth)\n const description = 'description' in overrides ? overrides.description : definition.description\n const specifiedByURL = 'specifiedByURL' in overrides ? overrides.specifiedByURL : definition.specifiedByURL\n return new GraphQLScalarType({\n name,\n ...(description === undefined ? {} : { description }),\n ...(specifiedByURL === undefined ? {} : { specifiedByURL }),\n coerceOutputValue: (value: unknown) => definition.serialize(value),\n coerceInputValue: (value: unknown) => definition.parseValue(value),\n coerceInputLiteral:\n parseLiteral === undefined\n ? (node: ConstValueNode) => definition.parseValue(valueFromASTUntyped(node))\n : (node: ConstValueNode) => parseLiteral.call(definition, node),\n })\n}\n","/**\n * The `GraphQLSchema` of `metadata.extensions.graphql` (RFC 0005 §7.3, §8.1): structural checks of\n * the section (it can be hand-written), then graphql-js 17 constructors (thunks for cycles, every\n * type passed in metadata order so that `printSchema()` matches `printSdl()`), then\n * `validateSchema`. Every problem is collected and reported as one ZNIGHT066 error.\n *\n * Resolve functions are not decided here: the caller supplies them per resolver-backed field\n * (`pipeline.ts`), so this module stays about the shape of the schema.\n */\nimport type { ZnightMetadata } from '@znight/core'\nimport type {\n GraphQLArgumentConfig,\n GraphQLEnumValueConfig,\n GraphQLFieldConfig,\n GraphQLFieldResolver,\n GraphQLInputFieldConfig,\n GraphQLInputType,\n GraphQLNamedType,\n GraphQLOutputType,\n} from 'graphql'\nimport type {\n GraphQLArgumentDefinition,\n GraphQLDiscriminator,\n GraphQLFieldDefinition,\n GraphQLInputTypeDefinition,\n GraphQLInterfaceTypeDefinition,\n GraphQLMetadata,\n GraphQLObjectTypeDefinition,\n GraphQLResolverBinding,\n GraphQLTypeDefinition,\n} from './metadata.ts'\nimport type { GraphQLTypeRef } from './type-ref.ts'\nimport type { ScalarDefinition } from './types.ts'\n\nimport { ErrorCode, ZnightError } from '@znight/core'\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLFloat,\n GraphQLID,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLInterfaceType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n GraphQLScalarType,\n GraphQLSchema,\n GraphQLString,\n GraphQLUnionType,\n validateSchema,\n} from 'graphql'\n\nimport { GRAPHQL_METADATA_VERSION } from './metadata.ts'\nimport { BUILTIN_SCALARS, isGraphQLName, RESERVED_ENUM_VALUES, SPECIFIED_SCALARS } from './names.ts'\nimport { builtinScalar, definitionScalar } from './scalars.ts'\nimport { parseTypeRef } from './type-ref.ts'\n\n/** The resolve functions of a resolver-backed field, decided by the caller (`pipeline.ts`). */\nexport interface FieldFunctions {\n readonly resolve?: GraphQLFieldResolver<unknown, unknown>\n /** Root subscription fields: the source event stream. */\n readonly subscribe?: GraphQLFieldResolver<unknown, unknown>\n}\n\n/** Builds the resolve functions of the field `coordinate` (`Query.books`) backed by `binding`. */\nexport type FieldFunctionsFactory = (\n binding: GraphQLResolverBinding,\n coordinate: string,\n field: GraphQLFieldDefinition,\n parent: GraphQLObjectTypeDefinition,\n) => FieldFunctions\n\n/** The graphql section of the metadata, or ZNIGHT066 when the application has none. */\nexport function graphqlSection(metadata: ZnightMetadata): GraphQLMetadata {\n const section: unknown = metadata.extensions?.graphql\n if (section === undefined) {\n throw new ZnightError(\n ErrorCode.InvalidGraphQLSetup,\n 'GraphQLPlugin: the metadata has no GraphQL schema (metadata.extensions.graphql)',\n {\n hints: [\n 'Declare at least one @Resolver() class with a @Query() method',\n 'Regenerate the metadata (znight generate) when resolvers exist',\n ],\n },\n )\n }\n return section as GraphQLMetadata\n}\n\nconst OPERATIONS: ReadonlySet<string> = new Set(['query', 'mutation', 'subscription', 'field'])\nconst INPUT_KINDS: ReadonlySet<string> = new Set(['input', 'enum', 'scalar'])\nconst OUTPUT_KINDS: ReadonlySet<string> = new Set(['object', 'interface', 'enum', 'scalar', 'union'])\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction show(value: unknown): string {\n if (typeof value === 'function') return 'a function'\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return typeof value\n }\n}\n\n/**\n * The structural problems of a graphql section (empty when it can be built): version, roots,\n * names, kinds, type references, resolver bindings, discriminators, scalars and groups.\n */\nexport function checkGraphQLSection(section: unknown): string[] {\n const problems: string[] = []\n if (!isRecord(section)) return [`expected an object (received ${show(section)})`]\n if (section['version'] !== GRAPHQL_METADATA_VERSION) {\n problems.push(\n `unsupported version ${show(section['version'])}: this @znight/graphql reads version ${GRAPHQL_METADATA_VERSION} (rebuild the application with the same @znight/graphql version)`,\n )\n return problems\n }\n if (typeof section['schemaHash'] !== 'string') problems.push('schemaHash must be a string')\n const types = section['types']\n if (!Array.isArray(types)) {\n problems.push('types must be an array')\n return problems\n }\n const kinds = new Map<string, string>()\n for (const [index, type] of types.entries()) {\n if (!isRecord(type) || typeof type['name'] !== 'string' || typeof type['kind'] !== 'string') {\n problems.push(`types[${index}] must be { kind, name, ... } (received ${show(type)})`)\n continue\n }\n const name = type['name']\n if (!isGraphQLName(name)) problems.push(`invalid type name ${show(name)}`)\n else if (SPECIFIED_SCALARS.has(name)) problems.push(`the specified scalar ${name} must not be declared`)\n else if (kinds.has(name)) problems.push(`the type ${name} is declared twice`)\n kinds.set(name, type['kind'])\n }\n const kindOf = (name: string): string | undefined => (SPECIFIED_SCALARS.has(name) ? 'scalar' : kinds.get(name))\n const checkRef = (where: string, text: unknown, allowed: ReadonlySet<string>, position: string): void => {\n const ref = typeof text === 'string' ? parseTypeRef(text) : undefined\n if (ref === undefined) {\n problems.push(`${where}: invalid type reference ${show(text)}`)\n return\n }\n let named: GraphQLTypeRef = ref\n while (named.kind === 'list') named = named.of\n const kind = kindOf(named.name)\n if (kind === undefined) problems.push(`${where}: unknown type ${named.name}`)\n else if (!allowed.has(kind))\n problems.push(`${where}: ${named.name} (${kind}) cannot be used as an ${position} type`)\n }\n const checkInputValues = (where: string, values: unknown, required: boolean): void => {\n if (!Array.isArray(values) || (required && values.length === 0)) {\n problems.push(`${where} must be a ${required ? 'non-empty ' : ''}array`)\n return\n }\n const seen = new Set<string>()\n for (const value of values) {\n if (!isRecord(value) || typeof value['name'] !== 'string') {\n problems.push(`${where}: expected { name, type } (received ${show(value)})`)\n continue\n }\n const name = value['name']\n if (!isGraphQLName(name)) problems.push(`${where}: invalid name ${show(name)}`)\n if (seen.has(name)) problems.push(`${where}: ${name} is declared twice`)\n seen.add(name)\n checkRef(`${where}.${name}`, value['type'], INPUT_KINDS, 'input')\n }\n }\n for (const type of types) {\n if (!isRecord(type) || typeof type['name'] !== 'string') continue\n const name = type['name']\n switch (type['kind']) {\n case 'object':\n case 'interface': {\n const isInterface = type['kind'] === 'interface'\n checkInterfaces(name, type['interfaces'], kinds, problems)\n const fields = type['fields']\n if (!Array.isArray(fields) || fields.length === 0) {\n problems.push(`${name}: fields must be a non-empty array`)\n break\n }\n const seen = new Set<string>()\n for (const field of fields) {\n if (!isRecord(field) || typeof field['name'] !== 'string') {\n problems.push(`${name}: expected fields { name, type } (received ${show(field)})`)\n continue\n }\n const coordinate = `${name}.${field['name']}`\n if (!isGraphQLName(field['name'])) problems.push(`${name}: invalid field name ${show(field['name'])}`)\n if (seen.has(field['name'])) problems.push(`${coordinate} is declared twice`)\n seen.add(field['name'])\n checkRef(coordinate, field['type'], OUTPUT_KINDS, 'output')\n if (field['args'] !== undefined) checkInputValues(`${coordinate} arguments`, field['args'], false)\n if (field['resolver'] === undefined) continue\n if (isInterface)\n problems.push(`${coordinate}: interface fields have no resolver (bind it on the object types)`)\n else checkBinding(coordinate, field['resolver'], problems)\n }\n if (isInterface) {\n const implementations = types.filter(\n other =>\n isRecord(other) &&\n other['kind'] === 'object' &&\n Array.isArray(other['interfaces']) &&\n other['interfaces'].includes(name),\n )\n checkDiscriminator(\n name,\n type['discriminator'],\n implementations.map(other => (other as Record<string, unknown>)['name']),\n problems,\n )\n }\n break\n }\n case 'input':\n checkInputValues(`${name} fields`, type['fields'], true)\n break\n case 'enum': {\n const values = type['values']\n if (!Array.isArray(values) || values.length === 0) {\n problems.push(`${name}: values must be a non-empty array`)\n break\n }\n const seen = new Set<string>()\n for (const value of values) {\n const valueName = isRecord(value) ? value['name'] : undefined\n if (\n !isRecord(value) ||\n typeof valueName !== 'string' ||\n !isGraphQLName(valueName) ||\n RESERVED_ENUM_VALUES.has(valueName) ||\n (typeof value['value'] !== 'string' && typeof value['value'] !== 'number')\n ) {\n problems.push(`${name}: invalid enum value ${show(value)} (expected { name, value: string | number })`)\n continue\n }\n if (seen.has(valueName)) problems.push(`${name}.${valueName} is declared twice`)\n seen.add(valueName)\n }\n break\n }\n case 'union': {\n const members = type['members']\n if (!Array.isArray(members) || members.length === 0) {\n problems.push(`${name}: members must be a non-empty array`)\n break\n }\n for (const member of members) {\n if (typeof member !== 'string' || kinds.get(member) !== 'object') {\n problems.push(`${name}: the member ${show(member)} is not an object type`)\n }\n }\n checkDiscriminator(name, type['discriminator'], members, problems)\n break\n }\n case 'scalar':\n if (type['builtin'] === true) {\n if (!BUILTIN_SCALARS.has(name))\n problems.push(`${name} is not a built-in scalar (${[...BUILTIN_SCALARS.keys()].join(', ')})`)\n } else {\n const scalar = type['scalar']\n if (scalar instanceof GraphQLScalarType) {\n if (scalar.name !== name) {\n problems.push(\n `the scalar ${name} is implemented by the graphql-js scalar ${scalar.name} (names must match)`,\n )\n }\n } else if (\n !isRecord(scalar) ||\n typeof scalar['serialize'] !== 'function' ||\n typeof scalar['parseValue'] !== 'function' ||\n (scalar['parseLiteral'] !== undefined && typeof scalar['parseLiteral'] !== 'function')\n ) {\n problems.push(\n `the scalar ${name} needs a definition { serialize, parseValue, parseLiteral? } or a GraphQLScalarType (received ${show(scalar)})`,\n )\n }\n }\n for (const key of ['description', 'specifiedByURL'] as const) {\n if (type[key] !== undefined && typeof type[key] !== 'string')\n problems.push(`${name}: ${key} must be a string`)\n }\n if (type['sdl'] !== undefined && type['sdl'] !== true) problems.push(`${name}: sdl must be true when present`)\n break\n default:\n problems.push(`${name}: unknown kind ${show(type['kind'])}`)\n }\n }\n checkRoots(section['roots'], kinds, types, problems)\n checkGroups(section['groups'], problems)\n return problems\n}\n\n/** `interfaces` of an object or interface type: absent, or interface type names. */\nfunction checkInterfaces(\n name: string,\n interfaces: unknown,\n kinds: ReadonlyMap<string, string>,\n problems: string[],\n): void {\n if (interfaces === undefined) return\n if (!Array.isArray(interfaces)) {\n problems.push(`${name}: interfaces must be an array of interface type names (received ${show(interfaces)})`)\n return\n }\n for (const entry of interfaces) {\n if (typeof entry !== 'string' || kinds.get(entry) !== 'interface') {\n problems.push(`${name}: ${show(entry)} is not an interface type`)\n }\n }\n}\n\nfunction checkBinding(coordinate: string, binding: unknown, problems: string[]): void {\n if (!isRecord(binding)) {\n problems.push(`${coordinate}: resolver must be an object (received ${show(binding)})`)\n return\n }\n const invalid: string[] = []\n if (typeof binding['token'] !== 'string' || binding['token'] === '') invalid.push('token')\n if (typeof binding['method'] !== 'string') invalid.push('method')\n if (typeof binding['operation'] !== 'string' || !OPERATIONS.has(binding['operation'])) invalid.push('operation')\n const guards = binding['guards']\n if (!Array.isArray(guards) || !guards.every(guard => typeof guard === 'string' && guard !== ''))\n invalid.push('guards')\n if (!isRecord(binding['meta'])) invalid.push('meta')\n if (typeof binding['invoke'] !== 'function') invalid.push('invoke')\n if (invalid.length > 0) problems.push(`${coordinate}: invalid resolver binding (${invalid.join(', ')})`)\n}\n\nfunction checkDiscriminator(\n name: string,\n discriminator: unknown,\n members: readonly unknown[],\n problems: string[],\n): void {\n const memberSet = new Set(members)\n if (!isRecord(discriminator)) {\n problems.push(`${name}: discriminator must be an object (received ${show(discriminator)})`)\n return\n }\n switch (discriminator['by']) {\n case 'typename':\n return\n case 'property': {\n const values = discriminator['values']\n if (typeof discriminator['property'] !== 'string' || !isRecord(values)) {\n problems.push(`${name}: a property discriminator needs { property, values }`)\n return\n }\n for (const member of Object.values(values)) {\n if (!memberSet.has(member)) problems.push(`${name}: the discriminator names ${show(member)}, not a member`)\n }\n return\n }\n case 'class': {\n const classes = discriminator['classes']\n if (!Array.isArray(classes)) {\n problems.push(`${name}: a class discriminator needs classes: [Class, member][]`)\n return\n }\n for (const entry of classes) {\n if (!Array.isArray(entry) || typeof entry[0] !== 'function' || !memberSet.has(entry[1])) {\n problems.push(`${name}: invalid class discriminator entry ${show(entry)} (expected [Class, member])`)\n }\n }\n return\n }\n default:\n problems.push(`${name}: unknown discriminator ${show(discriminator['by'])}`)\n }\n}\n\nfunction checkRoots(\n roots: unknown,\n kinds: ReadonlyMap<string, string>,\n types: readonly unknown[],\n problems: string[],\n): void {\n if (!isRecord(roots) || typeof roots['query'] !== 'string') {\n problems.push(`roots must be { query, mutation?, subscription? } (received ${show(roots)})`)\n return\n }\n for (const operation of ['query', 'mutation', 'subscription'] as const) {\n const root = roots[operation]\n if (root === undefined) continue\n if (typeof root !== 'string' || kinds.get(root) !== 'object') {\n problems.push(`the ${operation} root ${show(root)} is not an object type`)\n }\n }\n const subscription = roots['subscription']\n if (typeof subscription !== 'string') return\n for (const type of types) {\n if (!isRecord(type) || type['name'] !== subscription || !Array.isArray(type['fields'])) continue\n for (const field of type['fields'] as unknown[]) {\n if (!isRecord(field)) continue\n const binding = field['resolver']\n if (!isRecord(binding) || binding['operation'] !== 'subscription') {\n problems.push(`${subscription}.${show(field['name'])} needs a subscription resolver (its source event stream)`)\n }\n }\n }\n}\n\nfunction checkGroups(groups: unknown, problems: string[]): void {\n if (groups === undefined) return\n if (!isRecord(groups)) {\n problems.push(`groups must be an object (received ${show(groups)})`)\n return\n }\n for (const [group, entry] of Object.entries(groups)) {\n const keys = isRecord(entry) ? entry['keys'] : undefined\n if (\n !isRecord(entry) ||\n !Array.isArray(keys) ||\n keys.length === 0 ||\n !keys.every(key => typeof key === 'string' && key !== '') ||\n typeof entry['required'] !== 'boolean'\n ) {\n problems.push(`group ${show(group)} must be { keys: [non-empty strings], required: boolean }`)\n }\n }\n}\n\n/** Throws one ZNIGHT066 error listing `problems`. */\nexport function invalidSchema(problems: readonly string[]): never {\n throw new ZnightError(\n ErrorCode.InvalidGraphQLSetup,\n `GraphQLPlugin: invalid GraphQL schema (metadata.extensions.graphql), ${problems.length} ${problems.length === 1 ? 'problem' : 'problems'}:\\n${problems.map(problem => ` - ${problem}`).join('\\n')}`,\n {\n hints: [\n 'Regenerate the metadata with the @znight/graphql version the application runs (znight generate)',\n 'Hand-written metadata must follow GraphQLMetadata (@znight/graphql, RFC 0005 §7.1)',\n ],\n },\n )\n}\n\n/** The `resolveType` of a union or an interface, from its discriminator: data read once, at boot. */\nexport function typeResolver(discriminator: GraphQLDiscriminator): (value: unknown) => string | undefined {\n switch (discriminator.by) {\n case 'property': {\n const property = discriminator.property\n const values = new Map(Object.entries(discriminator.values))\n return value =>\n value !== null && typeof value === 'object'\n ? (values.get(String((value as Record<string, unknown>)[property])) ?? typenameOf(value))\n : undefined\n }\n case 'class': {\n const classes = discriminator.classes\n return value => {\n for (const [cls, name] of classes) if (value instanceof cls) return name\n return typenameOf(value)\n }\n }\n default:\n return typenameOf\n }\n}\n\nfunction typenameOf(value: unknown): string | undefined {\n if (value === null || typeof value !== 'object') return undefined\n const name = (value as { __typename?: unknown }).__typename\n return typeof name === 'string' ? name : undefined\n}\n\n/**\n * Builds the schema of a section. `functions` decides the resolve functions of every\n * resolver-backed field; plain property fields keep the graphql-js default resolver.\n *\n * @throws ZnightError ZNIGHT066 listing every structural, construction and `validateSchema` problem.\n */\nexport function buildGraphQLSchema(section: GraphQLMetadata, functions: FieldFunctionsFactory): GraphQLSchema {\n const structural = checkGraphQLSection(section)\n if (structural.length > 0) invalidSchema(structural)\n const named = new Map<string, GraphQLNamedType>([\n ['String', GraphQLString],\n ['Int', GraphQLInt],\n ['Float', GraphQLFloat],\n ['Boolean', GraphQLBoolean],\n ['ID', GraphQLID],\n ])\n const problems: string[] = []\n const lookup = (name: string): GraphQLNamedType => named.get(name) as GraphQLNamedType\n const typeOf = (ref: GraphQLTypeRef): GraphQLInputType & GraphQLOutputType => {\n const inner = ref.kind === 'named' ? lookup(ref.name) : new GraphQLList(typeOf(ref.of))\n return (ref.nonNull ? new GraphQLNonNull(inner) : inner) as GraphQLInputType & GraphQLOutputType\n }\n // references were checked by checkGraphQLSection\n const typeRef = (text: string): GraphQLInputType & GraphQLOutputType => typeOf(parseTypeRef(text) as GraphQLTypeRef)\n const inputValue = (value: GraphQLArgumentDefinition): GraphQLArgumentConfig & GraphQLInputFieldConfig => ({\n type: typeRef(value.type),\n ...(value.description === undefined ? {} : { description: value.description }),\n ...(value.deprecationReason === undefined ? {} : { deprecationReason: value.deprecationReason }),\n // external value (enum values by name): what printSdl() assumes (sdl.ts)\n ...(value.defaultValue === undefined ? {} : { default: { value: value.defaultValue } }),\n })\n const fieldConfig = (\n type: GraphQLObjectTypeDefinition | GraphQLInterfaceTypeDefinition,\n field: GraphQLFieldDefinition,\n ): GraphQLFieldConfig<unknown, unknown> => {\n const config: GraphQLFieldConfig<unknown, unknown> = {\n type: typeRef(field.type),\n ...(field.description === undefined ? {} : { description: field.description }),\n ...(field.deprecationReason === undefined ? {} : { deprecationReason: field.deprecationReason }),\n ...(field.args === undefined || field.args.length === 0\n ? {}\n : { args: Object.fromEntries(field.args.map(arg => [arg.name, inputValue(arg)])) }),\n }\n if (field.resolver === undefined || type.kind === 'interface') return config\n const resolved = functions(field.resolver, `${type.name}.${field.name}`, field, type)\n return {\n ...config,\n ...(resolved.resolve === undefined ? {} : { resolve: resolved.resolve }),\n ...(resolved.subscribe === undefined ? {} : { subscribe: resolved.subscribe }),\n }\n }\n try {\n for (const type of section.types) named.set(type.name, createType(type, fieldConfig, inputValue, lookup))\n } catch (error) {\n invalidSchema([`cannot build the schema: ${error instanceof Error ? error.message : String(error)}`])\n }\n const root = (name: string | undefined): GraphQLObjectType | undefined =>\n name === undefined ? undefined : (lookup(name) as GraphQLObjectType)\n let schema: GraphQLSchema | undefined\n try {\n schema = new GraphQLSchema({\n query: root(section.roots.query),\n mutation: root(section.roots.mutation),\n subscription: root(section.roots.subscription),\n // metadata order (sorted by name): printSchema() follows it, like printSdl()\n types: section.types.map(type => lookup(type.name)),\n })\n for (const error of validateSchema(schema)) problems.push(error.message)\n } catch (error) {\n // thunks run here: a resolver factory (a missing provider keeps its own code) or a constructor\n if (error instanceof ZnightError) throw error\n problems.push(error instanceof Error ? error.message : String(error))\n }\n if (problems.length > 0 || schema === undefined) invalidSchema(problems)\n return schema\n}\n\nfunction createType(\n type: GraphQLTypeDefinition,\n fieldConfig: (\n type: GraphQLObjectTypeDefinition | GraphQLInterfaceTypeDefinition,\n field: GraphQLFieldDefinition,\n ) => GraphQLFieldConfig<unknown, unknown>,\n inputValue: (value: GraphQLArgumentDefinition) => GraphQLInputFieldConfig,\n lookup: (name: string) => GraphQLNamedType,\n): GraphQLNamedType {\n const description = 'description' in type && type.description !== undefined ? { description: type.description } : {}\n switch (type.kind) {\n case 'object':\n return new GraphQLObjectType({\n name: type.name,\n ...description,\n ...interfacesOf(type, lookup),\n // thunk: object types reference each other (cycles)\n fields: () => Object.fromEntries(type.fields.map(field => [field.name, fieldConfig(type, field)])),\n })\n case 'interface':\n return new GraphQLInterfaceType({\n name: type.name,\n ...description,\n ...interfacesOf(type, lookup),\n fields: () => Object.fromEntries(type.fields.map(field => [field.name, fieldConfig(type, field)])),\n resolveType: typeResolver(type.discriminator),\n })\n case 'input':\n return new GraphQLInputObjectType({\n name: type.name,\n ...description,\n fields: () =>\n Object.fromEntries((type as GraphQLInputTypeDefinition).fields.map(field => [field.name, inputValue(field)])),\n })\n case 'enum':\n return new GraphQLEnumType({\n name: type.name,\n ...description,\n values: Object.fromEntries(\n type.values.map((value): [string, GraphQLEnumValueConfig] => [\n value.name,\n {\n value: value.value,\n ...(value.description === undefined ? {} : { description: value.description }),\n ...(value.deprecationReason === undefined ? {} : { deprecationReason: value.deprecationReason }),\n },\n ]),\n ),\n })\n case 'union':\n return new GraphQLUnionType({\n name: type.name,\n ...description,\n types: () => type.members.map(member => lookup(member) as GraphQLObjectType),\n resolveType: typeResolver(type.discriminator),\n })\n default: {\n if ('builtin' in type) return builtinScalar(type.name) as GraphQLScalarType\n // `sdl`: the entry's description and specifiedByURL replace the definition's, absent ones too\n const sdl = type.sdl === true\n const overrides = {\n ...(type.description === undefined && !sdl ? {} : { description: type.description }),\n ...(type.specifiedByURL === undefined && !sdl ? {} : { specifiedByURL: type.specifiedByURL }),\n }\n const scalar = type.scalar\n if (scalar instanceof GraphQLScalarType) {\n if (Object.keys(overrides).length === 0) return scalar\n const config = scalar.toConfig()\n return new GraphQLScalarType({\n ...config,\n description: 'description' in overrides ? overrides.description : config.description,\n specifiedByURL: 'specifiedByURL' in overrides ? overrides.specifiedByURL : config.specifiedByURL,\n })\n }\n return definitionScalar(type.name, scalar as ScalarDefinition<unknown>, overrides)\n }\n }\n}\n\n/** The `interfaces` thunk of an object or interface type (none: no key, as before RFC 0007). */\nfunction interfacesOf(\n type: GraphQLObjectTypeDefinition | GraphQLInterfaceTypeDefinition,\n lookup: (name: string) => GraphQLNamedType,\n): { interfaces?: () => GraphQLInterfaceType[] } {\n const names = type.interfaces\n if (names === undefined || names.length === 0) return {}\n return { interfaces: () => names.map(name => lookup(name) as GraphQLInterfaceType) }\n}\n","/**\n * Errors as data (RFC 0008): result mappers turn the error of a field into a value of its union.\n *\n * Decided at boot, per resolver-backed field: a field carries results when its type, without its\n * non-null wrapper, is a union (not a list) holding an object type declared by a result mapper\n * (`static types`). Only those fields get a wrapper (`pipeline.ts`); the others keep their resolve\n * function. On an error, the applicable mappers run in order; the first value resolving to a member\n * of the union is the field's value, otherwise the error is thrown back, to `errors[]`.\n */\nimport type { Container, CoreLogger } from '@znight/core'\nimport type { GraphQLResolveInfo } from 'graphql'\nimport type { Resolvable } from './format.ts'\nimport type { GraphQLFieldDefinition, GraphQLTypeDefinition } from './metadata.ts'\nimport type { GraphQLResultMapper, ResolverContext } from './types.ts'\n\nimport { ErrorCode, ZnightError } from '@znight/core'\nimport { isThenable } from '@znight/http'\n\nimport { resolveIn } from './format.ts'\nimport { typeResolver } from './schema.ts'\nimport { parseTypeRef } from './type-ref.ts'\n\n/** A result mapper resolved at boot. */\nexport interface ResultMapperEntry {\n readonly resolvable: Resolvable<GraphQLResultMapper>\n /** For logs: the class name. */\n readonly name: string\n /** Declared object types, checked by {@link checkResultTypes}. */\n readonly types: readonly string[]\n}\n\n/** The value of a field for an error, or the error thrown back. */\nexport type Recover = (error: unknown, ctx: ResolverContext) => unknown\n\n/** The object types a result mapper ref declares: `static types` of a class; for an instance, its `types` property or its class's. */\nexport function declaredTypes(ref: unknown): unknown {\n try {\n if (typeof ref === 'function') return (ref as { types?: unknown }).types\n const own = (ref as { types?: unknown }).types\n if (own !== undefined) return own\n return ((ref as { constructor?: unknown }).constructor as { types?: unknown } | undefined)?.types\n } catch {\n // a throwing getter: reported as no types\n return undefined\n }\n}\n\n/**\n * Checks the declared types of the result mappers against the schema's types: a non-empty array of\n * names of object types. Every problem in one ZNIGHT066 error.\n */\nexport function checkResultTypes(\n mappers: readonly { readonly name: string; readonly types: unknown }[],\n types: readonly GraphQLTypeDefinition[],\n): void {\n if (mappers.length === 0) return\n const kinds = new Map(types.map(type => [type?.name, type?.kind]))\n const problems: string[] = []\n for (const mapper of mappers) {\n const declared = mapper.types\n if (!Array.isArray(declared) || declared.length === 0) {\n problems.push(\n `the result mapper ${mapper.name} declares no types (static readonly types = [...object type names])`,\n )\n continue\n }\n for (const name of declared as unknown[]) {\n if (typeof name !== 'string' || kinds.get(name) !== 'object') {\n problems.push(\n `the result mapper ${mapper.name} declares ${typeof name === 'string' ? name : String(name)}, which is not an object type of the schema`,\n )\n }\n }\n }\n if (problems.length === 0) return\n throw new ZnightError(ErrorCode.InvalidGraphQLSetup, `GraphQLPlugin: ${problems.join('; ')}`, {\n hints: [\n \"A result mapper declares the object types its values may have: static readonly types = ['NotFoundRejection'] (RFC 0008)\",\n ],\n })\n}\n\n/** The union of a field type and its members, by union name. */\ninterface Union {\n readonly name: string\n readonly members: ReadonlySet<string>\n readonly typeOf: (value: unknown) => string | undefined\n}\n\n/** Decides which fields carry results, and builds their {@link Recover} functions. */\nexport class ResultMappers {\n readonly #container: Container\n readonly #logger: CoreLogger\n readonly #mappers: readonly ResultMapperEntry[]\n readonly #types: readonly GraphQLTypeDefinition[]\n /** Built on the first field, once the schema construction checked the section's structure. */\n #index: { readonly objects: ReadonlySet<string>; readonly unions: ReadonlyMap<string, Union> } | undefined\n #fields = 0\n\n constructor(\n container: Container,\n logger: CoreLogger,\n mappers: readonly ResultMapperEntry[],\n types: readonly GraphQLTypeDefinition[],\n ) {\n this.#container = container\n this.#logger = logger\n this.#mappers = mappers\n this.#types = types\n }\n\n /** Fields that carry results so far. */\n get fields(): number {\n return this.#fields\n }\n\n /** The {@link Recover} function of `field`, `undefined` when it carries no result. */\n recover(field: GraphQLFieldDefinition, coordinate: string): Recover | undefined {\n if (this.#mappers.length === 0) return undefined\n const ref = parseTypeRef(field.type)\n if (ref?.kind !== 'named') return undefined\n this.#index ??= index(this.#types)\n const objects = this.#index.objects\n const union = this.#index.unions.get(ref.name)\n if (union === undefined) return undefined\n const applicable = this.#mappers.filter(mapper => mapper.types.some(type => union.members.has(type)))\n if (applicable.length === 0) return undefined\n this.#fields++\n const container = this.#container\n const logger = this.#logger\n return (error, ctx) => {\n for (const mapper of applicable) {\n let value: unknown\n let type: string | undefined\n try {\n value = resolveIn(container, mapper.resolvable).toResult(error, ctx)\n if (value === undefined || value === null) continue\n if (isThenable(value)) {\n // not awaited: the field cannot wait for a mapper, and its rejection must not go unhandled\n Promise.resolve(value).catch(noop)\n logger.error(\n `GraphQLPlugin: the result mapper ${mapper.name} returned a promise: toResult() must be synchronous`,\n details(ctx, coordinate, error),\n )\n continue\n }\n // the discriminator reads the value (a getter, a class check): a failure is the mapper's\n type = union.typeOf(value)\n } catch (failure) {\n logger.error(`GraphQLPlugin: the result mapper ${mapper.name} failed`, details(ctx, coordinate, failure))\n continue\n }\n if (type !== undefined && union.members.has(type)) {\n // the business path: no request id (it may be minted on first read) nor path built for a debug line\n logger.debug(`GraphQL: error resolved as ${type} in ${coordinate}`, { coordinate, type })\n return value\n }\n if (type !== undefined && objects.has(type)) {\n logger.debug(\n `GraphQLPlugin: the result mapper ${mapper.name} returned a value of ${type}, not a member of ${union.name} (${coordinate}): skipped`,\n details(ctx, coordinate, error),\n )\n } else {\n logger.warn(\n `GraphQLPlugin: the result mapper ${mapper.name} returned a value of no type of the schema (${coordinate}): skipped`,\n details(ctx, coordinate, error),\n )\n }\n }\n throw error\n }\n }\n}\n\nfunction index(types: readonly GraphQLTypeDefinition[]): {\n readonly objects: ReadonlySet<string>\n readonly unions: ReadonlyMap<string, Union>\n} {\n const objects = new Set<string>()\n const unions = new Map<string, Union>()\n for (const type of types) {\n if (type.kind === 'object') objects.add(type.name)\n else if (type.kind === 'union') {\n unions.set(type.name, {\n name: type.name,\n members: new Set(type.members),\n typeOf: typeResolver(type.discriminator),\n })\n }\n }\n return { objects, unions }\n}\n\nfunction noop(): void {}\n\nfunction details(ctx: ResolverContext, coordinate: string, err: unknown): Record<string, unknown> {\n return { err, requestId: ctx.operation.requestId, coordinate, path: pathOf(ctx.info).join('.') }\n}\n\nfunction pathOf(info: GraphQLResolveInfo): (string | number)[] {\n const path: (string | number)[] = []\n for (let step: GraphQLResolveInfo['path'] | undefined = info.path; step !== undefined; step = step.prev) {\n path.push(step.key)\n }\n return path.reverse()\n}\n","/**\n * The built-in transport as a driver (RFC 0009 §4.11): GraphQL over HTTP and SSE, the default when\n * the `driver` option is absent. It keeps its privileged access to the internal executor (statuses,\n * formatted results, SSE sessions, the memoised negotiation): its handlers are the ones of\n * `HttpTransport`, unchanged, and it never goes through the public engine.\n */\nimport type { SseOptions } from '@znight/http'\nimport type { GraphQLDriver, GraphQLDriverRoute, GraphQLDriverRoutesContext } from '../driver.ts'\nimport type { GraphQLExecutor } from '../execution.ts'\n\nimport { HttpTransport } from './http.ts'\n\n/** What the built-in driver is built from (resolved plugin options). */\nexport interface BuiltinDriverOptions {\n /** The executor of the plugin, read on the first request (routes may be collected before the bootstrap). */\n readonly executor: () => GraphQLExecutor\n /** Queries over `GET`. */\n readonly get: boolean\n readonly graphiql: boolean\n /** `HttpResponse.sse()` options of GraphQL over SSE; `false`: no event streams. */\n readonly sse: SseOptions | false\n}\n\n/** The name of the built-in transport (`GraphQLOperationEvent.driver`), reserved. */\nexport const BUILTIN_DRIVER = 'builtin'\n\n/** The built-in GraphQL-over-HTTP and SSE endpoint. */\nexport class BuiltinDriver implements GraphQLDriver {\n readonly name: string = BUILTIN_DRIVER\n readonly #options: BuiltinDriverOptions\n\n constructor(options: BuiltinDriverOptions) {\n this.#options = options\n }\n\n /** `POST` on the path, and `GET` when queries over `GET` or GraphiQL are on (the router answers 405 otherwise). */\n routes(context: GraphQLDriverRoutesContext): readonly GraphQLDriverRoute[] {\n const options = this.#options\n const transport = new HttpTransport({\n executor: options.executor,\n endpoint: context.endpoint,\n get: options.get,\n graphiql: options.graphiql,\n sse: options.sse,\n })\n const routes: GraphQLDriverRoute[] = [\n { method: 'POST', path: context.path, name: 'handle', handler: transport.post },\n ]\n if (options.get || options.graphiql) {\n routes.unshift({ method: 'GET', path: context.path, name: 'handle', handler: transport.get })\n }\n return routes\n }\n\n /** Nothing to start: the handlers read the executor on the first request. */\n start(): void {}\n}\n","/**\n * `GraphQLPlugin` (RFC 0005 §5.11, §8.2): builds the schema from `metadata.extensions.graphql`,\n * provides `GraphQLContext`, `PubSub` and itself to the container, executes operations\n * (`execute()`, `subscribe()`, the `engine` of drivers, RFC 0009) and contributes the routes of its\n * driver (the built-in GraphQL-over-HTTP endpoint by default) to `HttpPlugin`.\n */\nimport type {\n Container,\n CoreLogger,\n Hooks,\n Plugin,\n PluginContext,\n PluginOptions,\n PluginRootsContext,\n ProviderKey,\n Token,\n ZnightMetadata,\n} from '@znight/core'\nimport type { HttpPlugin, PluginHttpRoutes, PluginHttpRoutesContext, PluginRoute, SseOptions } from '@znight/http'\nimport type { FormattedExecutionResult, GraphQLSchema } from 'graphql'\nimport type { CheckedField } from './decisions.ts'\nimport type { GraphQLDriver, GraphQLDriverRoute } from './driver.ts'\nimport type { GraphQLEngine } from './engine.ts'\nimport type { ExecuteOptions, GraphQLRequest, GraphQLResultStream } from './execution.ts'\nimport type { Resolvable } from './format.ts'\nimport type { GraphQLInputTypeDefinition, GraphQLMetadata, GraphQLResolverBinding } from './metadata.ts'\nimport type { GraphQLPluginOptions, ResolvedGraphQLOptions } from './options.ts'\nimport type { GraphQLErrorMapper, GraphQLGuard, GraphQLResultMapper } from './types.ts'\n\nimport { displayName, ErrorCode, resolveOptions, ZnightError } from '@znight/core'\nimport { printSchema } from 'graphql'\n\nimport { checkFieldDecisions } from './decisions.ts'\nimport { Engine } from './engine.ts'\nimport { GraphQLExecutor, singleResult } from './execution.ts'\nimport { ErrorFormatter } from './format.ts'\nimport { LoaderFactory } from './loaders.ts'\nimport { MemoryPubSub } from './memory-pubsub.ts'\nimport { invalidOption, resolveGraphQLOptions } from './options.ts'\nimport { globalGuardsApply, pipelineFactory } from './pipeline.ts'\nimport { PubSub } from './pubsub.ts'\nimport { checkResultTypes, declaredTypes, ResultMappers } from './results.ts'\nimport { buildGraphQLSchema, checkGraphQLSection, graphqlSection } from './schema.ts'\nimport { GraphQLTokens } from './tokens.ts'\nimport { BUILTIN_DRIVER, BuiltinDriver } from './transport/builtin.ts'\nimport { checkSseOptions } from './transport/http.ts'\n\n/** Options of {@link GraphQLPlugin.execute} and {@link GraphQLPlugin.subscribe}. */\nexport interface DirectExecuteOptions {\n /** Cancels the operation (graphql-js `abortSignal`, `GraphQLContext.signal`). */\n readonly signal?: AbortSignal\n /** `GraphQLContext.requestId`. Default: the request id of the enclosing scope, or a UUID. */\n readonly requestId?: string\n}\n\n/** What the plugin built at bootstrap. */\ninterface Runtime {\n readonly schema: GraphQLSchema\n readonly section: GraphQLMetadata\n readonly executor: GraphQLExecutor\n readonly engine: GraphQLEngine\n}\n\nlet readExecutor: (plugin: GraphQLPlugin) => GraphQLExecutor\nlet readEndpoint: (plugin: GraphQLPlugin) => string | undefined\n\n/**\n * The executor of a bootstrapped plugin: the internal API of the transports (statuses, streams).\n * Not exported from the package entry.\n */\nexport function executorOf(plugin: GraphQLPlugin): GraphQLExecutor {\n return readExecutor(plugin)\n}\n\n/**\n * The absolute path of the GraphQL-over-HTTP endpoint (prefix included), `undefined` without HTTP\n * transport (`http: false`, or before `HttpPlugin` collected the routes). Not exported from the\n * package entry: `@znight/graphql/testing` sends its requests there.\n */\nexport function endpointOf(plugin: GraphQLPlugin): string | undefined {\n return readEndpoint(plugin)\n}\n\n/** A value of type `T` or a promise of it. */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * The GraphQL plugin: `GraphQLPlugin.configure(options)` (name `graphql`).\n *\n * ```ts\n * await Application.create({\n * metadata: __ZNIGHT_METADATA__,\n * plugins: [HttpPlugin.configure(), GraphQLPlugin.configure({ guards: [AccessGuard] })],\n * })\n * ```\n */\nexport class GraphQLPlugin implements Plugin, PluginHttpRoutes {\n readonly name = 'graphql'\n readonly #options: PluginOptions<GraphQLPluginOptions>\n #resolved: ResolvedGraphQLOptions | undefined\n #container: Container | undefined\n #metadata: ZnightMetadata | undefined\n #logger: CoreLogger | undefined\n #hooks: Hooks | undefined\n #pubsub: PubSub | undefined\n #ownPubSub: MemoryPubSub | undefined\n #runtime: Runtime | undefined\n #stop: AbortController | undefined\n #endpoint: string | undefined\n /** The driver serving the schema: the `driver` option, or the built-in transport. */\n #driver: GraphQLDriver | undefined\n /** The driver was started (`onBootstrap`): `onStop` stops it. */\n #started = false\n #active = false\n\n private constructor(options: PluginOptions<GraphQLPluginOptions>) {\n this.#options = options\n }\n\n static {\n readExecutor = plugin => plugin.#ready().executor\n readEndpoint = plugin => plugin.#endpoint\n }\n\n /**\n * Creates the plugin. `options` may be a function of the container, evaluated once, when first\n * needed after the container is initialised: `GraphQLPlugin.configure(c => ({ exposeErrors: c.get(Env).dev }))`.\n */\n static configure(options: PluginOptions<GraphQLPluginOptions> = {}): GraphQLPlugin {\n return new GraphQLPlugin(options)\n }\n\n /**\n * Providers `TestApp` creates at boot: the classes of the `guards`, `errorMappers` and `resultMappers` options, and\n * the resolvers, guards and loaders of the metadata.\n */\n initRoots(context?: PluginRootsContext): readonly ProviderKey[] {\n const roots = new Set<ProviderKey>()\n try {\n const options: unknown = this.#options\n if (options !== null && typeof options === 'object') {\n for (const key of ['guards', 'errorMappers', 'resultMappers'] as const) {\n const refs: unknown = (options as GraphQLPluginOptions)[key]\n if (Array.isArray(refs)) for (const ref of refs) if (typeof ref === 'function') roots.add(ref as ProviderKey)\n }\n }\n const types: unknown = (context?.metadata.extensions?.graphql as { types?: unknown } | undefined)?.types\n if (Array.isArray(types)) {\n for (const type of types as { fields?: unknown }[]) {\n if (!Array.isArray(type?.fields)) continue\n for (const field of type.fields as { resolver?: Partial<GraphQLResolverBinding> }[]) {\n const binding = field?.resolver\n if (binding === undefined || typeof binding.token !== 'string') continue\n roots.add(binding.token)\n for (const token of [...(binding.guards ?? []), ...(binding.loaders ?? [])]) {\n if (typeof token === 'string') roots.add(token)\n }\n }\n }\n }\n } catch {\n // initRoots never throws: register() reports malformed options and metadata\n }\n return [...roots]\n }\n\n register(ctx: PluginContext): void {\n if (this.#active) {\n throw new ZnightError(ErrorCode.DuplicateProvider, 'This GraphQLPlugin is already used by another application', {\n hints: ['Call GraphQLPlugin.configure() once per application'],\n })\n }\n this.#resolved = undefined\n this.#runtime = undefined\n this.#ownPubSub = undefined\n this.#endpoint = undefined\n this.#driver = undefined\n this.#started = false\n this.#container = ctx.container\n this.#metadata = ctx.metadata\n this.#logger = ctx.logger\n this.#hooks = ctx.hooks\n if (typeof this.#options !== 'function') {\n // static options: validated now, and the HTTP transport needs HttpPlugin\n this.#checkHttp(ctx, this.#resolve())\n }\n this.#active = true\n this.#stop = new AbortController()\n ctx.container.registerExternal({ token: GraphQLTokens.Context, scope: 'request', providedBy: 'GraphQLPlugin' })\n ctx.container.registerValue(\n GraphQLTokens.PubSub,\n typeof this.#options === 'function' ? new DeferredPubSub(() => this.pubsub) : this.pubsub,\n )\n ctx.container.registerValue(GraphQLTokens.Plugin, this)\n }\n\n /**\n * The `PluginHttpRoutes` contract of `@znight/http`: the routes of the driver, with the `http`\n * option's meta and guards, and its body limit on the routes that are not `GET`. For the built-in\n * transport, the GraphQL endpoint (`GET` and `POST` on `path`). `[]` with `http: false`.\n */\n httpRoutes(context: PluginHttpRoutesContext): readonly PluginRoute[] {\n this.#container ??= context.container\n const options = this.#resolve()\n const http = options.http\n if (http === false) return []\n const driver = this.#driverOf(options)\n // a server-mounted driver attaches itself to the adapter in start()\n if (driver.routes === undefined) return []\n const endpoint = endpointPath(context.prefix, options.path)\n const routes = driver.routes({ path: options.path, endpoint })\n if (!Array.isArray(routes))\n throw invalidOption(`routes() of the ${driver.name} driver`, 'an array of routes', routes)\n this.#endpoint = endpoint\n return routes.map(route => mount(route, http, driver))\n }\n\n onBootstrap(ctx: PluginContext): void | Promise<void> {\n this.#container = ctx.container\n const options = this.#resolve()\n if (typeof this.#options === 'function') this.#checkHttp(ctx, options)\n if (options.driver === undefined) this.#checkSse(options)\n const runtime = this.#build(ctx, options)\n this.#runtime = runtime\n const driver = this.#driverOf(options)\n // the built-in transport reads the executor on its first request: nothing to start\n if (options.driver === undefined) return\n let started: void | Promise<void>\n try {\n started = driver.start(runtime.engine, {\n logger: ctx.logger,\n container: ctx.container,\n http: ctx.getPlugin<HttpPlugin>('http'),\n })\n } catch (error) {\n throw driverFailed(driver, error)\n }\n if (!isPromise(started)) {\n this.#started = true\n return\n }\n return started.then(\n () => {\n this.#started = true\n },\n (error: unknown) => {\n throw driverFailed(driver, error)\n },\n )\n }\n\n onStart(ctx: PluginContext): void {\n const runtime = this.#runtime\n const options = this.#resolved\n if (runtime === undefined || options === undefined) return\n const details = { types: runtime.section.types.length, schemaHash: runtime.section.schemaHash }\n if (options.http === false) ctx.logger.info('GraphQL schema ready', details)\n else ctx.logger.info('GraphQL endpoint ready', { path: options.path, ...details })\n }\n\n /**\n * The `PluginHttpRoutes` contract: `HttpPlugin` starts draining, whatever the plugin order. The\n * subscriptions of the engine end (a route-mounted driver serves them as streamed responses\n * `HttpPlugin` does not close), and new ones are refused (503); queries and mutations in flight\n * are served. Built-in SSE streams are closed by `HttpPlugin` itself.\n */\n onHttpDrain(): Promise<void> | undefined {\n return this.#runtime?.executor.stopEngineStreams()\n }\n\n async onStop(): Promise<void> {\n this.#stop?.abort(new Error('The application is stopping'))\n // direct subscriptions and the driver's (engine) ones; built-in SSE streams end with HttpPlugin\n await this.#runtime?.executor.stopStreams()\n // a route-mounted driver serves requests until HttpPlugin drained them: it stops in onDispose\n if (this.#driver?.routes === undefined) await this.#stopDriver()\n }\n\n onDispose(): void | Promise<void> {\n if (!this.#started) {\n this.#release()\n return\n }\n // after HttpPlugin drained (every onStop ran), or disposed without having started (onStop did not run)\n this.#stop?.abort(new Error('The application is stopping'))\n return Promise.resolve(this.#runtime?.executor.stopStreams())\n .then(() => this.#stopDriver())\n .finally(() => this.#release())\n }\n\n /** Stops the driver started in onBootstrap (once). */\n #stopDriver(): void | Promise<void> {\n const driver = this.#driver\n if (!this.#started) return\n this.#started = false\n return driver?.stop?.()\n }\n\n #release(): void {\n this.#active = false\n this.#ownPubSub?.close()\n this.#ownPubSub = undefined\n this.#pubsub = undefined\n this.#runtime?.executor.clear()\n this.#runtime = undefined\n this.#resolved = undefined\n }\n\n /** The schema (after bootstrap). */\n get schema(): GraphQLSchema {\n return this.#ready().schema\n }\n\n /**\n * The GraphQL engine (after bootstrap, RFC 0009): graphql-js-shaped `parse`, `validate`, `execute`\n * and `subscribe` running this plugin's schema with its guards, loaders, request scope, error\n * formatting and hook. What drivers receive in `start()`; any GraphQL server can call it.\n */\n get engine(): GraphQLEngine {\n return this.#ready().engine\n }\n\n /** The SDL of the schema (graphql-js `printSchema`). */\n printSchema(): string {\n return printSchema(this.#ready().schema)\n }\n\n /** The `PubSub` of the application: the `pubsub` option, or the plugin's `MemoryPubSub`. */\n get pubsub(): PubSub {\n let pubsub = this.#pubsub\n if (pubsub === undefined) {\n const options = this.#resolve()\n if (options.pubsub === undefined) {\n this.#ownPubSub = new MemoryPubSub({ bufferSize: options.bufferSize })\n pubsub = this.#ownPubSub\n } else {\n // the option accepts a PubSub of any event map; the container hands it out untyped\n pubsub = options.pubsub as unknown as PubSub\n }\n this.#pubsub = pubsub\n }\n return pubsub\n }\n\n /** Active subscriptions (every transport). */\n get activeSubscriptions(): number {\n return this.#runtime?.executor.activeSubscriptions ?? 0\n }\n\n /**\n * Executes a query or a mutation outside of HTTP (custom transports, tests, a controller calling\n * GraphQL), in the current request scope or in a scope of its own. Returns the result directly\n * when every resolver is synchronous; `await` it. A subscription is an error result: use\n * {@link subscribe}. Rejects only when `options.signal` aborts the execution.\n */\n execute(request: GraphQLRequest, options?: DirectExecuteOptions): MaybePromise<FormattedExecutionResult> {\n const response = this.#ready().executor.execute(request, direct(options))\n return isPromise(response) ? response.then(settled => settled.result) : response.result\n }\n\n /**\n * Subscribes outside of HTTP: the results of the subscription, one per event, until the source\n * ends, `options.signal` aborts, `return()` is called or the application stops. A request error\n * or a query gives a stream of one result.\n */\n async subscribe(request: GraphQLRequest, options?: DirectExecuteOptions): Promise<GraphQLResultStream> {\n const response = await this.#ready().executor.subscribe(request, direct(options))\n return 'status' in response ? singleResult(response.result) : response\n }\n\n // ------------------------------------------------------------------------------------------------\n\n #ready(): Runtime {\n const runtime = this.#runtime\n if (runtime === undefined) {\n throw new ZnightError(ErrorCode.LifecycleFailed, 'GraphQLPlugin is not bootstrapped yet', {\n hints: ['The schema and execute() are available once Application.create() resolved'],\n })\n }\n return runtime\n }\n\n #resolve(): ResolvedGraphQLOptions {\n if (this.#resolved !== undefined) return this.#resolved\n const container = this.#container\n if (container === undefined && typeof this.#options === 'function') {\n throw new ZnightError(ErrorCode.LifecycleFailed, 'GraphQLPlugin: the options are not available before register()')\n }\n this.#resolved = resolveGraphQLOptions(resolveOptions(this.#options, container as Container))\n return this.#resolved\n }\n\n /** The driver of the application: the `driver` option, or the built-in transport. */\n #driverOf(options: ResolvedGraphQLOptions): GraphQLDriver {\n let driver = this.#driver\n if (driver === undefined) {\n const http = options.http\n driver =\n options.driver ??\n new BuiltinDriver({\n // called on the first request: the routes are collected before or after this plugin's onBootstrap\n executor: () => this.#ready().executor,\n get: http !== false && http.get,\n graphiql: options.graphiql,\n sse: sseOptions(options),\n })\n this.#driver = driver\n }\n return driver\n }\n\n /** The SSE options are those of `HttpResponse.sse()` (heartbeat and maxDuration from 1 000 ms): checked at boot. */\n #checkSse(options: ResolvedGraphQLOptions): void {\n const sse = sseOptions(options)\n if (sse === false) return\n const problem = checkSseOptions(sse)\n if (problem !== undefined) throw invalidOption('subscriptions', `valid event stream options (${problem})`, sse)\n }\n\n #checkHttp(ctx: PluginContext, options: ResolvedGraphQLOptions): void {\n const driver = options.driver\n if (options.http === false && driver?.routes !== undefined) {\n throw new ZnightError(\n ErrorCode.InvalidGraphQLSetup,\n `GraphQLPlugin: the ${driver.name} driver serves routes, which http: false turns off`,\n { hints: ['Remove http: false: the driver serves the endpoint through HttpPlugin'] },\n )\n }\n if (options.http !== false && ctx.getPlugin('http') === undefined) {\n throw new ZnightError(\n ErrorCode.InvalidGraphQLSetup,\n 'GraphQLPlugin serves its endpoint through HttpPlugin, which is not registered',\n {\n hints: [\n 'Add HttpPlugin.configure() to the plugins of the application',\n 'Or set http: false to use the schema and execute() only',\n ],\n },\n )\n }\n }\n\n #build(ctx: PluginContext, options: ResolvedGraphQLOptions): Runtime {\n const container = ctx.container\n const metadata = ctx.metadata\n const section = graphqlSection(metadata)\n const providers = new Providers(container, metadata)\n const globalGuards = options.guards.map(ref => providers.ref<GraphQLGuard>(ref, 'guard', 'canResolve'))\n const mappers = options.errorMappers.map(ref => providers.ref<GraphQLErrorMapper>(ref, 'error mapper', 'map'))\n const resultMappers = options.resultMappers.map(ref => ({\n ...providers.ref<GraphQLResultMapper>(ref, 'result mapper', 'toResult'),\n types: declaredTypes(ref),\n }))\n const inputs = new Map<string, GraphQLInputTypeDefinition>()\n const fields: CheckedField[] = []\n const types = Array.isArray(section?.types) ? section.types : []\n for (const type of types) {\n if (type?.kind === 'input') inputs.set(type.name, type)\n if (type?.kind !== 'object' || !Array.isArray(type.fields)) continue\n for (const field of type.fields) {\n const binding = field?.resolver\n if (binding === undefined || binding === null || typeof binding !== 'object') continue\n const root = binding.operation !== 'field'\n const guardRefs: readonly Token[] = Array.isArray(binding.guards) ? binding.guards : []\n fields.push({\n description: `${type.name}.${field.name} (${displayName(String(binding.token))}.${String(binding.method)})`,\n root,\n meta: binding.meta ?? {},\n guards: [\n ...(globalGuardsApply(binding) ? globalGuards.map(guard => ({ cls: guard.cls, name: guard.name })) : []),\n ...guardRefs.map(token => ({ cls: metadata.providers[token]?.class, name: displayName(token) })),\n ],\n })\n }\n }\n // a malformed section is reported by buildGraphQLSchema, not as types missing from it\n if (resultMappers.length > 0 && checkGraphQLSection(section).length === 0) checkResultTypes(resultMappers, types)\n const results = new ResultMappers(\n container,\n ctx.logger,\n resultMappers.map(mapper => ({\n resolvable: mapper.resolvable,\n name: mapper.name,\n types: mapper.types as readonly string[],\n })),\n types,\n )\n const schema = buildGraphQLSchema(\n section,\n pipelineFactory({\n container,\n globalGuards: globalGuards.map(guard => guard.resolvable),\n guard: (token, coordinate) => providers.token<GraphQLGuard>(token, `guard of ${coordinate}`, 'canResolve'),\n resolver: (binding, coordinate) =>\n providers.token<object>(binding.token, `resolver of ${coordinate}`, binding.method),\n paramResolver: (token, coordinate) =>\n providers.token<object>(token, `parameter resolver of ${coordinate}`, 'resolve'),\n inputs,\n results: (field, coordinate) => results.recover(field, coordinate),\n }),\n )\n checkFieldDecisions(fields, section.groups, options.enforcement, ctx.logger)\n const formatter = new ErrorFormatter({\n container,\n mappers: mappers.map(mapper => mapper.resolvable),\n exposeErrors: options.exposeErrors,\n logger: ctx.logger,\n schema,\n })\n const executor = new GraphQLExecutor({\n schema,\n container,\n hooks: ctx.hooks,\n logger: ctx.logger,\n formatter,\n runtime: {\n container,\n loaders: new LoaderFactory(container),\n signal: (this.#stop as AbortController).signal,\n },\n limits: options.limits,\n introspection: options.introspection,\n documentCache: options.documentCache,\n maxActiveSubscriptions: options.subscriptions === false ? undefined : options.subscriptions.maxActive,\n subscriptions: options.subscriptions !== false,\n })\n const http = ctx.getPlugin<HttpPlugin>('http')\n const engine = new Engine(\n executor,\n {\n path:\n this.#endpoint ?? endpointPath(options.http === false || http === undefined ? '' : http.prefix, options.path),\n introspection: options.introspection,\n ide: options.graphiql,\n exposeErrors: options.exposeErrors,\n maxTokens: options.limits.maxTokens,\n subscriptions: options.subscriptions === false ? false : { maxActive: options.subscriptions.maxActive },\n http: options.http === false ? false : { get: options.http.get, bodyLimit: options.http.bodyLimit },\n },\n options.driver?.name ?? BUILTIN_DRIVER,\n )\n ctx.logger.debug('GraphQL schema built', {\n types: types.length,\n schemaHash: section.schemaHash,\n ...(results.fields === 0 ? {} : { resultFields: results.fields }),\n })\n return { schema, section, executor, engine }\n }\n}\n\nfunction direct(options: DirectExecuteOptions | undefined): ExecuteOptions {\n if (options === undefined) return DIRECT\n return {\n transport: 'direct',\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(options.requestId === undefined ? {} : { requestId: options.requestId }),\n }\n}\n\nconst DIRECT: ExecuteOptions = Object.freeze({ transport: 'direct' })\n\n/** A route of the driver as a plugin route: the `http` option's meta and guards, its body limit unless `GET`. */\nfunction mount(\n route: GraphQLDriverRoute,\n http: Exclude<ResolvedGraphQLOptions['http'], false>,\n driver: GraphQLDriver,\n): PluginRoute {\n if (route === null || typeof route !== 'object' || typeof route.handler !== 'function') {\n throw invalidOption(`routes() of the ${driver.name} driver`, 'routes { method, path, name, handler }', route)\n }\n return {\n method: route.method,\n path: route.path,\n name: route.name,\n handler: route.handler,\n ...(http.meta.length === 0 ? {} : { meta: http.meta }),\n ...(http.guards.length === 0 ? {} : { guards: http.guards }),\n ...(route.method === 'GET' || route.method === 'HEAD' ? {} : { bodyLimit: http.bodyLimit }),\n }\n}\n\n/** ZNIGHT066 for a driver whose `start()` failed, the original error as `cause`. */\nfunction driverFailed(driver: GraphQLDriver, error: unknown): ZnightError {\n return new ZnightError(ErrorCode.InvalidGraphQLSetup, `GraphQLPlugin: the ${driver.name} driver failed to start`, {\n cause: error,\n hints: ['See the cause: the driver could not create its server'],\n })\n}\n\n/** `prefix` (`''`, `/api`) joined with `path` (`/graphql`), without trailing slash: `/api/graphql`. */\nfunction endpointPath(prefix: string, path: string): string {\n const joined = `${prefix.replace(/\\/+$/, '')}/${path.replace(/^\\/+|\\/+$/g, '')}`\n return joined.length > 1 && joined.endsWith('/') ? joined.slice(0, -1) : joined\n}\n\n/** The `HttpResponse.sse()` options of GraphQL over SSE (`subscriptions`), `false` when disabled. */\nfunction sseOptions(options: ResolvedGraphQLOptions): SseOptions | false {\n const subscriptions = options.subscriptions\n if (subscriptions === false) return false\n return Object.freeze({\n ...(subscriptions.heartbeat === undefined ? {} : { heartbeat: subscriptions.heartbeat }),\n ...(subscriptions.maxDuration === undefined ? {} : { maxDuration: subscriptions.maxDuration }),\n })\n}\n\nfunction isPromise<T>(value: T | Promise<T>): value is Promise<T> {\n return typeof (value as { then?: unknown } | null)?.then === 'function'\n}\n\n/**\n * Resolves providers once at bootstrap: singletons (and registered values) to their instance,\n * request-scoped and transient providers to their token, resolved per use in the current scope.\n */\nclass Providers {\n readonly #container: Container\n readonly #metadata: ZnightMetadata\n readonly #resolvables = new Map<Token, Resolvable<unknown>>()\n\n constructor(container: Container, metadata: ZnightMetadata) {\n this.#container = container\n this.#metadata = metadata\n }\n\n /** A provider token (`@UseGuard`, a resolver), checked to have `method` when its class is known. */\n token<T>(token: Token, what: string, method: string): Resolvable<T> {\n const cls: unknown = Object.hasOwn(this.#metadata.providers, token)\n ? this.#metadata.providers[token]?.class\n : undefined\n if (\n typeof cls === 'function' &&\n typeof (cls.prototype as Record<string, unknown> | undefined)?.[method] !== 'function'\n ) {\n throw new ZnightError(\n ErrorCode.InvalidGraphQLSetup,\n `GraphQLPlugin: the ${what} (${displayName(token)}) has no ${method}() method`,\n {\n hints:\n method === 'canResolve'\n ? ['A GraphQL guard implements GraphQLGuard: canResolve(ctx: ResolverContext)']\n : [],\n },\n )\n }\n return this.#resolvable<T>(token, what)\n }\n\n /** A global ref: a provider class or an instance with `method`. */\n ref<T>(\n ref: unknown,\n what: string,\n method: string,\n ): { readonly resolvable: Resolvable<T>; readonly cls: unknown; readonly name: string } {\n if (typeof ref === 'function') {\n const token = this.#container.tokenOf(ref as ProviderKey)\n if (token === undefined) {\n const name = (ref as { name?: string }).name || '<anonymous>'\n throw new ZnightError(\n ErrorCode.MissingProvider,\n `GraphQLPlugin: the global ${what} ${name} is not a provider`,\n {\n hints: ['Add @Injectable() to the class, or pass an instance'],\n },\n )\n }\n const prototype: unknown = (ref as { prototype?: unknown }).prototype\n if (typeof (prototype as Record<string, unknown> | undefined)?.[method] !== 'function') {\n throw invalidOption(`${what}s`, `classes with a ${method}() method`, ref)\n }\n return { resolvable: this.#resolvable<T>(token, `global ${what}`), cls: ref, name: displayName(token) }\n }\n const cls: unknown = (ref as { constructor?: unknown }).constructor\n const name = typeof cls === 'function' && cls !== Object ? (cls as { name?: string }).name : undefined\n return { resolvable: { instance: ref as T }, cls, name: name || `${what} instance` }\n }\n\n #resolvable<T>(token: Token, what: string): Resolvable<T> {\n let found = this.#resolvables.get(token)\n if (found === undefined) {\n found = this.#create(token, what)\n this.#resolvables.set(token, found)\n }\n return found as Resolvable<T>\n }\n\n #create(token: Token, what: string): Resolvable<unknown> {\n const container = this.#container\n if (!container.has(token)) {\n throw new ZnightError(ErrorCode.MissingProvider, `GraphQLPlugin: the ${what} (${token}) is not a provider`, {\n hints: ['Add @Injectable() to the class (resolvers are providers through @Resolver())'],\n })\n }\n const scope = Object.hasOwn(this.#metadata.providers, token) ? this.#metadata.providers[token]?.scope : undefined\n if (scope === 'request' || scope === 'transient') return { token }\n try {\n return { instance: container.get(token) }\n } catch (error) {\n if ((error as { code?: unknown } | null)?.code === ErrorCode.NoActiveScope) return { token }\n throw error\n }\n }\n}\n\n/**\n * The `PubSub` registered when the options are a function of the container (they are only known\n * after `container.init()`): delegates to the plugin's `PubSub`, resolved on first use.\n */\nclass DeferredPubSub extends PubSub {\n readonly #target: () => PubSub\n\n constructor(target: () => PubSub) {\n super()\n this.#target = target\n }\n\n publish(topic: string, payload: unknown): Promise<void> {\n return this.#target().publish(topic, payload)\n }\n\n subscribe(topic: string, options?: { readonly signal?: AbortSignal }): AsyncIterableIterator<unknown> {\n return this.#target().subscribe(topic, options)\n }\n}\n"],"mappings":";;;;;;;;;;;AAsBA,IAAa,gBAAb,MAA2B;CACzB;CACA,2BAAoB,IAAI,IAAkC;CAE1D,YAAY,WAAsB;EAChC,KAAK,aAAa;CACpB;;CAGA,OAAO,OAA6C;EAClD,MAAM,WAAW,KAAK,WAAW,IAAI,KAAK;EAC1C,IAAI,aAAa,QAAQ,OAAO,aAAa,YAAY,OAAO,SAAS,SAAS,YAChF,MAAM,IAAI,YACR,UAAU,eACV,cAAc,MAAM,uDACpB,EAAE,OAAO,CAAC,+EAA+E,EAAE,CAC7F;EAEF,IAAI,UAAU,KAAK,SAAS,IAAI,KAAK;EACrC,IAAI,YAAY,KAAA,GAAW;GACzB,UAAU,YAAY,OAAO,SAAS,OAAO;GAC7C,KAAK,SAAS,IAAI,OAAO,OAAO;EAClC;EACA,OAAO,IAAI,YACT,SAAQ,UAAU,OAAO,MAAM,QAAuC,GACtE,OACF;CACF;AACF;;;;;;AAOA,eAAe,UACb,OACA,MACA,UAC6B;CAC7B,MAAM,SAAkB,MAAM,SAAS,KAAK,IAAI;CAChD,IAAI,MAAM,QAAQ,MAAM,KAAK,OAAO,WAAW,KAAK,QAAQ,OAAO;CACnE,MAAM,IAAI,YACR,UAAU,eACV,cAAc,MAAM,YAAY,MAAM,QAAQ,MAAM,IAAI,GAAG,OAAO,OAAO,WAAW,WAAW,OAAO,KAAK,OAAO,QAClH,EAAE,OAAO,CAAC,8FAA8F,EAAE,CAC5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K,QAAQ,OAAO,IAAI;GAChC,KAAK,aAAa,IAAI,OAAO,KAAK;EACpC;EACA,OAAO;CACT;CAEA,QAAQ,OAAc,MAAmC;EACvD,MAAM,YAAY,KAAK;EACvB,IAAI,CAAC,UAAU,IAAI,KAAK,GACtB,MAAM,IAAI,YAAY,UAAU,iBAAiB,sBAAsB,KAAK,IAAI,MAAM,sBAAsB,EAC1G,OAAO,CAAC,8EAA8E,EACxF,CAAC;EAEH,MAAM,QAAQ,OAAO,OAAO,KAAK,UAAU,WAAW,KAAK,IAAI,KAAK,UAAU,UAAU,MAAM,EAAE,QAAQ,KAAA;EACxG,IAAI,UAAU,aAAa,UAAU,aAAa,OAAO,EAAE,MAAM;EACjE,IAAI;GACF,OAAO,EAAE,UAAU,UAAU,IAAI,KAAK,EAAE;EAC1C,SAAS,OAAO;GACd,IAAK,OAAqC,SAAS,UAAU,eAAe,OAAO,EAAE,MAAM;GAC3F,MAAM;EACR;CACF;AACF;;;;;AAMA,IAAM,iBAAN,cAA6B,OAAO;CAClC;CAEA,YAAY,QAAsB;EAChC,MAAM;EACN,KAAK,UAAU;CACjB;CAEA,QAAQ,OAAe,SAAiC;EACtD,OAAO,KAAK,QAAQ,CAAC,CAAC,QAAQ,OAAO,OAAO;CAC9C;CAEA,UAAU,OAAe,SAA6E;EACpG,OAAO,KAAK,QAAQ,CAAC,CAAC,UAAU,OAAO,OAAO;CAChD;AACF"}
@@ -1,4 +1,4 @@
1
- import { E as LoaderKey, O as LoaderValue, f as BatchLoad, m as BatchLoader, t as GraphQLDriver } from "./driver-Cnze8Oyr.mjs";
1
+ import { E as LoaderKey, O as LoaderValue, f as BatchLoad, m as BatchLoader, t as GraphQLDriver } from "./driver-DgbpFj4-.mjs";
2
2
  import { HttpAdapter } from "@znight/http";
3
3
  import { GraphQLFormattedError } from "graphql";
4
4
  import { MockFunction, TestApp } from "@znight/testing";
package/dist/testing.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as endpointOf, r as executorOf, t as GraphQLPlugin } from "./plugin-q4oz7d6s.mjs";
1
+ import { n as endpointOf, r as executorOf, t as GraphQLPlugin } from "./plugin-BssB7wtn.mjs";
2
2
  import { HttpPlugin, NotFoundException, parseSseStream } from "@znight/http";
3
3
  import { TestApp, defineTestMetadata, resolveMockFn, testToken } from "@znight/testing";
4
4
  import { deepStrictEqual, ok, strictEqual } from "node:assert/strict";
package/dist/yoga.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { g as GraphQLContext, t as GraphQLDriver } from "./driver-Cnze8Oyr.mjs";
1
+ import { g as GraphQLContext, t as GraphQLDriver } from "./driver-DgbpFj4-.mjs";
2
2
  import { HttpContext } from "@znight/http";
3
3
  import { GraphiQLOptions, YogaInitialContext, YogaServerInstance, YogaServerOptions } from "graphql-yoga";
4
4
  /** The server context the driver gives Yoga: the `HttpContext` of the route, as `znight`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@znight/graphql",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Znight GraphQL: code-first GraphQL whose schema is derived from TypeScript types at build time, on graphql-js 17",
5
5
  "license": "MIT",
6
6
  "author": "Ugho STEPHAN",
@@ -52,13 +52,13 @@
52
52
  "access": "public"
53
53
  },
54
54
  "dependencies": {
55
- "@znight/core": "0.3.0",
55
+ "@znight/core": "0.4.0",
56
56
  "dataloader": "^2.2.3"
57
57
  },
58
58
  "peerDependencies": {
59
- "@znight/http": "^0.3.0",
60
- "@znight/compiler": "^0.3.0",
61
- "@znight/testing": "^0.3.0",
59
+ "@znight/http": "^0.4.0",
60
+ "@znight/compiler": "^0.4.0",
61
+ "@znight/testing": "^0.4.0",
62
62
  "graphql": "^17.0.2",
63
63
  "graphql-yoga": "^6.0.1"
64
64
  },
@@ -75,9 +75,9 @@
75
75
  },
76
76
  "devDependencies": {
77
77
  "@testcontainers/redis": "12.2.1",
78
- "@znight/compiler": "0.3.0",
79
- "@znight/http": "0.3.0",
80
- "@znight/testing": "0.3.0",
78
+ "@znight/compiler": "0.4.0",
79
+ "@znight/http": "0.4.0",
80
+ "@znight/testing": "0.4.0",
81
81
  "graphql": "17.0.2",
82
82
  "graphql-http": "1.23.1",
83
83
  "graphql-sse": "2.6.3",
@@ -471,6 +471,33 @@ function parameterDecorators(param: ParameterInfo): DecoratorInfo[] {
471
471
 
472
472
  function analyzeParameter(ctx: Context, cls: ClassInfo, param: ParameterInfo, where: string): ParamData | undefined {
473
473
  const decorators = parameterDecorators(param)
474
+ // custom parameter decorators (RFC 0010); compilers before it have no paramDecorator
475
+ const custom = typeof ctx.paramDecorator === 'function' ? ctx.paramDecorator(param, 'graphql', cls) : undefined
476
+ if (custom !== undefined) {
477
+ for (const other of decorators) {
478
+ error(
479
+ ctx,
480
+ Codes.InvalidDecorator,
481
+ other.location,
482
+ `Parameter '${param.name}' of ${where} has several parameter decorators (@${custom.decorator.name} and @${other.name})`,
483
+ ['Keep a single parameter decorator'],
484
+ )
485
+ }
486
+ if (!custom.ok || decorators.length > 0) return undefined
487
+ const data = custom.data
488
+ return {
489
+ kind: 'custom',
490
+ identity: custom.identity,
491
+ name: custom.name,
492
+ data: data === undefined ? undefined : { value: data.ref ?? (data.value as StaticValue) },
493
+ resolver: custom.resolver.kind === 'class' ? custom.resolver.ref : undefined,
494
+ ...(custom.resolver.kind === 'class' && custom.resolver.arity !== undefined
495
+ ? { arity: custom.resolver.arity }
496
+ : {}),
497
+ cast: custom.cast,
498
+ location: custom.location,
499
+ }
500
+ }
474
501
  const decorator = decorators[0]
475
502
  if (decorator === undefined) {
476
503
  const lookAlike = param.decorators.find(
@@ -5,7 +5,7 @@
5
5
  * parameters are looked up again by name and index (`ctx.classInfo(host.identity)`).
6
6
  */
7
7
 
8
- import type { BindingHandle, ClassInfo, ClassRef, Location, ValueRef } from '@znight/compiler'
8
+ import type { BindingHandle, ClassInfo, ClassRef, Location, StaticValue, ValueRef } from '@znight/compiler'
9
9
  import type { Scope } from '@znight/core'
10
10
  import type { MetaEntry } from '@znight/http/compiler'
11
11
 
@@ -78,6 +78,25 @@ export type ParamData =
78
78
  readonly identity: string
79
79
  readonly location: Location
80
80
  }
81
+ | {
82
+ /** A custom parameter decorator (`createParamDecorator`, RFC 0010). */
83
+ readonly kind: 'custom'
84
+ /** Canonical identity of the decorator `const` (imported by the generated module). */
85
+ readonly identity: string
86
+ readonly name: string
87
+ /** The data argument (a value, possibly holding references, or a reference); `undefined` without argument. */
88
+ readonly data: { readonly value: StaticValue } | undefined
89
+ /** The class resolver (`x[i].resolve(f, data)`); `undefined` for a function resolver. */
90
+ readonly resolver: ClassRef | undefined
91
+ /**
92
+ * Parameters of the class resolver's `resolve` (own, inherited or an arrow function property);
93
+ * `undefined` for a function, or when the compiler cannot read it (the call is cast).
94
+ */
95
+ readonly arity?: number
96
+ /** The value type could not be checked against the parameter. */
97
+ readonly cast: boolean
98
+ readonly location: Location
99
+ }
81
100
 
82
101
  /** Everything the extension stores. */
83
102
  export type GraphQLData = ResolverData