@znight/graphql 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +1062 -2
- package/dist/compiler.d.mts +93 -0
- package/dist/compiler.mjs +2832 -0
- package/dist/compiler.mjs.map +1 -0
- package/dist/index.d.mts +542 -0
- package/dist/index.mjs +128 -0
- package/dist/index.mjs.map +1 -0
- package/dist/names-BlzDM5cF.mjs +111 -0
- package/dist/names-BlzDM5cF.mjs.map +1 -0
- package/dist/plugin-BdBxr5NQ.mjs +3222 -0
- package/dist/plugin-BdBxr5NQ.mjs.map +1 -0
- package/dist/testing.d.mts +101 -0
- package/dist/testing.mjs +306 -0
- package/dist/testing.mjs.map +1 -0
- package/dist/types-CgbV9LjD.d.mts +234 -0
- package/package.json +95 -4
- package/src/compiler/analyze.ts +608 -0
- package/src/compiler/builder.ts +1640 -0
- package/src/compiler/constants.ts +74 -0
- package/src/compiler/data.ts +73 -0
- package/src/compiler/defaults.ts +92 -0
- package/src/compiler/discriminators.ts +53 -0
- package/src/compiler/docs.ts +55 -0
- package/src/compiler/generate.ts +405 -0
- package/src/compiler/ids.ts +128 -0
- package/src/compiler/index.ts +93 -0
- package/src/compiler/locate.ts +44 -0
- package/src/compiler/model.ts +122 -0
- package/src/compiler/options.ts +54 -0
- package/src/compiler/scalars.ts +138 -0
- package/src/compiler/sdl-view.ts +59 -0
- package/src/context.ts +181 -0
- package/src/decisions.ts +169 -0
- package/src/decorators.ts +196 -0
- package/src/errors.ts +89 -0
- package/src/execution.ts +1064 -0
- package/src/format.ts +285 -0
- package/src/index.ts +84 -0
- package/src/limits.ts +177 -0
- package/src/loaders.ts +149 -0
- package/src/memory-pubsub.ts +133 -0
- package/src/metadata.ts +195 -0
- package/src/names.ts +47 -0
- package/src/options.ts +309 -0
- package/src/pipeline.ts +277 -0
- package/src/plugin.ts +557 -0
- package/src/pubsub.ts +36 -0
- package/src/scalars.ts +131 -0
- package/src/schema-hash.ts +18 -0
- package/src/schema.ts +557 -0
- package/src/sdl.ts +515 -0
- package/src/testing.ts +454 -0
- package/src/tokens.ts +22 -0
- package/src/transport/abort.ts +80 -0
- package/src/transport/accept.ts +155 -0
- package/src/transport/graphiql.ts +106 -0
- package/src/transport/http.ts +373 -0
- package/src/transport/sse.ts +45 -0
- package/src/type-ref.ts +89 -0
- package/src/types.ts +190 -0
- package/src/validate-args.ts +48 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin-BdBxr5NQ.mjs","names":["count","DIRECT","DONE","GraphQLErrorClass","isPromise","show","isRecord","identity","isPromise"],"sources":["../src/errors.ts","../src/loaders.ts","../src/pubsub.ts","../src/memory-pubsub.ts","../src/decisions.ts","../src/context.ts","../src/format.ts","../src/limits.ts","../src/tokens.ts","../src/execution.ts","../src/options.ts","../src/pipeline.ts","../src/scalars.ts","../src/schema.ts","../src/transport/abort.ts","../src/transport/accept.ts","../src/transport/graphiql.ts","../src/transport/sse.ts","../src/transport/http.ts","../src/plugin.ts"],"sourcesContent":["/**\n * GraphQL errors shown to clients (RFC 0005 §5.10, §8.8): `GraphQLException` and the\n * `extensions.code` values the plugin produces (Apollo conventions, which clients already know).\n *\n * Import-free: the exception is a plain `Error` subclass, rendered by the runtime as\n * `{ message, locations, path, extensions: { code, ...extensions } }`.\n */\n\n/** `extensions.code` values produced by `@znight/graphql`. Applications may use their own codes too. */\nexport const GraphQLErrorCode: {\n /** The document does not parse (syntax error, `limits.maxTokens`). */\n readonly ParseFailed: 'GRAPHQL_PARSE_FAILED'\n /** The document is not valid against the schema. */\n readonly ValidationFailed: 'GRAPHQL_VALIDATION_FAILED'\n /** Invalid variables or arguments (Standard Schema issues in `extensions.issues`), HTTP 400. */\n readonly BadUserInput: 'BAD_USER_INPUT'\n /** The document exceeds `limits.maxDepth`, `maxAliases` or `maxDirectives`. */\n readonly QueryTooComplex: 'QUERY_TOO_COMPLEX'\n /** HTTP 401. */\n readonly Unauthenticated: 'UNAUTHENTICATED'\n /** A guard returned `false`, or HTTP 403. */\n readonly Forbidden: 'FORBIDDEN'\n /** HTTP 404, or a key missing from `orderByKeys`. */\n readonly NotFound: 'NOT_FOUND'\n /** HTTP 409. */\n readonly Conflict: 'CONFLICT'\n /** HTTP 429. */\n readonly TooManyRequests: 'TOO_MANY_REQUESTS'\n /** Any other HTTP 4xx. */\n readonly BadRequest: 'BAD_REQUEST'\n /** A subscriber fell behind its buffer: its stream ends with this error. */\n readonly SubscriptionOverflow: 'SUBSCRIPTION_OVERFLOW'\n /** Too many active subscriptions (`subscriptions.maxActive`), HTTP 503. */\n readonly ServiceUnavailable: 'SERVICE_UNAVAILABLE'\n /** An unexpected error, masked (`Unexpected error.`) unless `exposeErrors`. */\n readonly InternalServerError: 'INTERNAL_SERVER_ERROR'\n} = Object.freeze({\n ParseFailed: 'GRAPHQL_PARSE_FAILED',\n ValidationFailed: 'GRAPHQL_VALIDATION_FAILED',\n BadUserInput: 'BAD_USER_INPUT',\n QueryTooComplex: 'QUERY_TOO_COMPLEX',\n Unauthenticated: 'UNAUTHENTICATED',\n Forbidden: 'FORBIDDEN',\n NotFound: 'NOT_FOUND',\n Conflict: 'CONFLICT',\n TooManyRequests: 'TOO_MANY_REQUESTS',\n BadRequest: 'BAD_REQUEST',\n SubscriptionOverflow: 'SUBSCRIPTION_OVERFLOW',\n ServiceUnavailable: 'SERVICE_UNAVAILABLE',\n InternalServerError: 'INTERNAL_SERVER_ERROR',\n})\n\n/** One of the {@link GraphQLErrorCode} values. */\nexport type GraphQLErrorCodeValue = (typeof GraphQLErrorCode)[keyof typeof GraphQLErrorCode]\n\n/** Options of {@link GraphQLException}. */\nexport interface GraphQLExceptionOptions {\n /** `extensions.code` (`'NOT_FOUND'`, `'CONFLICT'`, or an application code). */\n readonly code: GraphQLErrorCodeValue | (string & Record<never, never>)\n /** Extra `extensions` entries, sent to the client (`code` always wins). */\n readonly extensions?: Readonly<Record<string, unknown>>\n /**\n * The original error: never sent, logged once at `error` level with the request id, the schema\n * coordinate and the path when the exception is shown for a field.\n */\n readonly cause?: unknown\n}\n\n/**\n * An error whose message and extensions are sent to the client as they are (§5.10): throw it from a\n * resolver or return it from a `GraphQLErrorMapper`.\n *\n * ```ts\n * throw new GraphQLException(`No book ${id}`, { code: 'NOT_FOUND', extensions: { bookId: id } })\n * ```\n */\nexport class GraphQLException extends Error {\n /** `extensions.code`. */\n readonly code: string\n /** Extra `extensions` entries. */\n readonly extensions: Readonly<Record<string, unknown>> | undefined\n\n constructor(message: string, options: GraphQLExceptionOptions) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause })\n this.name = 'GraphQLException'\n this.code = options.code\n this.extensions = options.extensions\n }\n}\n","/**\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 implementation of `GraphQLContext` (RFC 0005 §5.8): one per operation, passed to graphql-js\n * as `contextValue` and stored in the request scope (`@znight/graphql#GraphQLContext`).\n *\n * Everything that is not needed by every operation is computed on first read: the request id (a\n * UUID for direct executions), the HTTP context of an enclosing request, the signal, the state map\n * and the loader registry.\n */\nimport type { Container, ScopeContext, Token } from '@znight/core'\nimport type { HttpContext } from '@znight/http'\nimport type { DocumentNode, OperationDefinitionNode } from 'graphql'\nimport type { LoaderFactory } from './loaders.ts'\nimport type {\n BatchLoad,\n BatchLoadClass,\n BatchLoader,\n GraphQLContext,\n GraphQLOperationKind,\n GraphQLTransport,\n LoaderKey,\n LoaderValue,\n} from './types.ts'\n\nimport { randomUUID } from 'node:crypto'\nimport { ErrorCode, ZnightError } from '@znight/core'\nimport { HttpTokens } from '@znight/http'\n\n/** What every operation context of a plugin shares. */\nexport interface ContextRuntime {\n readonly container: Container\n readonly loaders: LoaderFactory\n /** The plugin's own signal (aborted by `onStop`): the signal of direct executions. */\n readonly signal: AbortSignal\n}\n\n/** What a request carries that the context exposes (a `GraphQLRequest`). */\nexport interface ContextRequest {\n readonly variables?: Readonly<Record<string, unknown>> | null | undefined\n}\n\n/** How the request reached the executor (`ExecuteOptions`). */\nexport interface ContextOptions {\n readonly transport?: GraphQLTransport\n readonly http?: HttpContext\n readonly signal?: AbortSignal\n readonly requestId?: string\n}\n\nconst NO_VARIABLES: Readonly<Record<string, unknown>> = Object.freeze({})\n\n/**\n * The `GraphQLContext` of one operation. Built from references the executor already holds (the\n * operation node, the request, the options, the enclosing scope): one allocation per operation,\n * every field read on demand.\n */\nexport class OperationContext implements GraphQLContext {\n readonly document: DocumentNode\n readonly #runtime: ContextRuntime\n readonly #operation: OperationDefinitionNode\n readonly #request: ContextRequest\n readonly #options: ContextOptions\n readonly #scope: ScopeContext | undefined\n #requestId: string | undefined\n #http: HttpContext | null | undefined\n #signal: AbortSignal | undefined\n #ended: AbortSignal | undefined\n #state: Map<string | symbol, unknown> | undefined\n #loaders: Map<Token, BatchLoader<unknown, unknown>> | undefined\n\n constructor(\n runtime: ContextRuntime,\n document: DocumentNode,\n operation: OperationDefinitionNode,\n request: ContextRequest,\n options: ContextOptions,\n scope: ScopeContext | undefined,\n ) {\n this.#runtime = runtime\n this.document = document\n this.#operation = operation\n this.#request = request\n this.#options = options\n this.#scope = scope\n this.#requestId = options.requestId\n }\n\n get transport(): GraphQLTransport {\n return this.#options.transport ?? 'direct'\n }\n\n get operationType(): GraphQLOperationKind {\n return this.#operation.operation\n }\n\n get operationName(): string | undefined {\n return this.#operation.name?.value\n }\n\n get requestId(): string {\n let id = this.#requestId\n if (id === undefined) {\n const http = this.http\n const scoped = http === undefined ? this.#scope?.get(HttpTokens.RequestId) : undefined\n id = http?.requestId ?? (typeof scoped === 'string' ? scoped : randomUUID())\n this.#requestId = id\n }\n return id\n }\n\n get http(): HttpContext | undefined {\n let http = this.#http\n if (http === undefined) {\n // a controller calling plugin.execute(): the HTTP request of the enclosing scope\n http = this.#options.http ?? this.#scope?.get(HttpTokens.Context) ?? null\n this.#http = http\n }\n return http ?? undefined\n }\n\n get variables(): Readonly<Record<string, unknown>> {\n return this.#request.variables ?? NO_VARIABLES\n }\n\n get signal(): AbortSignal {\n let signal = this.#signal\n if (signal === undefined) {\n // HttpContext.signal is created on first read: only read it when someone asks\n const base = this.#options.signal ?? this.http?.signal ?? this.#runtime.signal\n const ended = this.#ended\n signal = ended === undefined ? base : AbortSignal.any([base, ended])\n this.#signal = signal\n }\n return signal\n }\n\n /**\n * Ties {@link signal} to the end of a subscription: it also aborts when `ended` does (the stream\n * ended by itself or with `return()`). Called before any resolver runs.\n */\n endsWith(ended: AbortSignal): void {\n this.#ended = ended\n }\n\n get state(): Map<string | symbol, unknown> {\n this.#state ??= new Map()\n return this.#state\n }\n\n loader<L extends BatchLoad<unknown, unknown>>(loader: BatchLoadClass<L>): BatchLoader<LoaderKey<L>, LoaderValue<L>>\n loader(token: Token): BatchLoader<unknown, unknown>\n loader(key: Token | BatchLoadClass): BatchLoader<unknown, unknown> {\n const token = typeof key === 'string' ? key : this.#tokenOf(key)\n let loaders = this.#loaders\n if (loaders === undefined) {\n loaders = new Map()\n this.#loaders = loaders\n }\n let loader = loaders.get(token)\n if (loader === undefined) {\n loader = this.#runtime.loaders.create(token)\n loaders.set(token, loader)\n }\n return loader\n }\n\n /** Starts a new execution (a subscription event): loaders and their caches are renewed. */\n resetLoaders(): void {\n this.#loaders = undefined\n }\n\n #tokenOf(loader: BatchLoadClass): Token {\n const token = typeof loader === 'function' ? this.#runtime.container.tokenOf(loader) : undefined\n if (token === undefined) {\n const name = typeof loader === 'function' ? loader.name || '<anonymous>' : String(loader)\n throw new ZnightError(ErrorCode.MissingProvider, `GraphQLContext.loader(): ${name} is not a provider`, {\n hints: ['Add @Injectable() to the loader class (it implements BatchLoad<K, V>)'],\n })\n }\n return token\n }\n}\n","/**\n * Error formatting (RFC 0005 §5.10, §8.8): what clients see of the errors of a result.\n *\n * Execution errors, in order: a `GraphQLException` (or a `GraphQLError` thrown by user code) as is →\n * the error mappers, in order → an `HttpException` mapped by status (5xx masked) → anything else\n * masked as `Unexpected error.` with `INTERNAL_SERVER_ERROR`, logged once (unless `exposeErrors`).\n * The `cause` of a shown `GraphQLException` is logged once too, never sent.\n * Request errors (parse, validation, variables, limits) carry their code and are never logged\n * above `debug`.\n *\n * Kept apart from the import-free `errors.ts`, which the compiler side may reach.\n */\nimport type { Container, CoreLogger, Token } from '@znight/core'\nimport type {\n ASTNode,\n DocumentNode,\n FieldNode,\n FragmentDefinitionNode,\n GraphQLField,\n GraphQLFormattedError,\n GraphQLNamedType,\n GraphQLSchema,\n OperationDefinitionNode,\n SelectionSetNode,\n} from 'graphql'\nimport type { GraphQLContext, GraphQLErrorMapper } from './types.ts'\n\nimport { isHttpException, ValidationException } from '@znight/http'\nimport { GraphQLError, getNamedType, isObjectType, Kind } from 'graphql'\n\nimport { GraphQLErrorCode, GraphQLException } from './errors.ts'\n\n/** A provider resolved once (singleton, instance) or per use, in the current scope (token). */\nexport type Resolvable<T> = { readonly instance: T; readonly token?: undefined } | { readonly token: Token }\n\n/** Resolves a {@link Resolvable} (in the current scope for scoped providers). */\nexport function resolveIn<T>(container: Container, resolvable: Resolvable<T>): T {\n return resolvable.token === undefined ? resolvable.instance : (container.get(resolvable.token) as T)\n}\n\n/** Message of masked errors. */\nexport const MASKED_MESSAGE = 'Unexpected error.'\n\n/** `HttpException` status → `extensions.code` (other 4xx: `BAD_REQUEST`, 5xx: masked). */\nconst STATUS_CODES: ReadonlyMap<number, string> = new Map([\n [400, GraphQLErrorCode.BadUserInput],\n [401, GraphQLErrorCode.Unauthenticated],\n [403, GraphQLErrorCode.Forbidden],\n [404, GraphQLErrorCode.NotFound],\n [409, GraphQLErrorCode.Conflict],\n [429, GraphQLErrorCode.TooManyRequests],\n])\n\n/** Options of {@link ErrorFormatter}. */\nexport interface ErrorFormatterOptions {\n readonly container: Container\n readonly mappers: readonly Resolvable<GraphQLErrorMapper>[]\n readonly exposeErrors: boolean\n readonly logger: CoreLogger\n readonly schema: GraphQLSchema\n}\n\n/** Formats the errors of execution results. One per plugin, built at boot. */\nexport class ErrorFormatter {\n readonly #container: Container\n readonly #mappers: readonly Resolvable<GraphQLErrorMapper>[]\n readonly #expose: boolean\n readonly #logger: CoreLogger\n readonly #schema: GraphQLSchema\n\n constructor(options: ErrorFormatterOptions) {\n this.#container = options.container\n this.#mappers = options.mappers\n this.#expose = options.exposeErrors\n this.#logger = options.logger\n this.#schema = options.schema\n }\n\n /** Formats the errors of an executed operation (field errors). */\n format(errors: readonly GraphQLError[], ctx: GraphQLContext): GraphQLFormattedError[] {\n const result: GraphQLFormattedError[] = new Array(errors.length)\n // the same cause may fail several fields (a loader rejecting every key): logged once\n let logged: Set<unknown> | undefined\n for (let index = 0; index < errors.length; index++) {\n const error = errors[index] as GraphQLError\n const original = error.originalError\n if (original === undefined || original === null) {\n // produced by graphql-js during execution (non-null violation...): about the schema, shown as is\n result[index] = withCode(\n error,\n error.extensions['code'] === undefined ? GraphQLErrorCode.InternalServerError : undefined,\n )\n continue\n }\n const exposed = this.#exposed(original, ctx)\n if (exposed !== undefined) {\n result[index] = render(error, exposed)\n // the original failure behind a presented error (`{ cause }`): logged once, never sent\n const cause = exposed.cause\n if (cause !== undefined) {\n logged ??= new Set()\n if (!logged.has(cause)) {\n logged.add(cause)\n this.#log(error, cause, ctx, exposed.code)\n }\n }\n continue\n }\n if (original instanceof GraphQLError && !isCompletionError(original)) {\n result[index] = { ...original.toJSON(), ...located(error) }\n continue\n }\n logged ??= new Set()\n if (!logged.has(original)) {\n logged.add(original)\n this.#log(error, original, ctx, undefined)\n }\n result[index] = {\n message: this.#expose && original instanceof Error ? original.message : MASKED_MESSAGE,\n ...located(error),\n extensions: { code: GraphQLErrorCode.InternalServerError },\n }\n }\n return result\n }\n\n /** The exception shown for `original`, `undefined` when it must be masked. */\n #exposed(original: unknown, ctx: GraphQLContext): GraphQLException | undefined {\n if (original instanceof GraphQLException) return original\n for (const resolvable of this.#mappers) {\n let mapped: GraphQLException | undefined\n try {\n mapped = resolveIn(this.#container, resolvable).map(original, ctx)\n } catch (error) {\n this.#logger.error('GraphQLPlugin: an error mapper failed', { err: error, requestId: ctx.requestId })\n continue\n }\n if (mapped !== undefined) return mapped\n }\n if (isHttpException(original)) {\n const status = original.status\n if (original instanceof ValidationException) {\n return new GraphQLException(original.message, {\n code: GraphQLErrorCode.BadUserInput,\n extensions: { issues: original.details },\n })\n }\n if (status >= 500) return undefined\n return new GraphQLException(original.message, {\n code: STATUS_CODES.get(status) ?? GraphQLErrorCode.BadRequest,\n })\n }\n return undefined\n }\n\n /** Logs an unexpected error, or the cause of a presented one (`code`), at `error` level. */\n #log(error: GraphQLError, cause: unknown, ctx: GraphQLContext, code: string | undefined): void {\n const coordinate = coordinateOf(this.#schema, ctx.document, ctx.operationName, error.path)\n const what = code === undefined ? 'unexpected error' : `${code} error`\n this.#logger.error(`GraphQL: ${what}${coordinate === undefined ? '' : ` in ${coordinate}`}`, {\n err: cause,\n requestId: ctx.requestId,\n ...(code === undefined ? {} : { code }),\n ...(coordinate === undefined ? {} : { coordinate }),\n ...(error.path === undefined ? {} : { path: error.path.join('.') }),\n })\n }\n}\n\n/**\n * What graphql-js raises while completing a resolver's value: a built-in scalar or an enum that\n * cannot represent it (`String cannot represent value: { passwordHash: ... }`), a list value that\n * is not iterable, a union or interface value that resolves to no member. A server bug whose message\n * holds the value, masked and logged like any unexpected error. graphql-js throws plain\n * `GraphQLError`s without code there, told apart from the ones of user code by their message.\n */\nconst COMPLETION_ERROR =\n /^(?:(?:Int|Float|String|Boolean|ID) cannot represent |Enum \"[^\"]*\" cannot represent |Expected Iterable, but did not find one for field \"|Abstract type \"|Runtime Object type \")/\n\nfunction isCompletionError(error: GraphQLError): boolean {\n return (\n error.constructor === GraphQLError && error.extensions['code'] === undefined && COMPLETION_ERROR.test(error.message)\n )\n}\n\nfunction located(error: GraphQLError): Pick<GraphQLFormattedError, 'locations' | 'path'> {\n return {\n ...(error.locations === undefined ? {} : { locations: error.locations }),\n ...(error.path === undefined ? {} : { path: error.path }),\n }\n}\n\n/** `{ message, locations, path, extensions: { ...extensions, code } }`. */\nfunction render(error: GraphQLError, exception: GraphQLException): GraphQLFormattedError {\n return {\n message: exception.message,\n ...located(error),\n extensions: { ...exception.extensions, code: exception.code },\n }\n}\n\n/** A graphql-js error formatted with `extensions.code` set to `code` (kept as is without code). */\nexport function withCode(error: GraphQLError, code: string | undefined): GraphQLFormattedError {\n const formatted = error.toJSON()\n if (code === undefined) return formatted\n return { ...formatted, extensions: { ...formatted.extensions, code } }\n}\n\n/** A request error (no location): `{ message, extensions: { code } }`. */\nexport function requestError(\n message: string,\n code: string,\n nodes?: ASTNode | readonly ASTNode[],\n): GraphQLFormattedError {\n return withCode(new GraphQLError(message, nodes === undefined ? {} : { nodes }), code)\n}\n\n/**\n * The schema coordinate (`Book.author`) of the field at `path`, found by walking the operation's\n * selections (aliases, fragments, inline fragments). Best effort, for logs: `undefined` when the\n * path crosses a union without a type condition.\n */\nexport function coordinateOf(\n schema: GraphQLSchema,\n document: DocumentNode,\n operationName: string | undefined,\n path: readonly (string | number)[] | undefined,\n): string | undefined {\n if (path === undefined || path.length === 0) return undefined\n const fragments = new Map<string, FragmentDefinitionNode>()\n let operation: OperationDefinitionNode | undefined\n for (const definition of document.definitions) {\n if (definition.kind === Kind.FRAGMENT_DEFINITION) fragments.set(definition.name.value, definition)\n else if (\n definition.kind === Kind.OPERATION_DEFINITION &&\n (operationName === undefined || definition.name?.value === operationName)\n ) {\n operation ??= definition\n }\n }\n if (operation === undefined) return undefined\n let type: GraphQLNamedType | undefined | null = schema.getRootType(operation.operation)\n let selections: SelectionSetNode[] = [operation.selectionSet]\n let coordinate: string | undefined\n for (const segment of path) {\n if (typeof segment === 'number') continue\n const found = findField(selections, segment, fragments, type?.name)\n if (found === undefined || type === undefined || type === null) return undefined\n const parent: GraphQLNamedType | undefined | null =\n found.typeCondition === undefined ? type : schema.getType(found.typeCondition)\n if (!isObjectType(parent)) return undefined\n const field: GraphQLField<unknown, unknown> | undefined = parent.getFields()[found.field.name.value]\n coordinate = `${parent.name}.${found.field.name.value}`\n if (field === undefined) return coordinate\n type = getNamedType(field.type)\n selections = found.field.selectionSet === undefined ? [] : [found.field.selectionSet]\n }\n return coordinate\n}\n\nfunction findField(\n sets: readonly SelectionSetNode[],\n key: string,\n fragments: ReadonlyMap<string, FragmentDefinitionNode>,\n typeCondition: string | undefined,\n): { readonly field: FieldNode; readonly typeCondition: string | undefined } | undefined {\n for (const set of sets) {\n for (const selection of set.selections) {\n if (selection.kind === Kind.FIELD) {\n if ((selection.alias ?? selection.name).value === key) return { field: selection, typeCondition }\n } else {\n const nested = selection.kind === Kind.INLINE_FRAGMENT ? selection : fragments.get(selection.name.value)\n if (nested === undefined) continue\n const found = findField(\n [nested.selectionSet],\n key,\n fragments,\n nested.typeCondition?.name.value ?? typeCondition,\n )\n if (found !== undefined) return found\n }\n }\n }\n return undefined\n}\n","/**\n * Document limits (RFC 0005 §8.9): depth, aliases and directives, checked in one walk of the parsed\n * document **before** the specified validation rules, so that an abusive document is rejected\n * before rules whose cost grows with it (`OverlappingFieldsCanBeMerged`) run. Aliases are counted as\n * written, and, when the document spreads fragments, as each operation executes them (a fragment\n * spread several times counts each time). `maxTokens` is enforced by `parse()` itself.\n */\nimport type { DirectiveNode, DocumentNode, FragmentDefinitionNode, SelectionSetNode } from 'graphql'\n\nimport { GraphQLError, Kind } from 'graphql'\n\nimport { GraphQLErrorCode } from './errors.ts'\n\n/** Resolved limits: `undefined` disables one. */\nexport interface DocumentLimits {\n readonly maxDepth: number | undefined\n readonly maxAliases: number | undefined\n readonly maxDirectives: number | undefined\n}\n\n/** The limit errors of `document` (`QUERY_TOO_COMPLEX`), `undefined` when it is within its limits. */\nexport function checkLimits(document: DocumentNode, limits: DocumentLimits): GraphQLError[] | undefined {\n const { maxDepth, maxAliases, maxDirectives } = limits\n if (maxDepth === undefined && maxAliases === undefined && maxDirectives === undefined) return undefined\n const counter = { aliases: 0, directives: 0, spreads: 0 }\n const fragments = new Map<string, FragmentDefinitionNode>()\n for (const definition of document.definitions) {\n if (definition.kind === Kind.FRAGMENT_DEFINITION) fragments.set(definition.name.value, definition)\n }\n let errors: GraphQLError[] | undefined\n const fail = (message: string): void => {\n errors ??= []\n errors.push(new GraphQLError(message, { extensions: { code: GraphQLErrorCode.QueryTooComplex } }))\n }\n // counts every selection once, where it is written (fragment spreads expanded below for aliases)\n for (const definition of document.definitions) {\n if (definition.kind === Kind.OPERATION_DEFINITION || definition.kind === Kind.FRAGMENT_DEFINITION) {\n countDirectives(definition.directives, counter)\n if (definition.kind === Kind.OPERATION_DEFINITION) {\n for (const variable of definition.variableDefinitions ?? []) countDirectives(variable.directives, counter)\n }\n count(definition.selectionSet, counter)\n }\n }\n if (maxAliases !== undefined) {\n if (counter.aliases > maxAliases) {\n fail(`The document has ${counter.aliases} aliases, more than the limit of ${maxAliases}.`)\n } else if (counter.spreads > 0) {\n // a fragment spread several times executes its aliases each time: counted as executed\n const memo = new Map<string, number>()\n for (const definition of document.definitions) {\n if (definition.kind !== Kind.OPERATION_DEFINITION) continue\n const executed = aliasesOf(definition.selectionSet, fragments, memo, new Set(), maxAliases + 1)\n if (executed > maxAliases) {\n const name = definition.name === undefined ? 'The operation' : `The operation ${definition.name.value}`\n fail(`${name} has more than ${maxAliases} aliases once its fragments are expanded.`)\n break\n }\n }\n }\n }\n if (maxDirectives !== undefined && counter.directives > maxDirectives) {\n fail(`The document has ${counter.directives} directives, more than the limit of ${maxDirectives}.`)\n }\n if (maxDepth !== undefined) {\n const depths = new Map<string, number>()\n for (const definition of document.definitions) {\n if (definition.kind !== Kind.OPERATION_DEFINITION) continue\n const depth = depthOf(definition.selectionSet, fragments, depths, new Set())\n if (depth > maxDepth) {\n const name = definition.name === undefined ? 'The operation' : `The operation ${definition.name.value}`\n fail(`${name} is ${depth} levels deep, more than the limit of ${maxDepth}.`)\n }\n }\n }\n return errors\n}\n\ninterface Counter {\n aliases: number\n directives: number\n spreads: number\n}\n\nfunction countDirectives(directives: readonly DirectiveNode[] | undefined, counter: Counter): void {\n if (directives !== undefined) counter.directives += directives.length\n}\n\nfunction count(set: SelectionSetNode, counter: Counter): void {\n for (const selection of set.selections) {\n countDirectives(selection.directives, counter)\n if (selection.kind === Kind.FIELD) {\n if (selection.alias !== undefined) counter.aliases++\n if (selection.selectionSet !== undefined) count(selection.selectionSet, counter)\n } else if (selection.kind === Kind.INLINE_FRAGMENT) {\n count(selection.selectionSet, counter)\n } else {\n counter.spreads++\n }\n }\n}\n\n/**\n * Aliases a selection set executes, fragment spreads expanded (`a: f { ...F } b: f { ...F }` counts\n * the aliases of `F` twice). Fragment counts are memoised, so the walk stays linear in the document;\n * counts saturate at `cap` (one more than the limit) and a fragment cycle counts 0 (validation\n * rejects it).\n */\nfunction aliasesOf(\n set: SelectionSetNode,\n fragments: ReadonlyMap<string, FragmentDefinitionNode>,\n memo: Map<string, number>,\n visiting: Set<string>,\n cap: number,\n): number {\n let total = 0\n for (const selection of set.selections) {\n if (selection.kind === Kind.FIELD) {\n if (selection.alias !== undefined) total++\n if (selection.selectionSet !== undefined)\n total += aliasesOf(selection.selectionSet, fragments, memo, visiting, cap)\n } else if (selection.kind === Kind.INLINE_FRAGMENT) {\n total += aliasesOf(selection.selectionSet, fragments, memo, visiting, cap)\n } else {\n const name = selection.name.value\n let known = memo.get(name)\n if (known === undefined) {\n const fragment = fragments.get(name)\n if (fragment === undefined || visiting.has(name)) continue\n visiting.add(name)\n known = aliasesOf(fragment.selectionSet, fragments, memo, visiting, cap)\n visiting.delete(name)\n memo.set(name, known)\n }\n total += known\n }\n if (total >= cap) return cap\n }\n return total\n}\n\n/**\n * Field nesting of a selection set (`{ a { b } }` is 2). Introspection fields (`__schema`,\n * `__type`) do not count: `MaxIntrospectionDepthRule` bounds them. Fragment depths are memoised; a\n * fragment cycle counts 0 (validation rejects it).\n */\nfunction depthOf(\n set: SelectionSetNode,\n fragments: ReadonlyMap<string, FragmentDefinitionNode>,\n depths: Map<string, number>,\n visiting: Set<string>,\n): number {\n let max = 0\n for (const selection of set.selections) {\n let depth = 0\n if (selection.kind === Kind.FIELD) {\n if (selection.name.value.startsWith('__')) continue\n depth =\n selection.selectionSet === undefined ? 1 : 1 + depthOf(selection.selectionSet, fragments, depths, visiting)\n } else if (selection.kind === Kind.INLINE_FRAGMENT) {\n depth = depthOf(selection.selectionSet, fragments, depths, visiting)\n } else {\n const name = selection.name.value\n const known = depths.get(name)\n if (known === undefined) {\n const fragment = fragments.get(name)\n if (fragment === undefined || visiting.has(name)) continue\n visiting.add(name)\n depth = depthOf(fragment.selectionSet, fragments, depths, visiting)\n visiting.delete(name)\n depths.set(name, depth)\n } else depth = known\n }\n if (depth > max) max = depth\n }\n return max\n}\n","import type { TypedToken } from '@znight/core'\nimport type { GraphQLPlugin } from './plugin.ts'\nimport type { PubSub } from './pubsub.ts'\nimport type { GraphQLContext } from './types.ts'\n\n/**\n * Tokens of the values `GraphQLPlugin` supplies to the container (declared in the package\n * manifest). `GraphQLContext` is a request-scoped external: inject it in request-scoped providers\n * or through `Lazy<GraphQLContext>`.\n */\nexport const GraphQLTokens: {\n /** The {@link GraphQLContext} of the current operation (request scope). */\n readonly Context: TypedToken<GraphQLContext>\n /** The application {@link PubSub} (singleton). */\n readonly PubSub: TypedToken<PubSub>\n /** The {@link GraphQLPlugin} instance (singleton). */\n readonly Plugin: TypedToken<GraphQLPlugin>\n} = Object.freeze({\n Context: '@znight/graphql#GraphQLContext',\n PubSub: '@znight/graphql#PubSub',\n Plugin: '@znight/graphql#GraphQLPlugin',\n})\n","/**\n * Execution (RFC 0005 §8.4, §8.7–§8.10): the document cache, request checks, operation selection,\n * graphql-js `execute` and subscriptions, error formatting and the `graphql:operation` hook.\n *\n * `GraphQLExecutor` is the internal API of the transports (`plugin.execute()`, GraphQL over HTTP\n * and SSE): `execute()` answers a request with a status and a formatted result, `subscribe()` with\n * a stream of formatted results (or a rejection).\n *\n * Per operation, on the hot path (a cached query over a scope that already exists): one cache\n * lookup, one context object, graphql-js `execute`, and the result as graphql-js returned it when\n * it has no error. Synchronous when every resolver is; nothing is awaited that is not a promise.\n * The hook event is built only when the hook has wrappers or listeners.\n */\nimport type { Container, CoreLogger, GraphQLOperationEvent, Hooks, ScopeContext } from '@znight/core'\nimport type { HttpContext } from '@znight/http'\nimport type {\n DocumentNode,\n ExecutionResult,\n FormattedExecutionResult,\n GraphQLError,\n GraphQLFormattedError,\n GraphQLSchema,\n OperationDefinitionNode,\n ValidatedSubscriptionArgs,\n ValidationRule,\n} from 'graphql'\nimport type { ContextRuntime } from './context.ts'\nimport type { ErrorFormatter } from './format.ts'\nimport type { DocumentLimits } from './limits.ts'\nimport type { GraphQLOperationKind, GraphQLTransport } from './types.ts'\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { HttpTokens } from '@znight/http'\nimport {\n AbortedGraphQLExecutionError,\n createSourceEventStream,\n execute,\n executeSubscriptionEvent,\n GraphQLError as GraphQLErrorClass,\n Kind,\n NoSchemaIntrospectionCustomRule,\n parse,\n specifiedRules,\n validate,\n validateSubscriptionArgs,\n} from 'graphql'\n\nimport { OperationContext } from './context.ts'\nimport { GraphQLErrorCode } from './errors.ts'\nimport { requestError, withCode } from './format.ts'\nimport { checkLimits } from './limits.ts'\nimport { GraphQLTokens } from './tokens.ts'\n\n/** A GraphQL request: the body of a GraphQL-over-HTTP request, or the argument of `plugin.execute()`. */\nexport interface GraphQLRequest {\n readonly query: string\n readonly operationName?: string | null | undefined\n readonly variables?: Readonly<Record<string, unknown>> | null | undefined\n /** Request extensions (ignored by the executor; available to transports). */\n readonly extensions?: Readonly<Record<string, unknown>> | null | undefined\n}\n\n/** How a request reached the executor. */\nexport interface ExecuteOptions {\n /** Default `'direct'`. */\n readonly transport?: GraphQLTransport\n /** The HTTP request carrying the operation (GraphQL over HTTP and SSE). */\n readonly http?: HttpContext\n /**\n * Cancels the operation (passed to graphql-js `abortSignal`, and `GraphQLContext.signal`). Only\n * passed when given: graphql-js then adds an abort listener per execution. Over HTTP, the\n * transport passes `ctx.signal`.\n */\n readonly signal?: AbortSignal\n /**\n * Passed to graphql-js as `abortSignal` instead of {@link signal} (which stays the signal of\n * `GraphQLContext.signal`). The HTTP transport passes a stand-in that reads `ctx.signal` only when\n * an execution turns asynchronous (see `transport/abort.ts`).\n */\n readonly abortSignal?: AbortSignal\n /** Default: the HTTP request id, the request id of the enclosing scope, or a UUID (on first read). */\n readonly requestId?: string\n /** GET: queries only, other operations are rejected with 405 and `allow: POST`. */\n readonly queriesOnly?: boolean\n /**\n * {@link GraphQLExecutor.execute} answers a subscription with {@link SUBSCRIBE} (nothing observed\n * yet) instead of a 400: the HTTP transport then streams it (the client accepts an event stream).\n */\n readonly streamSubscriptions?: boolean\n}\n\n/**\n * The answer of {@link GraphQLExecutor.execute} to a subscription with\n * {@link ExecuteOptions.streamSubscriptions}: start it with {@link GraphQLExecutor.subscribe}.\n */\nexport const SUBSCRIBE: GraphQLResponse = Object.freeze({ status: 0, result: Object.freeze({}) })\n\n/** The answer to a request: an HTTP-like status and the formatted result. */\nexport interface GraphQLResponse {\n /**\n * 200: executed (the result may hold field errors); 400: request error (parse, validation,\n * variables, limits, operation selection, subscription without stream); 405: not a query with\n * `queriesOnly`; 503: too many active subscriptions.\n */\n readonly status: number\n readonly result: FormattedExecutionResult\n /** Headers of the HTTP response (`allow` with a 405). */\n readonly headers?: Readonly<Record<string, string>>\n}\n\n/** The results of a subscription (one per event), or the single result of a query sent as a stream. */\nexport interface GraphQLResultStream extends AsyncIterableIterator<FormattedExecutionResult> {\n /** Ends the stream: the source event stream is returned (unsubscribed). */\n return(): Promise<IteratorResult<FormattedExecutionResult>>\n}\n\n/** What {@link GraphQLExecutor} is built from (resolved plugin options). */\nexport interface ExecutorOptions {\n readonly schema: GraphQLSchema\n readonly container: Container\n readonly hooks: Hooks\n readonly logger: CoreLogger\n readonly formatter: ErrorFormatter\n readonly runtime: ContextRuntime\n readonly limits: DocumentLimits & { readonly maxTokens: number | undefined }\n readonly introspection: boolean\n /** Entries of the document cache, 0 disables it. */\n readonly documentCache: number\n /** Active subscriptions cap, `undefined`: none. */\n readonly maxActiveSubscriptions: number | undefined\n}\n\nconst OPERATION_HOOK = 'graphql:operation'\nconst DIRECT: ExecuteOptions = Object.freeze({})\nconst DONE: IteratorResult<FormattedExecutionResult> = Object.freeze({ done: true, value: undefined })\n\n/** SHA-256 (hex) of a query text: `GraphQLOperationEvent.documentId`. */\nfunction documentId(query: string): string {\n return createHash('sha256').update(query, 'utf8').digest('hex')\n}\n\n/** A parsed and validated document, kept by the document cache. */\nclass CachedDocument {\n readonly query: string\n readonly document: DocumentNode\n /** The operation of a single-operation document. */\n readonly single: OperationDefinitionNode | undefined\n /** Operations by name (documents with several operations). */\n readonly named: ReadonlyMap<string, OperationDefinitionNode> | undefined\n #id: string | undefined\n\n constructor(query: string, document: DocumentNode) {\n this.query = query\n this.document = document\n let single: OperationDefinitionNode | undefined\n let named: Map<string, OperationDefinitionNode> | undefined\n let count = 0\n for (const definition of document.definitions) {\n if (definition.kind !== Kind.OPERATION_DEFINITION) continue\n count++\n single = definition\n if (definition.name !== undefined) {\n named ??= new Map()\n named.set(definition.name.value, definition)\n }\n }\n this.single = count === 1 ? single : undefined\n this.named = named\n }\n\n /** SHA-256 of the query, computed on first read (only the hook needs it). */\n get id(): string {\n this.#id ??= documentId(this.query)\n return this.#id\n }\n}\n\n/** A bounded LRU of documents by exact query text. */\nclass DocumentCache {\n readonly #max: number\n readonly #entries = new Map<string, CachedDocument>()\n #last: string | undefined\n\n constructor(max: number) {\n this.#max = max\n }\n\n get size(): number {\n return this.#entries.size\n }\n\n get(query: string): CachedDocument | undefined {\n const entry = this.#entries.get(query)\n // refresh the recency (a re-insertion), except for the most recent entry: the hot loop of one query\n if (entry !== undefined && this.#last !== query) {\n this.#entries.delete(query)\n this.#entries.set(query, entry)\n this.#last = query\n }\n return entry\n }\n\n set(query: string, entry: CachedDocument): void {\n if (this.#max === 0) return\n if (this.#entries.size >= this.#max) {\n const oldest = this.#entries.keys().next()\n if (oldest.done !== true) this.#entries.delete(oldest.value)\n }\n this.#entries.set(query, entry)\n this.#last = query\n }\n\n clear(): void {\n this.#entries.clear()\n this.#last = undefined\n }\n}\n\n/** A request refused before execution. */\nclass Rejection {\n readonly status: number\n readonly errors: GraphQLFormattedError[]\n readonly operationType: GraphQLOperationKind | undefined\n readonly operationName: string | undefined\n readonly documentId: string | undefined\n readonly headers: Readonly<Record<string, string>> | undefined\n\n constructor(\n status: number,\n errors: GraphQLFormattedError[],\n documentId: string | undefined,\n operation?: OperationDefinitionNode,\n headers?: Readonly<Record<string, string>>,\n ) {\n this.status = status\n this.errors = errors\n this.documentId = documentId\n this.operationType = operation?.operation\n this.operationName = operation?.name?.value\n this.headers = headers\n }\n\n response(): GraphQLResponse {\n return {\n status: this.status,\n result: { errors: this.errors },\n ...(this.headers === undefined ? {} : { headers: this.headers }),\n }\n }\n}\n\n/** A request ready to execute. */\ninterface Prepared {\n readonly entry: CachedDocument\n readonly operation: OperationDefinitionNode\n}\n\n/** The GraphQL executor of a plugin. */\nexport class GraphQLExecutor {\n readonly #schema: GraphQLSchema\n readonly #container: Container\n readonly #hooks: Hooks\n readonly #logger: CoreLogger\n readonly #formatter: ErrorFormatter\n readonly #runtime: ContextRuntime\n readonly #rules: readonly ValidationRule[]\n readonly #limits: DocumentLimits\n readonly #maxTokens: number | undefined\n readonly #hideSuggestions: boolean\n readonly #cache: DocumentCache\n readonly #maxActive: number | undefined\n readonly #streams = new Set<SubscriptionStream>()\n readonly #direct = new Set<SubscriptionStream>()\n /** Subscriptions counted against `maxActive` while their source starts (not yet in `#streams`). */\n #starting = 0\n\n constructor(options: ExecutorOptions) {\n this.#schema = options.schema\n this.#container = options.container\n this.#hooks = options.hooks\n this.#logger = options.logger\n this.#formatter = options.formatter\n this.#runtime = options.runtime\n this.#rules = options.introspection ? specifiedRules : [...specifiedRules, NoSchemaIntrospectionCustomRule]\n this.#limits = options.limits\n this.#maxTokens = options.limits.maxTokens\n // without introspection, suggestions would leak field and type names\n this.#hideSuggestions = !options.introspection\n this.#cache = new DocumentCache(options.documentCache)\n this.#maxActive = options.maxActiveSubscriptions\n }\n\n /** Active subscriptions (every transport). */\n get activeSubscriptions(): number {\n return this.#streams.size\n }\n\n /** Documents in the cache. */\n get cachedDocuments(): number {\n return this.#cache.size\n }\n\n /**\n * Executes a query or a mutation. Resolves (or returns, when every resolver is synchronous) a\n * response; rejects only when `options.signal` aborts the execution (with the signal's reason).\n * A subscription is a 400: it needs {@link subscribe} ({@link SUBSCRIBE} with\n * `streamSubscriptions`).\n */\n execute(request: GraphQLRequest, options: ExecuteOptions = DIRECT): GraphQLResponse | Promise<GraphQLResponse> {\n const prepared = this.#prepare(request, options)\n if (prepared instanceof Rejection) return this.#reject(prepared, request, options)\n if (prepared.operation.operation === 'subscription') {\n if (options.streamSubscriptions === true) return SUBSCRIBE\n return this.#reject(\n new Rejection(\n 400,\n [\n requestError(\n 'Subscriptions are delivered as a stream: send the request with accept: text/event-stream (GraphQL over SSE), or call GraphQLPlugin.subscribe()',\n GraphQLErrorCode.BadRequest,\n ),\n ],\n prepared.entry.id,\n prepared.operation,\n ),\n request,\n options,\n )\n }\n const scope = this.#container.currentScope()\n const ctx = this.#context(prepared, request, options, scope)\n const hooks = this.#hooks\n if (!hooks.hasWrappers(OPERATION_HOOK) && !hooks.hasListeners(OPERATION_HOOK)) {\n return this.#inScope(scope, ctx, () => this.#run(prepared, request, options, ctx))\n }\n return this.#inScope(scope, ctx, () =>\n this.#observed(ctx, prepared.entry.id, () => this.#run(prepared, request, options, ctx)),\n )\n }\n\n /**\n * Subscribes: a stream of results, one per source event, or a rejection (status 400, 405 or 503).\n * A query or a mutation gives a stream of its single result. The stream ends when the source\n * ends, when `options.signal` aborts, or with `return()`; a source failure ends it with a final\n * error result (`SUBSCRIPTION_OVERFLOW` for a subscriber that fell behind `MemoryPubSub`).\n */\n async subscribe(\n request: GraphQLRequest,\n options: ExecuteOptions = DIRECT,\n ): Promise<GraphQLResponse | GraphQLResultStream> {\n const prepared = this.#prepare(request, options)\n if (prepared instanceof Rejection) return this.#reject(prepared, request, options)\n if (prepared.operation.operation !== 'subscription') {\n const response = await this.execute(request, options)\n return response.status === 200 ? new SingleResultStream(response.result) : response\n }\n const limited = this.#maxActive !== undefined\n if (limited && this.#streams.size + this.#starting >= (this.#maxActive as number)) {\n return this.#reject(\n new Rejection(\n 503,\n [requestError('Too many active subscriptions, retry later', GraphQLErrorCode.ServiceUnavailable)],\n prepared.entry.id,\n prepared.operation,\n ),\n request,\n options,\n )\n }\n // the slot is reserved before the source starts (guards and subscribe methods may be async):\n // concurrent subscriptions see it; released once the stream is counted or did not start\n let reserved = limited\n if (reserved) this.#starting++\n const release = (): void => {\n if (reserved) {\n reserved = false\n this.#starting--\n }\n }\n const outer = this.#container.currentScope()\n const ctx = this.#context(prepared, request, options, outer)\n // ctx.signal also aborts when the stream ends (return() included, on every transport): the\n // source, started before the first read (SubscriptionStream), then lets go of its PubSub topic\n const ended = new AbortController()\n ctx.endsWith(ended.signal)\n let run: <R>(fn: () => R) => R\n let close: () => void\n if (outer === undefined) {\n // a direct subscription: its own scope, open as long as the stream\n const opened = this.#container.openScope([[GraphQLTokens.Context, ctx]])\n run = fn => opened.run(fn)\n close = () => {\n ended.abort()\n opened.close()?.catch(error => this.#runtimeLogError('Failed to close the scope of a subscription', error))\n }\n } else {\n outer.set(GraphQLTokens.Context, ctx)\n run = fn => fn()\n close = () => ended.abort()\n }\n const observer = this.#observer(ctx, prepared.entry.id)\n try {\n const stream = await run(() =>\n this.#startSubscription(prepared, request, options, ctx, observer, run, close, release),\n )\n release()\n if (stream instanceof Rejection) {\n close()\n observer?.end('rejected', stream.errors)\n return stream.response()\n }\n return stream\n } catch (error) {\n release()\n close()\n observer?.end('error', undefined)\n throw error\n }\n }\n\n /** Ends every subscription started with `transport: 'direct'` (plugin `onStop`). */\n async stopDirect(): Promise<void> {\n await Promise.all([...this.#direct].map(stream => stream.return()))\n }\n\n /** Forgets every cached document. */\n clear(): void {\n this.#cache.clear()\n }\n\n // ------------------------------------------------------------------------------------------------\n // preparation\n\n /** Request checks, the document (cached, or parsed, limited and validated), the operation. */\n #prepare(request: GraphQLRequest, options: ExecuteOptions): Prepared | Rejection {\n const query: unknown = request?.query\n if (typeof query !== 'string' || query === '') {\n return badRequest(typeof query === 'string' ? 'The query is empty' : 'Missing query (a string)')\n }\n const operationName: unknown = request.operationName\n if (operationName !== undefined && operationName !== null && typeof operationName !== 'string') {\n return badRequest('operationName must be a string')\n }\n const variables: unknown = request.variables\n if (variables !== undefined && variables !== null && (typeof variables !== 'object' || Array.isArray(variables))) {\n return badRequest('variables must be an object')\n }\n const entry = this.#cache.get(query) ?? this.#load(query)\n if (entry instanceof Rejection) return entry\n let operation: OperationDefinitionNode | undefined\n if (operationName === undefined || operationName === null) {\n operation = entry.single\n if (operation === undefined) {\n return new Rejection(\n 400,\n [\n requestError(\n 'Must provide operation name if query contains multiple operations.',\n GraphQLErrorCode.BadRequest,\n ),\n ],\n entry.id,\n )\n }\n } else {\n operation = entry.named?.get(operationName)\n if (operation === undefined) {\n return new Rejection(\n 400,\n [requestError(`Unknown operation named \"${operationName}\".`, GraphQLErrorCode.BadRequest)],\n entry.id,\n )\n }\n }\n if (options.queriesOnly === true && operation.operation !== 'query') {\n return new Rejection(\n 405,\n [requestError(`A ${operation.operation} cannot be sent with GET: use POST`, GraphQLErrorCode.BadRequest)],\n entry.id,\n operation,\n { allow: 'POST' },\n )\n }\n return { entry, operation }\n }\n\n /** Parses, limits and validates a document; caches it when valid (rejected documents are not cached). */\n #load(query: string): CachedDocument | Rejection {\n let document: DocumentNode\n try {\n document = parse(query, this.#maxTokens === undefined ? undefined : { maxTokens: this.#maxTokens })\n } catch (error) {\n if (!(error instanceof GraphQLErrorClass)) throw error\n return new Rejection(400, [withCode(error, GraphQLErrorCode.ParseFailed)], documentId(query))\n }\n const limited = checkLimits(document, this.#limits)\n if (limited !== undefined) {\n return new Rejection(\n 400,\n limited.map(error => withCode(error, undefined)),\n documentId(query),\n )\n }\n const errors = validate(this.#schema, document, this.#rules, { hideSuggestions: this.#hideSuggestions })\n if (errors.length > 0) {\n return new Rejection(\n 400,\n errors.map(error => withCode(error, GraphQLErrorCode.ValidationFailed)),\n documentId(query),\n )\n }\n const entry = new CachedDocument(query, document)\n this.#cache.set(query, entry)\n return entry\n }\n\n #context(\n prepared: Prepared,\n request: GraphQLRequest,\n options: ExecuteOptions,\n scope: ScopeContext | undefined,\n ): OperationContext {\n return new OperationContext(this.#runtime, prepared.entry.document, prepared.operation, request, options, scope)\n }\n\n // ------------------------------------------------------------------------------------------------\n // execution\n\n /** Runs `fn` in the current scope (the GraphQL context set in it) or in a new one, closed after. */\n #inScope<R>(scope: ScopeContext | undefined, ctx: OperationContext, fn: () => R | Promise<R>): R | Promise<R> {\n if (scope !== undefined) {\n scope.set(GraphQLTokens.Context, ctx)\n return fn()\n }\n const opened = this.#container.openScope([[GraphQLTokens.Context, ctx]])\n let result: R | Promise<R>\n try {\n result = opened.run(fn)\n } catch (error) {\n const closing = opened.close()\n if (closing === undefined) throw error\n return closing.then(\n () => Promise.reject(error),\n () => Promise.reject(error),\n )\n }\n if (isPromise(result)) {\n return result.then(\n value => {\n const closing = opened.close()\n return closing === undefined ? value : closing.then(() => value)\n },\n (error: unknown) => {\n const closing = opened.close()\n if (closing === undefined) throw error\n return closing.then(\n () => Promise.reject(error),\n () => Promise.reject(error),\n )\n },\n )\n }\n // request-scoped providers created by a synchronous execution: disposed before answering\n const closing = opened.close()\n return closing === undefined ? result : closing.then(() => result)\n }\n\n #run(\n prepared: Prepared,\n request: GraphQLRequest,\n options: ExecuteOptions,\n ctx: OperationContext,\n ): GraphQLResponse | Promise<GraphQLResponse> {\n let result: ExecutionResult | Promise<ExecutionResult>\n try {\n result = execute({\n schema: this.#schema,\n document: prepared.entry.document,\n operationName: request.operationName,\n variableValues: request.variables,\n contextValue: ctx,\n // undefined: no abort listener in graphql-js (one per execution otherwise)\n abortSignal: options.abortSignal ?? options.signal,\n hideSuggestions: this.#hideSuggestions,\n })\n } catch (error) {\n return Promise.reject(abortReason(error, options))\n }\n if (isPromise(result)) {\n return result.then(\n settled => this.#respond(settled, ctx),\n (error: unknown) => Promise.reject(abortReason(error, options)),\n )\n }\n return this.#respond(result, ctx)\n }\n\n /** The response of an execution result: as is without errors, formatted errors otherwise. */\n #respond(result: ExecutionResult, ctx: OperationContext): GraphQLResponse {\n const errors = result.errors\n if (errors === undefined) return { status: 200, result: result as FormattedExecutionResult }\n if (!('data' in result)) {\n // no data: graphql-js refused the variables before executing\n return { status: 400, result: { errors: errors.map(variableError) } }\n }\n return {\n status: 200,\n result: {\n data: result.data,\n errors: this.#formatter.format(errors, ctx),\n ...(result.extensions === undefined ? {} : { extensions: result.extensions }),\n },\n }\n }\n\n /** Formats a subscription result: an event, a source that could not start or failed (field errors). */\n formatEvent(result: ExecutionResult, ctx: OperationContext): FormattedExecutionResult {\n const errors = result.errors\n if (errors === undefined) return result as FormattedExecutionResult\n return {\n ...('data' in result ? { data: result.data } : {}),\n errors: this.#formatter.format(errors, ctx),\n }\n }\n\n #startSubscription(\n prepared: Prepared,\n request: GraphQLRequest,\n options: ExecuteOptions,\n ctx: OperationContext,\n observer: Observer | undefined,\n run: <R>(fn: () => R) => R,\n close: () => void,\n release: () => void,\n ): Promise<GraphQLResultStream | Rejection> | GraphQLResultStream | Rejection {\n const validated = validateSubscriptionArgs({\n schema: this.#schema,\n document: prepared.entry.document,\n operationName: request.operationName,\n variableValues: request.variables,\n contextValue: ctx,\n abortSignal: options.signal,\n hideSuggestions: this.#hideSuggestions,\n })\n if (!('schema' in validated)) {\n return new Rejection(400, validated.map(variableError), prepared.entry.id, prepared.operation)\n }\n const start = (source: AsyncIterable<unknown> | ExecutionResult): GraphQLResultStream => {\n // the reservation becomes the stream (counted in #streams), or ends with the failed start\n release()\n if (!isAsyncIterable(source)) {\n // the subscription could not start (guard, resolver error): one error result\n const result = this.formatEvent(source, ctx)\n close()\n observer?.end('error', result.errors)\n return new SingleResultStream(result)\n }\n const stream = new SubscriptionStream({\n executor: this,\n source: source[Symbol.asyncIterator](),\n validated,\n ctx,\n run,\n signal: options.signal,\n field: responseKey(prepared.operation),\n onEnd: (outcome, errors) => {\n this.#streams.delete(stream)\n this.#direct.delete(stream)\n close()\n observer?.end(outcome, errors)\n },\n })\n this.#streams.add(stream)\n if (ctx.transport === 'direct') this.#direct.add(stream)\n return stream\n }\n const source = createSourceEventStream(validated)\n return isPromise(source) ? source.then(start) : start(source)\n }\n\n // ------------------------------------------------------------------------------------------------\n // hook\n\n /** A rejection as a response, observed by the hook (outcome `rejected`). */\n #reject(\n rejection: Rejection,\n request: GraphQLRequest,\n options: ExecuteOptions,\n ): GraphQLResponse | Promise<GraphQLResponse> {\n const hooks = this.#hooks\n const wrapped = hooks.hasWrappers(OPERATION_HOOK)\n if (!wrapped && !hooks.hasListeners(OPERATION_HOOK)) return rejection.response()\n const event: GraphQLOperationEvent = {\n operationType: rejection.operationType,\n operationName:\n rejection.operationName ?? (typeof request?.operationName === 'string' ? request.operationName : undefined),\n documentId: rejection.documentId,\n transport: options.transport ?? 'direct',\n requestId: options.requestId ?? options.http?.requestId ?? this.#scopedRequestId(),\n context: undefined,\n startTime: performance.now(),\n outcome: 'rejected',\n errors: summaries(rejection.errors),\n }\n if (!wrapped) {\n hooks.emit(OPERATION_HOOK, event)\n return rejection.response()\n }\n return hooks\n .run(OPERATION_HOOK, event, () => Promise.resolve(rejection.response()))\n .then(response => {\n if (hooks.hasListeners(OPERATION_HOOK)) hooks.emit(OPERATION_HOOK, event)\n return response\n })\n }\n\n /** An executed query or mutation, observed by the hook. */\n #observed(\n ctx: OperationContext,\n id: string,\n run: () => GraphQLResponse | Promise<GraphQLResponse>,\n ): GraphQLResponse | Promise<GraphQLResponse> {\n const hooks = this.#hooks\n const event = operationEvent(ctx, id)\n const done = (response: GraphQLResponse): GraphQLResponse => {\n event.outcome = outcomeOf(response)\n if (response.result.errors !== undefined) event.errors = summaries(response.result.errors)\n return response\n }\n const failed = (error: unknown): never => {\n event.outcome = 'error'\n throw error\n }\n const emit = (): void => {\n if (hooks.hasListeners(OPERATION_HOOK)) hooks.emit(OPERATION_HOOK, event)\n }\n if (hooks.hasWrappers(OPERATION_HOOK)) {\n const promise = hooks.run(OPERATION_HOOK, event, () => Promise.resolve(run()).then(done, failed))\n return promise.then(\n response => {\n emit()\n return response\n },\n (error: unknown) => {\n emit()\n throw error\n },\n )\n }\n // listeners only: no promise added to a synchronous execution\n let response: GraphQLResponse | Promise<GraphQLResponse>\n try {\n response = run()\n } catch (error) {\n event.outcome = 'error'\n emit()\n throw error\n }\n if (!isPromise(response)) {\n done(response)\n emit()\n return response\n }\n return response.then(\n settled => {\n done(settled)\n emit()\n return settled\n },\n (error: unknown) => {\n event.outcome = 'error'\n emit()\n throw error\n },\n )\n }\n\n /** The hook of a subscription, for its whole life (`end()` settles it), or `undefined` without wrappers nor listeners. */\n #observer(ctx: OperationContext, id: string): Observer | undefined {\n const hooks = this.#hooks\n const wrapped = hooks.hasWrappers(OPERATION_HOOK)\n if (!wrapped && !hooks.hasListeners(OPERATION_HOOK)) return undefined\n const event = operationEvent(ctx, id)\n let resolve: (() => void) | undefined\n if (wrapped) {\n const ended = new Promise<void>(settle => {\n resolve = settle\n })\n hooks\n .run(OPERATION_HOOK, event, () => ended)\n .catch(error => this.#runtimeLogError('A \"graphql:operation\" hook wrapper failed', error))\n }\n let ended = false\n return {\n end: (outcome, errors) => {\n if (ended) return\n ended = true\n event.outcome = outcome\n if (errors !== undefined && errors.length > 0) event.errors = summaries(errors)\n resolve?.()\n if (hooks.hasListeners(OPERATION_HOOK)) hooks.emit(OPERATION_HOOK, event)\n },\n }\n }\n\n /** The request id of the enclosing scope (a controller calling GraphQL), or a new one. */\n #scopedRequestId(): string {\n const id = this.#container.currentScope()?.get(HttpTokens.RequestId)\n return typeof id === 'string' ? id : randomUUID()\n }\n\n #runtimeLogError(message: string, error: unknown): void {\n this.#logger.error(`GraphQLPlugin: ${message}`, { err: error })\n }\n}\n\n/** Settles the hook event of a subscription. */\ninterface Observer {\n end(\n outcome: NonNullable<GraphQLOperationEvent['outcome']>,\n errors: readonly GraphQLFormattedError[] | undefined,\n ): void\n}\n\nfunction noop(): void {}\n\nfunction badRequest(message: string): Rejection {\n return new Rejection(400, [requestError(message, GraphQLErrorCode.BadRequest)], undefined)\n}\n\nfunction variableError(error: GraphQLError): GraphQLFormattedError {\n return withCode(error, error.extensions['code'] === undefined ? GraphQLErrorCode.BadUserInput : undefined)\n}\n\n/** graphql-js rejects with `AbortedGraphQLExecutionError`: callers get the reason of their signal. */\nfunction abortReason(error: unknown, options: ExecuteOptions): unknown {\n const signal = options.abortSignal ?? options.signal\n if (error instanceof AbortedGraphQLExecutionError && signal?.aborted === true) return signal.reason\n return error\n}\n\nfunction operationEvent(ctx: OperationContext, id: string): GraphQLOperationEvent {\n return {\n operationType: ctx.operationType,\n operationName: ctx.operationName,\n documentId: id,\n transport: ctx.transport,\n requestId: ctx.requestId,\n context: ctx,\n startTime: performance.now(),\n }\n}\n\nfunction outcomeOf(response: GraphQLResponse): NonNullable<GraphQLOperationEvent['outcome']> {\n if (response.status !== 200) return 'rejected'\n const result = response.result\n if (result.errors === undefined || result.errors.length === 0) return 'success'\n return result.data === null || result.data === undefined ? 'error' : 'partial'\n}\n\nfunction summaries(errors: readonly GraphQLFormattedError[]): NonNullable<GraphQLOperationEvent['errors']> {\n return errors.map(error => {\n const code = error.extensions?.['code']\n return {\n message: error.message,\n code: typeof code === 'string' ? code : undefined,\n ...(error.path === undefined ? {} : { path: error.path }),\n }\n })\n}\n\n/** The response key of the root field of a subscription (its single selection). */\nfunction responseKey(operation: OperationDefinitionNode): string | undefined {\n const selection = operation.selectionSet.selections[0]\n return selection?.kind === Kind.FIELD ? (selection.alias ?? selection.name).value : undefined\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\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'\n )\n}\n\n/** A stream of one result (a query sent as a stream, a rejection for `plugin.subscribe()`). */\nexport function singleResult(result: FormattedExecutionResult): GraphQLResultStream {\n return new SingleResultStream(result)\n}\n\n/** The stream of a query or a mutation sent as a stream (SSE): its single result. */\nclass SingleResultStream implements GraphQLResultStream {\n #result: FormattedExecutionResult | undefined\n\n constructor(result: FormattedExecutionResult) {\n this.#result = result\n }\n\n next(): Promise<IteratorResult<FormattedExecutionResult>> {\n const result = this.#result\n if (result === undefined) return Promise.resolve(DONE)\n this.#result = undefined\n return Promise.resolve({ done: false, value: result })\n }\n\n return(): Promise<IteratorResult<FormattedExecutionResult>> {\n this.#result = undefined\n return Promise.resolve(DONE)\n }\n\n [Symbol.asyncIterator](): GraphQLResultStream {\n return this\n }\n}\n\ninterface SubscriptionStreamInit {\n readonly executor: GraphQLExecutor\n readonly source: AsyncIterator<unknown>\n readonly validated: ValidatedSubscriptionArgs\n readonly ctx: OperationContext\n readonly run: <R>(fn: () => R) => R\n readonly signal: AbortSignal | undefined\n readonly field: string | undefined\n readonly onEnd: (\n outcome: NonNullable<GraphQLOperationEvent['outcome']>,\n errors: readonly GraphQLFormattedError[] | undefined,\n ) => void\n}\n\n/**\n * The results of a subscription: each source event executed with `executeSubscriptionEvent`, a\n * fresh per-execution state (loaders) and the operation's `GraphQLContext`.\n *\n * The source is started at once: its first `next()` is requested when the stream is created, so\n * that a resolver written as an async generator (`for await (const x of pubsub.subscribe(...))`)\n * has subscribed when `subscribe()` resolves, whatever the transport and however late its consumer\n * reads (an SSE body pulled on demand). Only that first event is read ahead; the next ones are read\n * when the consumer asks (backpressure).\n */\nclass SubscriptionStream implements GraphQLResultStream {\n readonly #init: SubscriptionStreamInit\n readonly #onAbort: (() => void) | undefined\n /** The first `next()` of the source, requested at creation and consumed by the first read. */\n #first: Promise<IteratorResult<unknown>> | undefined\n /** `next()` calls of the source still pending. */\n #reading = 0\n #ended = false\n #partial = false\n\n constructor(init: SubscriptionStreamInit) {\n this.#init = init\n const signal = init.signal\n if (signal !== undefined) {\n this.#onAbort = () => {\n void this.return()\n }\n signal.addEventListener('abort', this.#onAbort, { once: true })\n }\n const first = init.run(() => this.#read())\n // handled by the first read; ignored when the stream ends before it\n first.catch(noop)\n this.#first = first\n // the client may have left while the operation was starting (async guards): end at once\n if (signal?.aborted === true) void this.return()\n }\n\n next(): Promise<IteratorResult<FormattedExecutionResult>> {\n if (this.#ended) return Promise.resolve(DONE)\n return this.#init.run(() => this.#pull())\n }\n\n /** The next event of the source. */\n async #read(): Promise<IteratorResult<unknown>> {\n this.#reading++\n try {\n return await this.#init.source.next()\n } finally {\n this.#reading--\n }\n }\n\n async #pull(): Promise<IteratorResult<FormattedExecutionResult>> {\n const init = this.#init\n let step: IteratorResult<unknown>\n try {\n const first = this.#first\n this.#first = undefined\n step = await (first ?? this.#read())\n } catch (error) {\n if (this.#ended) return DONE\n // the source failed (MemoryPubSub overflow...): a final error result, then the end\n const result = init.executor.formatEvent(\n {\n errors: [\n new GraphQLErrorClass(errorMessage(error), {\n originalError: asError(error),\n path: init.field === undefined ? undefined : [init.field],\n }),\n ],\n },\n init.ctx,\n )\n this.#end('error', result.errors)\n return { done: false, value: result }\n }\n if (step.done === true || this.#ended) {\n this.#end(this.#partial ? 'partial' : 'success', undefined)\n return DONE\n }\n init.ctx.resetLoaders()\n const executed = executeSubscriptionEvent({ ...init.validated, rootValue: step.value })\n const result = init.executor.formatEvent(isPromise(executed) ? await executed : executed, init.ctx)\n if (result.errors !== undefined) this.#partial = true\n return { done: false, value: result }\n }\n\n async return(): Promise<IteratorResult<FormattedExecutionResult>> {\n if (this.#ended) return DONE\n this.#first = undefined\n // ends ctx.signal: a source following it (MemoryPubSub, a generator iterating it) ends at once\n this.#end(this.#partial ? 'partial' : 'success', undefined)\n const reading = this.#reading > 0\n try {\n const returned = Promise.resolve(this.#init.source.return?.())\n // an async generator runs return() only once its pending next() settles, which a source\n // ignoring ctx.signal may never do: do not wait for it then\n if (reading) returned.catch(noop)\n else await returned\n } catch {\n // the source is gone either way\n }\n return DONE\n }\n\n throw(): Promise<IteratorResult<FormattedExecutionResult>> {\n return this.return()\n }\n\n [Symbol.asyncIterator](): GraphQLResultStream {\n return this\n }\n\n #end(\n outcome: NonNullable<GraphQLOperationEvent['outcome']>,\n errors: readonly GraphQLFormattedError[] | undefined,\n ): void {\n if (this.#ended) return\n this.#ended = true\n if (this.#onAbort !== undefined) this.#init.signal?.removeEventListener('abort', this.#onAbort)\n this.#init.onEnd(outcome, errors)\n }\n}\n\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\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 { SubscribeOptions } from './pubsub.ts'\nimport type { GraphQLErrorMapper, GraphQLErrorMapperClass, GraphQLGuard, GraphQLGuardClass } 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/** 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 /** SSE heartbeat (ms), `false` for none. Default: the `HttpPlugin` `sse` option. */\n readonly heartbeat?: number | false\n /** SSE maximum duration (ms). Default: none. */\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 /** 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 /** GraphiQL on `GET path` with `accept: text/html`. Default `NODE_ENV === 'development'`. */\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. */\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\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 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}\n\nconst KEYS: ReadonlySet<string> = new Set([\n 'path',\n 'http',\n 'guards',\n 'errorMappers',\n 'exposeErrors',\n 'introspection',\n 'graphiql',\n 'limits',\n 'documentCache',\n 'subscriptions',\n 'pubsub',\n 'enforcement',\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 return {\n path,\n http,\n guards: refs<GraphQLGuardRef>('guards', options['guards'], 'canResolve'),\n errorMappers: refs<GraphQLErrorMapperRef>('errorMappers', options['errorMappers'], 'map'),\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 }\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 */\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 { 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 /** Input object types by name (null handling of nested input values). */\n readonly inputs: ReadonlyMap<string, GraphQLInputTypeDefinition>\n}\n\n/** The generated invoker of a binding. */\ntype Invoke = GraphQLResolverBinding['invoke']\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 invoke: Invoke = binding.invoke\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\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 route = Object.freeze({ meta: binding.meta, coordinate })\n const parentType = parent.name\n const fieldName = field.name\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 allowed = runGuards(\n container,\n guards,\n new FieldContext(route, operation, parentType, fieldName, args, p, i),\n )\n // §8.5: guards (they see the coerced arguments), then null handling, then invoke\n const call = (): unknown => {\n if (normalize !== undefined) normalize(args)\n return invoke(resolveIn(container, target), p, args, operation, i)\n }\n if (allowed === true) return call()\n if (allowed === false) return forbidden()\n return allowed.then(ok => (ok ? call() : forbidden()))\n }\n }\n if (binding.operation === '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/** 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(name: string, definition: ScalarDefinition<unknown>): GraphQLScalarType {\n const parseLiteral = definition.parseLiteral\n return new GraphQLScalarType({\n name,\n ...(definition.description === undefined ? {} : { description: definition.description }),\n ...(definition.specifiedByURL === undefined ? {} : { specifiedByURL: definition.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 GraphQLTypeResolver,\n} from 'graphql'\nimport type {\n GraphQLArgumentDefinition,\n GraphQLDiscriminator,\n GraphQLFieldDefinition,\n GraphQLInputTypeDefinition,\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 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', '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 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) checkBinding(coordinate, field['resolver'], problems)\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 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\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/** A union's `resolveType`, from its discriminator: data read once, at boot. */\nfunction typeResolver(discriminator: GraphQLDiscriminator): GraphQLTypeResolver<unknown, unknown> {\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,\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) 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,\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 // thunk: object types reference each other (cycles)\n fields: () => Object.fromEntries(type.fields.map(field => [field.name, fieldConfig(type, field)])),\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 const scalar = type.scalar\n return scalar instanceof GraphQLScalarType\n ? scalar\n : definitionScalar(type.name, scalar as ScalarDefinition<unknown>)\n }\n }\n}\n","/**\n * A deferred abort signal for graphql-js (RFC 0005 §8.3, \"Cancellation\").\n *\n * `HttpContext.signal` is created on first read, and creating it costs an `AbortController` plus a\n * close listener on the connection; graphql-js then adds and removes an abort listener per\n * execution. A query whose resolvers are synchronous cannot be cancelled anyway, so the transport\n * passes this stand-in instead: it records the listener graphql-js registers and starts following\n * `ctx.signal` only when the execution turned asynchronous ({@link DeferredAbort.follow}).\n *\n * It implements the part of `AbortSignal` graphql-js 17 reads (`aborted`, `reason`,\n * `throwIfAborted()`, `addEventListener('abort')`, `removeEventListener('abort')`); the transport\n * tests check that a client leaving during an asynchronous query aborts it.\n */\n\ntype Listener = () => void\n\n/** The stand-in passed as graphql-js `abortSignal` by the HTTP transport (one per request). */\nexport class DeferredAbort {\n aborted = false\n reason: unknown = undefined\n /** graphql-js registers one listener per execution; more are kept in {@link #others}. */\n #listener: Listener | undefined = undefined\n #others: Listener[] | undefined = undefined\n\n throwIfAborted(): void {\n if (this.aborted) throw this.reason\n }\n\n addEventListener(type: string, listener: Listener): void {\n if (type !== 'abort') return\n if (this.#listener === undefined) {\n this.#listener = listener\n return\n }\n this.#others ??= []\n this.#others.push(listener)\n }\n\n removeEventListener(type: string, listener: Listener): void {\n if (type !== 'abort') return\n if (this.#listener === listener) {\n this.#listener = undefined\n return\n }\n const others = this.#others\n const index = others === undefined ? -1 : others.indexOf(listener)\n if (index !== -1) others?.splice(index, 1)\n }\n\n /**\n * The execution is asynchronous: from now on, `signal` aborting aborts the execution. Reads the\n * signal only when graphql-js still listens (a pending execution).\n */\n follow(read: () => AbortSignal): void {\n if (this.#listener === undefined && (this.#others === undefined || this.#others.length === 0)) return\n const signal = read()\n if (signal.aborted) {\n this.#abort(signal.reason)\n return\n }\n signal.addEventListener('abort', () => this.#abort(signal.reason), { once: true })\n }\n\n /** This stand-in, typed as the `AbortSignal` graphql-js expects. */\n asSignal(): AbortSignal {\n return this as unknown as AbortSignal\n }\n\n #abort(reason: unknown): void {\n if (this.aborted) return\n this.aborted = true\n this.reason = reason\n const listener = this.#listener\n const others = this.#others\n this.#listener = undefined\n this.#others = undefined\n listener?.()\n if (others !== undefined) for (const other of others) other()\n }\n}\n","/**\n * Content negotiation of the GraphQL endpoint (RFC 0005 §8.3): which of the media types the\n * endpoint produces a request accepts best. Import-free.\n *\n * `application/json` is the only type matched by wildcards (`*\\/*`, `application/*`): the\n * GraphQL-over-HTTP draft asks for `application/json` when the client accepts anything, and the\n * other types change the protocol (`application/graphql-response+json` statuses, an event stream,\n * the GraphiQL page), so they are chosen only when listed. Among types of equal quality,\n * `application/graphql-response+json` wins, then `application/json`, then HTML (a browser listing\n * `text/html` first gets GraphiQL). An event stream is chosen only when it is strictly preferred, or\n * the only acceptable type: a client listing JSON and `text/event-stream` alike (urql, for\n * incremental delivery) gets its queries and mutations as one JSON body, and its subscriptions as\n * a stream ({@link STREAMABLE}).\n */\n\n/** What a response is encoded as. */\nexport const Media: {\n readonly EventStream: 0\n readonly GraphQLJson: 1\n readonly Json: 2\n readonly Html: 3\n /** Nothing the endpoint produces is acceptable: 406. */\n readonly None: 4\n} = Object.freeze({ EventStream: 0, GraphQLJson: 1, Json: 2, Html: 3, None: 4 })\n\n/** One of the {@link Media} values. */\nexport type MediaKind = (typeof Media)[keyof typeof Media]\n\n/**\n * Added to a negotiated JSON type when an event stream is acceptable too, though not preferred: a\n * subscription, which has no JSON answer, is then streamed. `answer & MEDIA` is the {@link MediaKind}.\n */\nexport const STREAMABLE = 8\n\n/** The {@link MediaKind} bits of a {@link negotiate} answer. */\nexport const MEDIA = 7\n\n/** The media type names, by {@link Media} value (`None` excluded). */\nconst NAMES: readonly (readonly [type: string, subtype: string])[] = [\n ['text', 'event-stream'],\n ['application', 'graphql-response+json'],\n ['application', 'json'],\n ['text', 'html'],\n]\n\n/** A media range of an `accept` header. */\ninterface Range {\n readonly type: string\n readonly subtype: string\n readonly q: number\n}\n\n/** The media ranges of an `accept` header (lower-case, without parameters other than `q`). */\nfunction parseRanges(header: string): Range[] {\n const ranges: Range[] = []\n for (const item of header.split(',')) {\n const parts = item.split(';')\n const media = (parts[0] as string).trim().toLowerCase()\n const slash = media.indexOf('/')\n if (slash <= 0 || slash === media.length - 1) continue\n let q = 1\n for (let index = 1; index < parts.length; index++) {\n const parameter = (parts[index] as string).trim()\n if (parameter.length < 2 || (parameter.charCodeAt(0) | 0x20) !== 0x71 /* q */ || parameter[1] !== '=') continue\n const value = Number(parameter.slice(2))\n // an invalid weight leaves the range as it is (RFC 9110 §12.4.2 allows 0 to 1, 3 decimals)\n if (value >= 0 && value <= 1) q = value\n }\n ranges.push({ type: media.slice(0, slash), subtype: media.slice(slash + 1), q })\n }\n return ranges\n}\n\n/**\n * The quality of `type/subtype` in `ranges`: that of the most specific matching range (RFC 9110\n * §12.5.1), wildcards only when `wildcards` is set; 0 when nothing matches.\n */\nfunction quality(ranges: readonly Range[], type: string, subtype: string, wildcards: boolean): number {\n let best = -1\n let specificity = -1\n for (const range of ranges) {\n let level: number\n if (range.type === type && range.subtype === subtype) level = 2\n else if (!wildcards) continue\n else if (range.type === type && range.subtype === '*') level = 1\n else if (range.type === '*' && range.subtype === '*') level = 0\n else continue\n if (level > specificity || (level === specificity && range.q > best)) {\n specificity = level\n best = range.q\n }\n }\n return best < 0 ? 0 : best\n}\n\n/**\n * Chooses the media type of a response among `produced` (a bit mask of `1 << Media.X`), per\n * `accept` (`undefined`: no header, i.e. `application/json`): a {@link MediaKind}, plus\n * {@link STREAMABLE} when a JSON type wins and an event stream is acceptable too.\n */\nexport function negotiate(accept: string | undefined, produced: number): number {\n if (accept === undefined) return produced & (1 << Media.Json) ? Media.Json : Media.None\n const ranges = parseRanges(accept)\n if (ranges.length === 0) return produced & (1 << Media.Json) ? Media.Json : Media.None\n let chosen: number = Media.None\n let best = 0\n for (let media: number = Media.GraphQLJson; media < NAMES.length; media++) {\n if ((produced & (1 << media)) === 0) continue\n const [type, subtype] = NAMES[media] as readonly [string, string]\n const q = quality(ranges, type, subtype, media === Media.Json)\n if (q > best) {\n best = q\n chosen = media\n }\n }\n if (produced & (1 << Media.EventStream)) {\n const q = quality(ranges, 'text', 'event-stream', false)\n // strictly preferred, or the only acceptable type\n if (q > best) return Media.EventStream\n if (q > 0 && (chosen === Media.GraphQLJson || chosen === Media.Json)) chosen |= STREAMABLE\n }\n return chosen\n}\n\nconst CACHE_MAX = 64\n\n/**\n * {@link negotiate} for one route, memoised by header value: a server sees a handful of `accept`\n * values, so a request costs a map lookup. Bounded, since clients choose the values: cleared when\n * full.\n */\nexport class Negotiator {\n readonly #produced: number\n readonly #cache = new Map<string, number>()\n /** The answer without `accept` header. */\n readonly #absent: number\n\n /** `produced`: a bit mask of `1 << Media.X`. */\n constructor(produced: number) {\n this.#produced = produced\n this.#absent = negotiate(undefined, produced)\n }\n\n /** The {@link negotiate} answer: a {@link MediaKind}, possibly with {@link STREAMABLE}. */\n choose(accept: string | undefined): number {\n if (accept === undefined) return this.#absent\n let media = this.#cache.get(accept)\n if (media === undefined) {\n media = negotiate(accept, this.#produced)\n if (this.#cache.size === CACHE_MAX) this.#cache.clear()\n this.#cache.set(accept, media)\n }\n return media\n }\n}\n","/**\n * The GraphiQL page (RFC 0005 §8.3, §8.9): served on `GET path` with `accept: text/html` when the\n * `graphiql` option is on (default: `NODE_ENV === 'development'`). React and GraphiQL load from a\n * pinned CDN with Subresource Integrity; the inline script is fixed at boot and allowed by hash in\n * the page's own `content-security-policy`, which overrides the strict API default of RFC 0001 on\n * this response only.\n */\nimport { createHash } from 'node:crypto'\n\n/** jsDelivr. */\nexport const GRAPHIQL_CDN = 'https://cdn.jsdelivr.net'\n\n/** A pinned CDN asset. */\nexport interface GraphiQLAsset {\n readonly url: string\n /** Subresource Integrity of the pinned file. */\n readonly integrity: string\n readonly kind: 'script' | 'style'\n}\n\n/**\n * The assets of the page: GraphiQL 3 (the last major with a UMD build) on React 18. Bumped by hand,\n * with their SRI hashes (`sha384` of the files on the CDN).\n */\nexport const GRAPHIQL_ASSETS: readonly GraphiQLAsset[] = Object.freeze([\n {\n url: `${GRAPHIQL_CDN}/npm/graphiql@3.9.0/graphiql.min.css`,\n integrity: 'sha384-QMux00XgRtwRLSYIY3kw2rj1ovk5AuuliAchk+HSQbqdbGFnz9GYuqIlOqxhwCE2',\n kind: 'style',\n },\n {\n url: `${GRAPHIQL_CDN}/npm/react@18.3.1/umd/react.production.min.js`,\n integrity: 'sha384-DGyLxAyjq0f9SPpVevD6IgztCFlnMF6oW/XQGmfe+IsZ8TqEiDrcHkMLKI6fiB/Z',\n kind: 'script',\n },\n {\n url: `${GRAPHIQL_CDN}/npm/react-dom@18.3.1/umd/react-dom.production.min.js`,\n integrity: 'sha384-gTGxhz21lVGYNMcdJOyq01Edg0jhn/c22nsx0kyqP0TxaV5WVdsSH1fSDUf5YJj1',\n kind: 'script',\n },\n {\n url: `${GRAPHIQL_CDN}/npm/graphiql@3.9.0/graphiql.min.js`,\n integrity: 'sha384-8NGfVj4CVlqHajlZj+bPJT4thxPMHMJYn7DWK2CvtopLd02E7qsPHazniBYvVjOO',\n kind: 'script',\n },\n])\n\n/** The rendered page. */\nexport interface GraphiQLPage {\n readonly html: string\n readonly csp: string\n}\n\n/** `<`, `>` and `&` escaped: JSON safe inside a `<script>` element. */\nfunction scriptJson(value: unknown): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c').replace(/>/g, '\\\\u003e').replace(/&/g, '\\\\u0026')\n}\n\nfunction escapeHtml(text: string): string {\n return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n}\n\n/** The GraphiQL page of the endpoint `endpoint` (an absolute path, prefix included) and its CSP. */\nexport function renderGraphiQL(endpoint: string): GraphiQLPage {\n const tags = GRAPHIQL_ASSETS.map(asset =>\n asset.kind === 'style'\n ? `<link rel=\"stylesheet\" href=\"${escapeHtml(asset.url)}\" integrity=\"${asset.integrity}\" crossorigin=\"anonymous\">`\n : `<script src=\"${escapeHtml(asset.url)}\" integrity=\"${asset.integrity}\" crossorigin=\"anonymous\"></script>`,\n )\n const inline = [\n `const fetcher = GraphiQL.createFetcher({ url: ${scriptJson(endpoint)} })`,\n `ReactDOM.createRoot(document.getElementById('graphiql')).render(React.createElement(GraphiQL, { fetcher }))`,\n ].join('\\n')\n const hash = `'sha256-${createHash('sha256').update(inline).digest('base64')}'`\n const html = [\n '<!doctype html>',\n '<html lang=\"en\">',\n '<head>',\n '<meta charset=\"utf-8\">',\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">',\n '<title>GraphiQL</title>',\n '<style>body { margin: 0; } #graphiql { height: 100dvh; }</style>',\n ...tags.filter(tag => tag.startsWith('<link')),\n '</head>',\n '<body>',\n '<div id=\"graphiql\">Loading GraphiQL…</div>',\n ...tags.filter(tag => tag.startsWith('<script')),\n `<script>${inline}</script>`,\n '</body>',\n '</html>',\n '',\n ].join('\\n')\n const csp = [\n \"default-src 'none'\",\n `script-src ${GRAPHIQL_CDN} ${hash}`,\n // GraphiQL and CodeMirror set inline styles\n `style-src 'unsafe-inline' ${GRAPHIQL_CDN}`,\n `font-src data: ${GRAPHIQL_CDN}`,\n \"img-src 'self' data:\",\n \"connect-src 'self'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n \"frame-ancestors 'self'\",\n ].join('; ')\n return { html, csp }\n}\n","/**\n * GraphQL over SSE, distinct connections mode (RFC 0005 §5.6, §8.3, §8.11): the results of an\n * operation as `next` events, then a `complete` event. Everything else (headers, heartbeats,\n * backpressure, client abort, graceful close) is RFC 0006's `HttpResponse.sse()`.\n */\nimport type { SseEvent } from '@znight/http'\nimport type { GraphQLResultStream } from '../execution.ts'\n\n/** The last event of a stream that ended normally. */\nconst COMPLETE: SseEvent<string> = Object.freeze({ event: 'complete', data: '' })\nconst DONE: IteratorResult<SseEvent> = Object.freeze({ done: true, value: undefined })\n\n/**\n * The event source of an operation: one `next` event per result, then `complete` when the\n * operation ended by itself. A stream ended by `ctx.signal` (client gone, shutdown, `maxDuration`)\n * gets no `complete`: GraphQL-over-SSE clients then treat it as a lost connection and retry.\n */\nexport class ResultEvents implements AsyncIterableIterator<SseEvent> {\n readonly #results: GraphQLResultStream\n readonly #signal: AbortSignal\n #done = false\n\n constructor(results: GraphQLResultStream, signal: AbortSignal) {\n this.#results = results\n this.#signal = signal\n }\n\n async next(): Promise<IteratorResult<SseEvent>> {\n if (this.#done) return DONE\n const step = await this.#results.next()\n if (step.done !== true) return { done: false, value: { event: 'next', data: step.value } }\n this.#done = true\n return this.#signal.aborted ? DONE : { done: false, value: COMPLETE }\n }\n\n async return(): Promise<IteratorResult<SseEvent>> {\n this.#done = true\n await this.#results.return()\n return DONE\n }\n\n [Symbol.asyncIterator](): AsyncIterableIterator<SseEvent> {\n return this\n }\n}\n","/**\n * GraphQL over HTTP (RFC 0005 §8.3, GraphQL-over-HTTP specification draft), the handlers of the two\n * plugin routes of the endpoint (`GET` and `POST` on `path`).\n *\n * - `POST`: `application/json` bodies only (415 otherwise: no form or text body, so cross-site\n * requests are always preflighted), read by the handler so that every malformed request gets a\n * GraphQL-shaped error (malformed JSON, missing query, batching: 400; body limit: 413).\n * - `GET`: queries only (405 with `allow: POST` otherwise), when `http.get` is on; GraphiQL with\n * `accept: text/html` when enabled.\n * - The response is `application/graphql-response+json` when the client lists it (200 with data,\n * 400 for request errors), otherwise `application/json` (200 for every well-formed request); no\n * `accept` header is `application/json`; nothing acceptable is 406. `accept: text/event-stream`\n * selects GraphQL over SSE for any operation when it is preferred to the JSON types (or the only\n * one listed); listed at the same quality as a JSON type, only subscriptions are streamed.\n *\n * Hot path (a cached query whose resolvers are synchronous): a memoised negotiation (a map lookup),\n * the query string read without `URLSearchParams` or the body read and parsed once, one options\n * object and one deferred abort per request, the executor's synchronous result, and a single\n * `JSON.stringify` by the serialiser. Every answer stays on the fast lane of `@znight/http` (no\n * promise while the route is synchronous, headers from a template) unless the application adds\n * CORS, guards, `http:request` listeners or wrappers: a `GET` answered as `application/json` with\n * status 200 returns the plain result; the other answers are an `HttpResponse` with a plain JSON\n * body, at most a `content-type` header and an explicit status (a `POST` route answers 201 by\n * default), which the fast lane serves too.\n */\nimport type { HttpContext, SseOptions } from '@znight/http'\nimport type { FormattedExecutionResult } from 'graphql'\nimport type { ExecuteOptions, GraphQLExecutor, GraphQLRequest, GraphQLResponse } from '../execution.ts'\n\nimport { HttpResponse, isHttpException, parseMediaType } from '@znight/http'\n\nimport { GraphQLErrorCode } from '../errors.ts'\nimport { SUBSCRIBE } from '../execution.ts'\nimport { DeferredAbort } from './abort.ts'\nimport { MEDIA, Media, type MediaKind, Negotiator, STREAMABLE } from './accept.ts'\nimport { renderGraphiQL } from './graphiql.ts'\nimport { ResultEvents } from './sse.ts'\n\n/** What the transport is built from (resolved plugin options). */\nexport interface HttpTransportOptions {\n /** The executor of the plugin, built at bootstrap (after the routes may have been collected). */\n readonly executor: () => GraphQLExecutor\n /** Absolute path of the endpoint, prefix included (GraphiQL's fetcher). */\n readonly endpoint: string\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\nconst JSON_TYPE = 'application/json; charset=utf-8'\nconst GRAPHQL_JSON_TYPE = 'application/graphql-response+json; charset=utf-8'\n\n/** Response options of `application/graphql-response+json` replies, by status. */\nconst GRAPHQL_JSON_200 = Object.freeze({ status: 200, headers: Object.freeze({ 'content-type': GRAPHQL_JSON_TYPE }) })\nconst GRAPHQL_JSON_400 = Object.freeze({ status: 400, headers: Object.freeze({ 'content-type': GRAPHQL_JSON_TYPE }) })\n/** `application/json` is what the serialiser gives an object body: only the status is set. */\nconst JSON_200 = Object.freeze({ status: 200 })\n\nconst UTF8 = new TextDecoder('utf-8', { fatal: true })\n\n/** A request error before execution: `{ errors: [{ message, extensions: { code } }] }`. */\nfunction errorBody(message: string, code: string = GraphQLErrorCode.BadRequest): FormattedExecutionResult {\n return { errors: [{ message, extensions: { code } }] }\n}\n\n/** A reply of `status` carrying a GraphQL error body in the negotiated JSON type (`application/json` before negotiation). */\nfunction errorReply(\n media: MediaKind,\n status: number,\n body: FormattedExecutionResult,\n headers?: Readonly<Record<string, string>>,\n): HttpResponse<FormattedExecutionResult> {\n const type = media === Media.GraphQLJson ? GRAPHQL_JSON_TYPE : JSON_TYPE\n return new HttpResponse(body, { status, headers: { ...headers, 'content-type': type } })\n}\n\nconst NOT_ACCEPTABLE = errorReply(\n Media.Json,\n 406,\n errorBody(\n 'None of the accepted media types can be produced: accept application/graphql-response+json, application/json or text/event-stream',\n ),\n)\nconst GET_NOT_ALLOWED = errorReply(\n Media.Json,\n 405,\n errorBody('GraphQL operations are sent with POST on this endpoint'),\n Object.freeze({ allow: 'POST' }),\n)\n\n/** `content-type` values of JSON bodies seen most often, compared before parsing. */\nfunction isJsonRequest(contentType: string | undefined): boolean {\n if (contentType === 'application/json' || contentType === 'application/json; charset=utf-8') return true\n // parsed once per distinct value (memoised by @znight/http)\n const media = parseMediaType(contentType)\n if (media === undefined || media.type !== 'application/json') return false\n return media.charset === undefined || media.charset === 'utf-8' || media.charset === 'utf8'\n}\n\n/** Why the parameters of a request are invalid, `undefined` when they are valid. */\nfunction invalidParams(params: Readonly<Record<string, unknown>>): string | undefined {\n const query = params['query']\n if (typeof query !== 'string') {\n return query === undefined || query === null\n ? 'Missing query: send { query, variables?, operationName?, extensions? }'\n : 'The query must be a string'\n }\n const operationName = params['operationName']\n if (operationName !== undefined && operationName !== null && typeof operationName !== 'string') {\n return 'operationName must be a string'\n }\n if (!isMapOrNull(params['variables'])) return 'variables must be an object'\n if (!isMapOrNull(params['extensions'])) return 'extensions must be an object'\n return undefined\n}\n\n/** The parameters of a GraphQL `GET` request. */\nconst GET_PARAMS = ['query', 'operationName', 'variables', 'extensions'] as const\n\ntype GetParams = Partial<Record<(typeof GET_PARAMS)[number], string | string[]>>\n\n/** A query string component decoded like `URLSearchParams` (`+` is a space); `undefined` when malformed. */\nfunction decodeComponent(text: string): string | undefined {\n if (text.indexOf('%') === -1 && text.indexOf('+') === -1) return text\n try {\n return decodeURIComponent(text.replaceAll('+', ' '))\n } catch {\n return undefined\n }\n}\n\n/**\n * The GraphQL parameters of a request target, read directly: `ctx.query` builds a record of every\n * parameter through `URLSearchParams` (about 0.35 µs of a `GET` on Node.js, 0.15 µs on Bun, see\n * `test/bench/http.bench.ts`). A repeated parameter\n * becomes an array, like `ctx.query`. `undefined` when a component is malformed percent-encoding:\n * the caller falls back to `ctx.query` (which keeps such sequences as they are).\n */\nfunction readGetParams(url: string): GetParams | undefined {\n const params: GetParams = {}\n const mark = url.indexOf('?')\n if (mark === -1) return params\n const length = url.length\n let start = mark + 1\n while (start < length) {\n let end = url.indexOf('&', start)\n if (end === -1) end = length\n if (end > start) {\n let equals = url.indexOf('=', start)\n if (equals === -1 || equals > end) equals = end\n const name = decodeComponent(url.slice(start, equals))\n if (name === undefined) return undefined\n if (name === 'query' || name === 'operationName' || name === 'variables' || name === 'extensions') {\n const value = equals === end ? '' : decodeComponent(url.slice(equals + 1, end))\n if (value === undefined) return undefined\n const existing = params[name]\n if (existing === undefined) params[name] = value\n else params[name] = typeof existing === 'string' ? [existing, value] : [...existing, value]\n }\n }\n start = end + 1\n }\n return params\n}\n\nfunction isMapOrNull(value: unknown): boolean {\n return value === undefined || value === null || (typeof value === 'object' && !Array.isArray(value))\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/** The handlers of the GraphQL endpoint. */\nexport class HttpTransport {\n readonly #resolveExecutor: () => GraphQLExecutor\n #executor: GraphQLExecutor | undefined\n readonly #getQueries: boolean\n readonly #sse: SseOptions | false\n readonly #post: Negotiator\n readonly #get: Negotiator\n /** The GraphiQL page, `undefined` when disabled. */\n readonly #graphiql: HttpResponse<Uint8Array> | undefined\n\n constructor(options: HttpTransportOptions) {\n this.#resolveExecutor = options.executor\n this.#getQueries = options.get\n this.#sse = options.sse\n const json = (1 << Media.GraphQLJson) | (1 << Media.Json) | (options.sse === false ? 0 : 1 << Media.EventStream)\n this.#post = new Negotiator(json)\n this.#get = new Negotiator(options.graphiql ? json | (1 << Media.Html) : json)\n if (options.graphiql) {\n const page = renderGraphiQL(options.endpoint)\n // encoded once: the same immutable response serves every request\n this.#graphiql = new HttpResponse(new TextEncoder().encode(page.html), {\n status: 200,\n headers: {\n 'content-type': 'text/html; charset=utf-8',\n 'content-security-policy': page.csp,\n 'cache-control': 'no-store',\n },\n })\n }\n }\n\n /** `POST path`. */\n readonly post = (ctx: HttpContext): unknown => {\n const headers = ctx.headers\n const negotiated = this.#post.choose(headers['accept'])\n const media = (negotiated & MEDIA) as MediaKind\n if (media === Media.None) return NOT_ACCEPTABLE\n if (!isJsonRequest(headers['content-type'])) {\n return errorReply(\n media,\n 415,\n errorBody('Send GraphQL requests as application/json (content-type: application/json)'),\n )\n }\n const encoding = headers['content-encoding']\n if (encoding !== undefined && encoding.trim().toLowerCase() !== 'identity' && encoding.trim() !== '') {\n return errorReply(media, 415, errorBody(`Unsupported content encoding \"${encoding}\"`))\n }\n return ctx.rawBody().then(\n bytes => this.#posted(ctx, bytes, media, negotiated >= STREAMABLE),\n (error: unknown) => transportError(error, media),\n )\n }\n\n /** `GET path`. */\n readonly get = (ctx: HttpContext): unknown => {\n const media = (this.#get.choose(ctx.headers['accept']) & MEDIA) as MediaKind\n if (media === Media.Html) return this.#graphiql\n if (media === Media.None) return NOT_ACCEPTABLE\n if (!this.#getQueries) return GET_NOT_ALLOWED\n const params = readGetParams(ctx.url) ?? ctx.query\n const request: Record<string, unknown> = {}\n for (const name of GET_PARAMS) {\n const value = params[name]\n if (value === undefined) continue\n if (typeof value !== 'string') return errorReply(media, 400, errorBody(`Repeated ${name} parameter`))\n if (name === 'variables' || name === 'extensions') {\n try {\n request[name] = JSON.parse(value)\n } catch {\n return errorReply(media, 400, errorBody(`The ${name} parameter must be JSON`))\n }\n } else {\n request[name] = value\n }\n }\n const invalid = invalidParams(request)\n if (invalid !== undefined) return errorReply(media, 400, errorBody(invalid))\n if (media === Media.EventStream) return this.#stream(ctx, request as unknown as GraphQLRequest, true)\n // GET carries queries only: no subscription to stream\n return this.#execute(ctx, request as unknown as GraphQLRequest, media, true, false)\n }\n\n /** A `POST` body read: parsed, checked, executed or streamed. */\n #posted(ctx: HttpContext, bytes: Uint8Array, media: MediaKind, streamable: boolean): unknown {\n if (bytes.byteLength === 0) {\n return errorReply(media, 400, errorBody('Missing request body: send { query, variables?, operationName? }'))\n }\n let body: unknown\n try {\n body = JSON.parse(UTF8.decode(bytes))\n } catch {\n return errorReply(media, 400, errorBody('Malformed JSON body'))\n }\n if (body === null || typeof body !== 'object') {\n return errorReply(media, 400, errorBody('The body must be a JSON object: { query, variables?, operationName? }'))\n }\n if (Array.isArray(body)) {\n return errorReply(media, 400, errorBody('Operation batching is not supported: send one operation per request'))\n }\n const invalid = invalidParams(body as Record<string, unknown>)\n if (invalid !== undefined) return errorReply(media, 400, errorBody(invalid))\n if (media === Media.EventStream) return this.#stream(ctx, body as GraphQLRequest, false)\n return this.#execute(ctx, body as GraphQLRequest, media, false, streamable)\n }\n\n /**\n * Executes a query or a mutation; synchronous while the execution is. A subscription is streamed\n * when the client accepts an event stream (`streamable`), a 400 otherwise.\n */\n #execute(ctx: HttpContext, request: GraphQLRequest, media: MediaKind, get: boolean, streamable: boolean): unknown {\n const executor = this.#executor ?? this.#bind()\n const abort = new DeferredAbort()\n const options: ExecuteOptions = {\n transport: 'http',\n http: ctx,\n abortSignal: abort.asSignal(),\n queriesOnly: get,\n streamSubscriptions: streamable,\n }\n const response = executor.execute(request, options)\n if (response === SUBSCRIBE) return this.#stream(ctx, request, get)\n if (!isPromise(response)) return reply(response, media, get)\n // asynchronous resolvers: a client leaving now aborts the execution\n abort.follow(() => ctx.signal)\n return response.then(\n settled => reply(settled, media, get),\n (error: unknown) => {\n if (!abort.aborted || error !== abort.reason) throw error\n // nobody reads it: the client is gone (or the server stops)\n return errorReply(media, 503, errorBody('The request was aborted', GraphQLErrorCode.ServiceUnavailable))\n },\n )\n }\n\n /** GraphQL over SSE: any operation, its results as `next` events. */\n #stream(ctx: HttpContext, request: GraphQLRequest, get: boolean): Promise<unknown> {\n const executor = this.#executor ?? this.#bind()\n const signal = ctx.signal\n const options: ExecuteOptions = { transport: 'sse', http: ctx, signal, queriesOnly: get }\n return executor.subscribe(request, options).then(\n outcome => {\n if ('status' in outcome) {\n return errorReply(Media.Json, outcome.status, outcome.result, outcome.headers)\n }\n // the SSE options were checked at boot (see sseOptions)\n return HttpResponse.sse(new ResultEvents(outcome, signal), this.#sse as SseOptions)\n },\n (error: unknown) => {\n if (!signal.aborted || error !== signal.reason) throw error\n return errorReply(Media.Json, 503, errorBody('The request was aborted', GraphQLErrorCode.ServiceUnavailable))\n },\n )\n }\n\n #bind(): GraphQLExecutor {\n this.#executor = this.#resolveExecutor()\n return this.#executor\n }\n}\n\n/**\n * The HTTP reply of an executor response. `application/json` answers 200 to every well-formed\n * request (request errors included); `application/graphql-response+json` keeps the status.\n */\nfunction reply(response: GraphQLResponse, media: MediaKind, get: boolean): unknown {\n const status = response.status\n const result = response.result\n if (media === Media.Json) {\n if (status === 200 || status === 400) {\n // a plain object on a GET route: 200 application/json (a POST route would answer 201)\n return get ? result : new HttpResponse(result, JSON_200)\n }\n return errorReply(media, status, result, response.headers)\n }\n if (response.headers === undefined) {\n if (status === 200) return new HttpResponse(result, GRAPHQL_JSON_200)\n if (status === 400) return new HttpResponse(result, GRAPHQL_JSON_400)\n }\n return errorReply(media, status, result, response.headers)\n}\n\n/** A failure reading the body (413 past the body limit, 400 for an aborted body) with a GraphQL error body. */\nfunction transportError(error: unknown, media: MediaKind): HttpResponse<FormattedExecutionResult> {\n if (!isHttpException(error)) throw error\n return errorReply(media, error.status, errorBody(error.message))\n}\n\n/** Checks the SSE options once (`HttpResponse.sse()` validates them): `undefined` when they are valid. */\nexport function checkSseOptions(options: SseOptions): string | undefined {\n try {\n HttpResponse.sse([], options)\n return undefined\n } catch (error) {\n return error instanceof Error ? error.message : String(error)\n }\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()`) and contributes the GraphQL endpoint 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 { PluginHttpRoutes, PluginHttpRoutesContext, PluginRoute, SseOptions } from '@znight/http'\nimport type { FormattedExecutionResult, GraphQLSchema } from 'graphql'\nimport type { CheckedField } from './decisions.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 } from './types.ts'\n\nimport { displayName, ErrorCode, resolveOptions, ZnightError } from '@znight/core'\nimport { printSchema } from 'graphql'\n\nimport { checkFieldDecisions } from './decisions.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 { buildGraphQLSchema, graphqlSection } from './schema.ts'\nimport { GraphQLTokens } from './tokens.ts'\nimport { checkSseOptions, HttpTransport } 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}\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 #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` and `errorMappers` 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'] 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.#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 GraphQL endpoint (`GET` and `POST` on\n * `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 endpoint = endpointPath(context.prefix, options.path)\n const transport = new HttpTransport({\n // called on the first request: the routes are collected before or after this plugin's onBootstrap\n executor: () => this.#ready().executor,\n endpoint,\n get: http.get,\n graphiql: options.graphiql,\n sse: sseOptions(options),\n })\n this.#endpoint = endpoint\n const common = {\n name: 'handle',\n path: options.path,\n ...(http.meta.length === 0 ? {} : { meta: http.meta }),\n ...(http.guards.length === 0 ? {} : { guards: http.guards }),\n }\n const routes: PluginRoute[] = [{ ...common, method: 'POST', handler: transport.post, bodyLimit: http.bodyLimit }]\n // GET serves queries (`http.get`) and GraphiQL; without either, the router answers 405\n if (http.get || options.graphiql) routes.unshift({ ...common, method: 'GET', handler: transport.get })\n return routes\n }\n\n onBootstrap(ctx: PluginContext): void {\n this.#container = ctx.container\n const options = this.#resolve()\n if (typeof this.#options === 'function') this.#checkHttp(ctx, options)\n this.#checkSse(options)\n this.#runtime = this.#build(ctx, options)\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 async onStop(): Promise<void> {\n this.#stop?.abort(new Error('The application is stopping'))\n await this.#runtime?.executor.stopDirect()\n }\n\n onDispose(): 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 /** 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 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 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 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 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 inputs,\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 })\n ctx.logger.debug('GraphQL schema built', { types: types.length, schemaHash: section.schemaHash })\n return { schema, section, executor }\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/** `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":";;;;;;;;;;;;;;;AASA,MAAa,mBA2BT,OAAO,OAAO;CAChB,aAAa;CACb,kBAAkB;CAClB,cAAc;CACd,iBAAiB;CACjB,iBAAiB;CACjB,WAAW;CACX,UAAU;CACV,UAAU;CACV,iBAAiB;CACjB,YAAY;CACZ,sBAAsB;CACtB,oBAAoB;CACpB,qBAAqB;AACvB,CAAC;;;;;;;;;AA0BD,IAAa,mBAAb,cAAsC,MAAM;;CAE1C;;CAEA;CAEA,YAAY,SAAiB,SAAkC;EAC7D,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EACjF,KAAK,OAAO;EACZ,KAAK,OAAO,QAAQ;EACpB,KAAK,aAAa,QAAQ;CAC5B;AACF;;;;;;AClEA,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,+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