@prisma-next/framework-components 0.11.0-dev.2 → 0.11.0-dev.20

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.
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":["candidate","#kind","#terminalName","#annotations"],"sources":["../src/execution/runtime-error.ts","../src/annotations.ts","../src/execution/async-iterable-result.ts","../src/execution/race-against-abort.ts","../src/execution/before-execute-chain.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts","../src/execution/runtime-middleware.ts","../src/meta-builder.ts"],"sourcesContent":["export interface RuntimeErrorEnvelope extends Error {\n readonly code: string;\n readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\n/**\n * Stable code emitted by the runtime when an in-flight `execute()`\n * is cancelled via the per-query `AbortSignal`. The envelope's\n * `details.phase` distinguishes where the abort was observed:\n *\n * - `'encode'` — abort fired during `encodeParams` (SQL) or\n * `resolveValue` (Mongo).\n * - `'decode'` — abort fired during `decodeRow` / `decodeField`.\n * - `'stream'` — abort fired between rows or before any codec call\n * (already-aborted at entry).\n * - `'beforeExecute'` / `'afterExecute'` / `'onRow'` — abort fired\n * on entry to or during the corresponding middleware phase\n * (cooperative cancellation per the param-transform seam).\n */\nexport const RUNTIME_ABORTED = 'RUNTIME.ABORTED' as const;\n\n/** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */\nexport type RuntimeAbortedPhase =\n | 'encode'\n | 'decode'\n | 'stream'\n | 'beforeExecute'\n | 'afterExecute'\n | 'onRow';\n\n/**\n * Type guard for the runtime-error envelope produced by `runtimeError`.\n *\n * Prefer this over duck-typing on `error.code` directly so consumers stay\n * insulated from the envelope's internal shape.\n */\nexport function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {\n return (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string' &&\n 'category' in error &&\n 'severity' in error\n );\n}\n\nexport function runtimeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): RuntimeErrorEnvelope {\n const error = new Error(message) as RuntimeErrorEnvelope;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n\n return Object.assign(error, {\n code,\n category: resolveCategory(code),\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction resolveCategory(code: string): RuntimeErrorEnvelope['category'] {\n const prefix = code.split('.')[0] ?? 'RUNTIME';\n switch (prefix) {\n case 'PLAN':\n case 'CONTRACT':\n case 'LINT':\n case 'BUDGET':\n return prefix;\n default:\n return 'RUNTIME';\n }\n}\n\n/**\n * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the\n * abort was observed — codec call sites (`encode` / `decode` / `stream`)\n * or middleware seams (`beforeExecute` / `afterExecute` / `onRow`), as\n * enumerated on {@link RuntimeAbortedPhase}. Cause carries\n * `signal.reason` verbatim from the platform — native abort produces a\n * `DOMException`, explicit `controller.abort(reason)` produces whatever\n * the caller passed. No synthesis happens here.\n */\nexport function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope {\n const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });\n return Object.assign(envelope, { cause });\n}\n","import { runtimeError } from './execution/runtime-error';\n\n/**\n * The kinds of operations an annotation may apply to.\n *\n * - `'read'` — `SELECT` / `find` / `first` / `all` / `count` / aggregates.\n * - `'write'` — `INSERT` / `UPDATE` / `DELETE` / `create` / `update` / `delete` / `upsert`.\n *\n * Annotations declare which kinds they apply to via `defineAnnotation`'s\n * `applicableTo` option; lane terminals enforce the constraint at both the\n * type level (via `ValidAnnotations`) and at runtime (via\n * `assertAnnotationsApplicable`).\n *\n * Finer-grained kinds (`'select' | 'insert' | 'update' | 'delete' | 'upsert'`)\n * are deliberately deferred. The binary covers the common case (the cache\n * middleware applies to reads; an audit annotation would apply to writes;\n * tracing/OTel applies to both). When a real annotation surfaces that needs\n * a finer split, the union widens and existing handles remain typecheckable.\n */\nexport type OperationKind = 'read' | 'write';\n\n/**\n * An applied annotation. Carries the namespace, the typed payload, and the\n * `applicableTo` set the underlying handle declared. The `__annotation`\n * brand lets `read` distinguish branded user annotations from arbitrary\n * data that may happen to live under the same namespace key in\n * `plan.meta.annotations` (e.g. framework-internal metadata such as\n * `meta.annotations.codecs`).\n *\n * Constructed by calling an `AnnotationHandle` directly (e.g.\n * `cacheAnnotation({ ttl: 60 })`); never instantiated by hand.\n */\nexport interface AnnotationValue<Payload, Kinds extends OperationKind> {\n readonly __annotation: true;\n readonly namespace: string;\n readonly value: Payload;\n readonly applicableTo: ReadonlySet<Kinds>;\n}\n\n/**\n * Handle returned by `defineAnnotation`. The handle is **callable**: the\n * call signature wraps a `Payload` into an `AnnotationValue` ready to\n * pass to a lane terminal's variadic `annotations` argument. The handle\n * also carries static metadata as own properties:\n *\n * - `namespace` — the namespace string the handle was declared with.\n * - `applicableTo` — the frozen `ReadonlySet<Kinds>` consumed by both\n * the type-level `ValidAnnotations` gate and the runtime\n * `assertAnnotationsApplicable` gate.\n * - `read(plan)` — extract the `Payload` from a plan's `meta.annotations`\n * if a value was previously written under this handle's namespace.\n * Returns `undefined` when the annotation is absent or when the stored\n * value is not a branded `AnnotationValue` (e.g. framework-internal\n * metadata under the same namespace key).\n *\n * Handles are the only supported public entry point for reading and\n * writing annotations. Direct mutation of `plan.meta.annotations` is not\n * part of the public API.\n *\n * ```typescript\n * const cacheAnnotation = defineAnnotation<{ ttl: number }>()({\n * namespace: 'cache',\n * applicableTo: ['read'],\n * });\n *\n * // Call the handle to construct a value:\n * const applied = cacheAnnotation({ ttl: 60 });\n *\n * // Read a stored value off a plan:\n * const payload = cacheAnnotation.read(plan);\n * ```\n *\n * Note on the inherited `Function.prototype.apply`: because the handle is\n * a function, the property name `apply` resolves to JavaScript's built-in\n * `Function.prototype.apply` (which lets you invoke a function with an\n * array of arguments). This is **not** the construction entry point — to\n * build an `AnnotationValue`, call the handle directly. The\n * `AnnotationHandle` interface deliberately does not declare an `apply`\n * member of its own.\n */\nexport interface AnnotationHandle<Payload, Kinds extends OperationKind> {\n (value: Payload): AnnotationValue<Payload, Kinds>;\n readonly namespace: string;\n readonly applicableTo: ReadonlySet<Kinds>;\n read(plan: {\n readonly meta: { readonly annotations?: Record<string, unknown> };\n }): Payload | undefined;\n}\n\n/**\n * Options accepted by `defineAnnotation`.\n *\n * `namespace` is the string key under which the annotation is stored in\n * `plan.meta.annotations`. **Reserved namespaces** include framework-\n * internal metadata keys; user handles must not use them:\n *\n * - `codecs` — used by the SQL emitter to record per-alias codec ids\n * (`meta.annotations.codecs[alias] = 'pg/text@1'`); the SQL runtime's\n * `decodeRow` reads from this key. A user `defineAnnotation('codecs')`\n * handle is not structurally prevented, but its behavior with the\n * emitter and the runtime is undefined and we make no compatibility\n * guarantees about it.\n * - Target-specific keys such as `pg` (and equivalents on other\n * targets) are similarly reserved for adapter / target use.\n *\n * `applicableTo` declares which operation kinds the annotation may attach\n * to. The lane terminals' type-level `ValidAnnotations<K, As>` gate rejects\n * annotations whose `Kinds` does not include the terminal's `K`; the\n * runtime helper `assertAnnotationsApplicable` does the equivalent at\n * runtime so casts and `any` cannot bypass the gate.\n */\nexport interface DefineAnnotationOptions<Kinds extends OperationKind> {\n readonly namespace: string;\n readonly applicableTo: readonly Kinds[];\n}\n\n/**\n * Defines a typed annotation handle.\n *\n * Two-step call form. The first step takes the `Payload` type argument\n * (TypeScript cannot infer `Payload` from anything in the options, so it\n * must be supplied explicitly); the second step takes the runtime options\n * and infers `Kinds` from the `applicableTo` array via a `const` type\n * parameter, so the operation kinds appear exactly once at the call site.\n *\n * @example\n * ```typescript\n * // Read-only annotation. Lane terminals like `db.User.first(...)` accept\n * // it; `db.User.create(...)` rejects it at the type level.\n * const cacheAnnotation = defineAnnotation<{ ttl?: number; skip?: boolean }>()({\n * namespace: 'cache',\n * applicableTo: ['read'],\n * }); // Kinds inferred as 'read'\n *\n * // Write-only annotation. Mirror image.\n * const auditAnnotation = defineAnnotation<{ actor: string }>()({\n * namespace: 'audit',\n * applicableTo: ['write'],\n * }); // Kinds inferred as 'write'\n *\n * // Annotation applicable to both kinds (e.g. tracing).\n * const otelAnnotation = defineAnnotation<{ traceId: string }>()({\n * namespace: 'otel',\n * applicableTo: ['read', 'write'],\n * }); // Kinds inferred as 'read' | 'write'\n * ```\n *\n * **Reserved namespaces.** See `DefineAnnotationOptions.namespace` for the\n * list of framework-internal namespaces (`codecs`, target-specific keys).\n * `defineAnnotation` does not structurally prevent a user from naming a\n * reserved namespace, but the framework makes no compatibility guarantee\n * about handles that do.\n */\nexport function defineAnnotation<Payload>(): <const Kinds extends OperationKind>(\n options: DefineAnnotationOptions<Kinds>,\n) => AnnotationHandle<Payload, Kinds> {\n return <const Kinds extends OperationKind>(\n options: DefineAnnotationOptions<Kinds>,\n ): AnnotationHandle<Payload, Kinds> => {\n const namespace = options.namespace;\n const applicableTo: ReadonlySet<Kinds> = Object.freeze(new Set(options.applicableTo));\n\n function handle(value: Payload): AnnotationValue<Payload, Kinds> {\n return Object.freeze({\n __annotation: true as const,\n namespace,\n value,\n applicableTo,\n });\n }\n\n function read(plan: {\n readonly meta: { readonly annotations?: Record<string, unknown> };\n }): Payload | undefined {\n const stored = plan.meta.annotations?.[namespace];\n if (!isAnnotationValue(stored)) {\n return undefined;\n }\n if (stored.namespace !== namespace) {\n // Defensive: a different handle wrote under our namespace key.\n return undefined;\n }\n return stored.value as Payload;\n }\n\n return Object.freeze(\n Object.assign(handle, {\n namespace,\n applicableTo,\n read,\n }),\n );\n };\n}\n\n/**\n * Type-level applicability gate consumed by lane terminals.\n *\n * Maps a tuple of `AnnotationValue`s to a tuple where each element either\n * keeps its annotation type (when the annotation's declared `Kinds`\n * includes the terminal's operation kind `K`) or resolves to `never`\n * (when the kinds are incompatible). A `never` element makes the entire\n * tuple unassignable, surfacing the mismatch as a type error at the call\n * site of the terminal.\n *\n * The SQL DSL builders constrain their variadic `...annotations`\n * parameter via `As & ValidAnnotations<K, As>`. **The intersection is\n * load-bearing** — see the note below. The ORM terminals deliberately\n * sidestep this trick by taking one annotation per `meta.annotate(...)`\n * call (no variadic-tuple inference involved), so `ValidAnnotations` is\n * consumed only by the SQL DSL today.\n *\n * @example\n * ```typescript\n * class SelectQuery<Row> {\n * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n * ...annotations: As & ValidAnnotations<'read', As>\n * ): SelectQuery<Row>;\n * }\n *\n * class InsertQuery<Row> {\n * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n * ...annotations: As & ValidAnnotations<'write', As>\n * ): InsertQuery<Row>;\n * }\n *\n * db.users.select('id').annotate(cacheAnnotation({ ttl: 60 }));\n * // ✓ cacheAnnotation declares 'read'; SelectQuery.annotate requires 'read'.\n *\n * db.users.insert([{ name: 'Alice' }]).annotate(cacheAnnotation({ ttl: 60 }));\n * // ✗ cacheAnnotation declares 'read'; InsertQuery.annotate requires 'write'.\n * // Element resolves to `never` → tuple unassignable → type error.\n * ```\n *\n * **Why `As & ValidAnnotations<K, As>` and not `ValidAnnotations<K, As>`\n * alone.** TypeScript's variadic-tuple inference is too forgiving when\n * the parameter type refers to `As` only through `ValidAnnotations`: it\n * will pick an `As` that makes the call valid even when the gated tuple\n * would contain `never` for an inapplicable element. The intersection\n * pins `As` to the actual call-site tuple AND requires it to be\n * assignable to the gated form. A `never` element in the gated tuple\n * then collapses the corresponding intersection position to `never`,\n * and the inapplicable argument fails to assign — surfacing the mismatch\n * as a type error at the call site.\n *\n * The runtime helper `assertAnnotationsApplicable` covers the equivalent\n * check at runtime so casts and `any` cannot bypass this gate.\n */\nexport type ValidAnnotations<\n K extends OperationKind,\n As extends readonly AnnotationValue<unknown, OperationKind>[],\n> = {\n readonly [I in keyof As]: As[I] extends AnnotationValue<infer P, infer Kinds>\n ? K extends Kinds\n ? AnnotationValue<P, Kinds>\n : never\n : never;\n};\n\n/**\n * Runtime applicability gate. Throws `RUNTIME.ANNOTATION_INAPPLICABLE` if\n * any annotation in `annotations` declares an `applicableTo` set that does\n * not include `kind`. Used by lane terminals (SQL DSL builders' `.build()`,\n * ORM `Collection` terminals) to fail closed when the type-level\n * `ValidAnnotations` gate is bypassed via cast / `any` / dynamic\n * invocation.\n *\n * Passes silently on:\n * - empty arrays\n * - annotations whose `applicableTo` includes `kind`\n *\n * Throws on:\n * - any annotation whose `applicableTo` does not include `kind`. The\n * error names the offending annotation's `namespace` and the\n * `terminalName` so users can locate the misuse.\n *\n * @example\n * ```typescript\n * // Inside an ORM read terminal:\n * assertAnnotationsApplicable(annotations, 'read', 'first');\n * ```\n */\nexport function assertAnnotationsApplicable(\n annotations: readonly AnnotationValue<unknown, OperationKind>[],\n kind: OperationKind,\n terminalName: string,\n): void {\n for (const annotation of annotations) {\n if (!annotation.applicableTo.has(kind)) {\n throw runtimeError(\n 'RUNTIME.ANNOTATION_INAPPLICABLE',\n `Annotation '${annotation.namespace}' is not applicable to '${kind}' operations (terminal: '${terminalName}'). The annotation declares applicableTo = [${Array.from(\n annotation.applicableTo,\n )\n .map((k) => `'${k}'`)\n .join(', ')}].`,\n {\n namespace: annotation.namespace,\n terminalName,\n kind,\n applicableTo: Array.from(annotation.applicableTo),\n },\n );\n }\n }\n}\n\n/**\n * Type guard for branded annotation values stored in `plan.meta.annotations`.\n *\n * Internal — used by `AnnotationHandle.read` to distinguish user\n * annotations (created by calling a handle returned from\n * `defineAnnotation(...)`) from framework-internal metadata that may\n * happen to live under the same namespace key.\n */\nfunction isAnnotationValue(value: unknown): value is AnnotationValue<unknown, OperationKind> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const candidate = value as { readonly __annotation?: unknown };\n return candidate.__annotation === true;\n}\n","import { runtimeError } from './runtime-error';\n\nexport class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {\n private readonly generator: AsyncGenerator<Row, void, unknown>;\n private consumed = false;\n private consumedBy: 'bufferedArray' | 'iterator' | undefined;\n private bufferedArrayPromise: Promise<Row[]> | undefined;\n\n constructor(generator: AsyncGenerator<Row, void, unknown>) {\n this.generator = generator;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Row> {\n if (this.consumed) {\n throw runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === 'bufferedArray' ? 'toArray()/then()' : 'for-await loop'}. Each AsyncIterableResult can only be iterated once.`,\n {\n consumedBy: this.consumedBy,\n suggestion:\n this.consumedBy === 'bufferedArray'\n ? 'If you need to iterate multiple times, store the results from toArray() in a variable and reuse that.'\n : 'If you need to iterate multiple times, use toArray() to collect all results first.',\n },\n );\n }\n this.consumed = true;\n this.consumedBy = 'iterator';\n return this.generator;\n }\n\n toArray(): Promise<Row[]> {\n if (this.consumedBy === 'iterator') {\n return Promise.reject(\n runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n 'AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.',\n {\n consumedBy: this.consumedBy,\n suggestion:\n 'The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating.',\n },\n ),\n );\n }\n\n if (this.bufferedArrayPromise) {\n return this.bufferedArrayPromise;\n }\n\n this.consumed = true;\n this.consumedBy = 'bufferedArray';\n this.bufferedArrayPromise = (async () => {\n const out: Row[] = [];\n for await (const item of this.generator) {\n out.push(item);\n }\n return out;\n })();\n return this.bufferedArrayPromise;\n }\n\n async first(): Promise<Row | null> {\n const rows = await this.toArray();\n return rows[0] ?? null;\n }\n\n async firstOrThrow(): Promise<Row> {\n const row = await this.first();\n if (row === null)\n throw runtimeError(\n 'RUNTIME.NO_ROWS',\n 'Expected at least one row, but none were returned',\n {},\n );\n return row;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: PromiseLike implementation is intentional for await support.\n then<TResult1 = Row[], TResult2 = never>(\n onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.toArray().then(onfulfilled, onrejected);\n }\n}\n","import type { RuntimeAbortedPhase } from './runtime-error';\nimport { runtimeAborted } from './runtime-error';\n\n/**\n * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied\n * context is already aborted at the precheck site. Centralises the\n * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that\n * every codec dispatch site (and the `beforeExecute` middleware phase)\n * repeats. Accepts both the framework `CodecCallContext` and the\n * `RuntimeMiddlewareContext`; both expose `signal?: AbortSignal`.\n */\nexport function checkAborted(\n ctx: { readonly signal?: AbortSignal },\n phase: RuntimeAbortedPhase,\n): void {\n if (ctx.signal?.aborted) {\n throw runtimeAborted(phase, ctx.signal.reason);\n }\n}\n\n/**\n * Race a per-cell `Promise.all` (or any other in-flight work promise) against\n * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly\n * even when codec bodies ignore the signal. In-flight bodies that ignore the\n * signal are abandoned and run to completion in the background — the\n * cooperative-cancellation contract documented in ADR 204.\n *\n * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with\n * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —\n * that path is the canonical \"aborted at entry\" surface and avoids\n * scheduling the work promise. As a defensive belt-and-braces, this helper\n * also handles the already-aborted case internally: `AbortSignal` does not\n * replay past abort events to listeners registered after the abort, so we\n * inspect `signal.aborted` synchronously and reject with the sentinel\n * before installing the listener. The rejection is still attributed to the\n * abort path via the sentinel-identity check.\n *\n * Distinguishing the rejection source is load-bearing for AC-ERR4\n * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).\n * The semantically equivalent `abortable(signal)` helper in\n * `@prisma-next/utils` rejects with `signal.reason ?? new DOMException(...)`,\n * which is not stably distinguishable from a codec-thrown error by identity\n * alone (a fresh fallback DOMException is allocated per call). We instead\n * track abort attribution with a unique sentinel: only the `onAbort` listener\n * installed here ever rejects with the sentinel, so an `error === sentinel`\n * identity check after the race is unambiguous.\n *\n * Lives in `framework-components` (rather than the SQL family, where it\n * originated in m2) so every family runtime that needs cooperative\n * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode\n * today, Mongo encode in m3) shares the same attribution logic.\n */\nexport async function raceAgainstAbort<T>(\n work: Promise<T>,\n signal: AbortSignal | undefined,\n phase: RuntimeAbortedPhase,\n): Promise<T> {\n if (signal === undefined) {\n return await work;\n }\n const sentinel: { reason: unknown } = { reason: undefined };\n let onAbort: (() => void) | undefined;\n\n const abortPromise = new Promise<never>((_, reject) => {\n if (signal.aborted) {\n sentinel.reason = signal.reason;\n reject(sentinel);\n return;\n }\n onAbort = () => {\n sentinel.reason = signal.reason;\n reject(sentinel);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n try {\n return await Promise.race([work, abortPromise]);\n } catch (error) {\n if (error === sentinel) {\n throw runtimeAborted(phase, sentinel.reason);\n }\n throw error;\n } finally {\n if (onAbort) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n}\n","import type { ExecutionPlan } from './query-plan';\nimport { checkAborted, raceAgainstAbort } from './race-against-abort';\nimport type {\n ParamRefMutator,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Runs every middleware's `beforeExecute` hook in registration order,\n * threading through the (optional) family-specific `paramsMutator`.\n *\n * Why this lives outside {@link runWithMiddleware}: middleware that\n * mutates parameter values (e.g. cipherstash's bulk-encrypt SDK\n * round-trip) must run *before* the family runtime encodes those\n * parameters to driver wire format. Family runtimes call\n * `runBeforeExecuteChain` between the AST → plan lowering step and\n * the parameter encode step; the encode then observes the mutator's\n * `currentParams()` view. `runWithMiddleware` retains the rest of\n * the lifecycle (`intercept`, driver/row source loop, `onRow`,\n * `afterExecute`) but no longer fires `beforeExecute` itself.\n *\n * Lifecycle within this helper:\n *\n * 1. For each middleware in registration order, if `beforeExecute`\n * is implemented:\n * - `checkAborted(ctx, 'beforeExecute')` short-circuits if the\n * caller already aborted at entry.\n * - The hook is invoked with `(plan, ctx, paramsMutator)`. A\n * middleware body that ignores the mutator stays compatible —\n * JavaScript allows extra positional arguments.\n * - If the hook returns a Promise, it is raced against\n * `ctx.signal` via {@link raceAgainstAbort} so cooperative\n * cancellation surfaces a `RUNTIME.ABORTED { phase:\n * 'beforeExecute' }` envelope even when the body itself\n * ignores the signal.\n *\n * Error propagation: any error thrown by a `beforeExecute` body\n * (or surfaced by the abort race) propagates out of this helper\n * unchanged. The family runtime is responsible for converting it\n * into the appropriate `afterExecute(completed: false)` notification\n * once `runWithMiddleware` runs.\n *\n * Relationship to {@link runWithMiddleware}: the framework's\n * `RuntimeCore.execute` template calls this helper between\n * `lower(plan)` and `runWithMiddleware(...)`. Family runtimes that\n * override `execute` (e.g. SQL, which inlines lower + encode for\n * direct mutator threading) call this helper themselves at the\n * equivalent point — between the family's AST → draft-plan\n * lowering and the parameter-encode step.\n *\n * Intercept ordering: this helper fires unconditionally before\n * `runWithMiddleware`. `intercept` (inside `runWithMiddleware`)\n * therefore observes the post-`beforeExecute` plan — mutator\n * mutations are visible in the params interceptors see. The\n * trade-off is documented on `RuntimeMiddleware.intercept`.\n */\nexport async function runBeforeExecuteChain<\n TExec extends ExecutionPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n>(\n plan: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec, TMutator>>,\n ctx: RuntimeMiddlewareContext,\n paramsMutator?: TMutator,\n): Promise<void> {\n for (const mw of middleware) {\n if (!mw.beforeExecute) {\n continue;\n }\n checkAborted(ctx, 'beforeExecute');\n const work = mw.beforeExecute(plan, ctx, paramsMutator as TMutator);\n if (work !== undefined) {\n await raceAgainstAbort(Promise.resolve(work), ctx.signal, 'beforeExecute');\n }\n }\n}\n","import { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan } from './query-plan';\nimport type { RuntimeMiddleware, RuntimeMiddlewareContext } from './runtime-middleware';\n\n/**\n * Drives a single execution of `runDriver()` through the middleware\n * lifecycle's intercept + row-source + termination phases.\n *\n * Lifecycle, in order:\n * 1. For each middleware in registration order: `intercept(exec, ctx)`. The\n * first non-`undefined` result wins; subsequent middleware's `intercept`\n * does not fire. On a hit, the runtime emits a `middleware.intercept`\n * debug event naming the winning middleware, switches the row source to\n * the intercepted rows, and proceeds with `source: 'middleware'`. On\n * all-passthrough (every `intercept` returns `undefined` or is omitted),\n * `source: 'driver'` is used and the row source is `runDriver()`.\n * 2. Iterate the row source. On the driver path, for each row, for each\n * middleware in registration order: `onRow(row, exec, ctx)`; then yield\n * the row. On the intercepted hit path, `onRow` is skipped — intercepted\n * rows did not originate from a driver row stream — but rows are still\n * yielded to the consumer in order.\n * 3. On successful completion: for each middleware in registration order:\n * `afterExecute(exec, { rowCount, latencyMs, completed: true, source },\n * ctx)`.\n * 4. On any error thrown during steps 1–2: for each middleware in\n * registration order: `afterExecute(exec, { rowCount, latencyMs,\n * completed: false, source }, ctx)`. Errors thrown by `afterExecute`\n * during the error path are swallowed so they do not mask the original\n * error. The original error is then rethrown.\n *\n * `beforeExecute` is **not** fired here — see\n * {@link runBeforeExecuteChain} in `before-execute-chain.ts`. Family\n * runtimes call that helper between the AST → plan lowering step and\n * the parameter encode step so middleware that mutates ParamRef\n * values (e.g. cipherstash bulk-encrypt) can have its mutations\n * visible to encode. `runWithMiddleware` operates on the fully-\n * encoded plan; interceptors therefore observe a fully-mutated,\n * encoded plan.\n *\n * The `source` field on `AfterExecuteResult` lets observers (telemetry,\n * lints, budgets) distinguish driver-served from middleware-served\n * executions without needing their own out-of-band signal.\n *\n * This helper is the single canonical implementation of the\n * intercept-and-row-source loop; family runtimes should not\n * reimplement it.\n */\nexport function runWithMiddleware<TExec extends ExecutionPlan, Row>(\n exec: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec>>,\n ctx: RuntimeMiddlewareContext,\n runDriver: () => AsyncIterable<Row>,\n): AsyncIterableResult<Row> {\n const iterator = async function* (): AsyncGenerator<Row, void, unknown> {\n const startedAt = Date.now();\n let rowCount = 0;\n let completed = false;\n let source: 'driver' | 'middleware' = 'driver';\n // Deferred so a winning interceptor can skip `runDriver()` entirely.\n // For factories that lazily produce async generators this is a no-op,\n // but factories that do eager work (e.g. acquiring a connection,\n // sending a query) must not run on the intercepted hit path.\n let rowSource: AsyncIterable<Row> | Iterable<Row> | undefined;\n\n try {\n for (const mw of middleware) {\n if (!mw.intercept) {\n continue;\n }\n // Mark the lifecycle as middleware-driven *before* awaiting the\n // hook. If `intercept` throws, the catch block reports the failure\n // as `source: 'middleware'` — the failure originated in the\n // intercept chain, not in the driver. If `intercept` returns\n // `undefined` (passthrough), we revert to `'driver'` and continue.\n source = 'middleware';\n const result = await mw.intercept(exec, ctx);\n if (result === undefined) {\n source = 'driver';\n continue;\n }\n ctx.log.debug?.({ event: 'middleware.intercept', middleware: mw.name });\n // The intercepted rows are typed as `Record<string, unknown>` at\n // the SPI level; the consumer's `Row` type parameter is enforced by\n // the caller (via the plan's phantom `_row`) the same way driver\n // rows are. Cast through unknown to bridge the SPI shape to the\n // caller-supplied Row.\n rowSource = result.rows as unknown as AsyncIterable<Row> | Iterable<Row>;\n break;\n }\n\n if (source === 'driver') {\n rowSource = runDriver();\n }\n\n // `rowSource` is always assigned by this point: either the intercepted\n // rows (on a hit) or `runDriver()` (on the driver path).\n for await (const row of rowSource as AsyncIterable<Row> | Iterable<Row>) {\n if (source === 'driver') {\n for (const mw of middleware) {\n if (mw.onRow) {\n await mw.onRow(row as Record<string, unknown>, exec, ctx);\n }\n }\n }\n rowCount++;\n yield row;\n }\n\n completed = true;\n } catch (error) {\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n try {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n } catch {\n // Swallow afterExecute errors during the error path so they do not\n // mask the original error.\n }\n }\n }\n\n throw error;\n }\n\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n }\n }\n };\n\n return new AsyncIterableResult(iterator());\n}\n","import type { CodecCallContext } from '../shared/codec-types';\nimport { AsyncIterableResult } from './async-iterable-result';\nimport { runBeforeExecuteChain } from './before-execute-chain';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { checkAborted } from './race-against-abort';\nimport { runWithMiddleware } from './run-with-middleware';\nimport type {\n RuntimeExecuteOptions,\n RuntimeExecutor,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Constructor options shared by every concrete `RuntimeCore` subclass.\n *\n * Family runtimes typically build the middleware list and the\n * `RuntimeMiddlewareContext` themselves (running compatibility checks,\n * narrowing the context's `contract` field, etc.) before calling `super`.\n */\nexport interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {\n readonly middleware: ReadonlyArray<TMiddleware>;\n readonly ctx: RuntimeMiddlewareContext;\n}\n\n/**\n * Family-agnostic abstract runtime base.\n *\n * Defines the entire `execute(plan)` template in one place:\n *\n * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides\n * this to run its `beforeCompile` middleware-hook chain.\n * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`\n * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).\n * 3. `runBeforeExecuteChain(exec, this.middleware, this.ctx)` — concrete;\n * runs every middleware's `beforeExecute` hook after lowering but\n * before the row source is opened. Family runtimes that need a\n * params mutator visible to a downstream encode step (SQL) override\n * `execute` and call this helper themselves at the equivalent\n * pre-encode point.\n * 4. `runWithMiddleware(exec, this.middleware, this.ctx,\n * () => runDriver(exec))` — concrete; runs the intercept chain,\n * drives the row source, fires `onRow` / `afterExecute`. Does\n * **not** fire `beforeExecute` — see step 3.\n *\n * Concrete subclasses must implement `lower`, `runDriver`, and `close`.\n *\n * The class is generic over:\n * - `TPlan` — the family's pre-lowering plan type.\n * - `TExec` — the family's post-lowering (executable) plan type.\n * - `TMiddleware` — the family's middleware type. Constrained to\n * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the\n * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered\n * `TExec`. (The spec/plan wording \"RuntimeMiddleware<TPlan>\" is\n * tightened to `<TExec>` here so the helper call typechecks; the\n * intent is unchanged — middleware sees the post-lowering plan.)\n */\nexport abstract class RuntimeCore<\n TPlan extends QueryPlan,\n TExec extends ExecutionPlan,\n TMiddleware extends RuntimeMiddleware<TExec>,\n> implements RuntimeExecutor<TPlan>\n{\n protected readonly middleware: ReadonlyArray<TMiddleware>;\n protected readonly ctx: RuntimeMiddlewareContext;\n\n constructor(options: RuntimeCoreOptions<TMiddleware>) {\n this.middleware = options.middleware;\n this.ctx = options.ctx;\n }\n\n /**\n * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses\n * may override to run a `beforeCompile` middleware chain (SQL does this\n * to support typed AST rewrites — see `before-compile-chain.ts`).\n */\n protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan> {\n return plan;\n }\n\n /**\n * Lower a pre-lowering `TPlan` into the family's executable `TExec`.\n * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo\n * produces `{ command, ... }`.\n *\n * `ctx` carries per-query cancellation (and any future fields on\n * `CodecCallContext`); concrete subclasses forward it to the\n * encode-side codec dispatch site (e.g. SQL's `encodeParams` in m2,\n * Mongo's `resolveValue` in m3). The runtime allocates one ctx per\n * `execute()` call and threads the same reference everywhere; the\n * `signal` field inside may be `undefined`, but the ctx object itself\n * is always present.\n */\n protected abstract lower(plan: TPlan, ctx: CodecCallContext): TExec | Promise<TExec>;\n\n /**\n * Drive the underlying transport for a lowered `TExec`. Yields raw rows\n * directly from the driver as `Record<string, unknown>`; codec decoding\n * (if any) is the subclass's responsibility, applied by wrapping\n * `execute()` rather than living inside this hook.\n *\n * The `Row` type parameter on `execute()` is satisfied by the caller via\n * the plan's phantom `_row`; the runtime treats rows as opaque records\n * here and trusts the caller's row typing.\n */\n protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;\n\n abstract close(): Promise<void>;\n\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call. The ctx object is always allocated; the\n // `signal` field is only included when a signal was supplied (required\n // under exactOptionalPropertyTypes — `{ signal: undefined }` would not\n // satisfy `signal?: AbortSignal`).\n const codecCtx: CodecCallContext = signal === undefined ? {} : { signal };\n\n async function* generator(): AsyncGenerator<Row, void, unknown> {\n // Pre-check the signal at entry so an already-aborted caller observes\n // RUNTIME.ABORTED on the first `next()` without any work being done.\n checkAborted(codecCtx, 'stream');\n\n const compiled = await self.runBeforeCompile(plan);\n const exec = await self.lower(compiled, codecCtx);\n // Fire the framework-level `beforeExecute` chain on the lowered\n // plan before opening the row source. Families that need\n // pre-encode mutator visibility (SQL) override `execute` to\n // inject the same chain at the equivalent point.\n await runBeforeExecuteChain<TExec>(exec, self.middleware, self.ctx);\n // The driver yields raw `Record<string, unknown>`; we cast to `Row` here.\n // The Row contract is enforced by the caller via `plan._row`.\n yield* runWithMiddleware<TExec, Row>(\n exec,\n self.middleware,\n self.ctx,\n () => self.runDriver(exec) as AsyncIterable<Row>,\n );\n }\n\n return new AsyncIterableResult(generator());\n }\n}\n","import type { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { runtimeError } from './runtime-error';\n\nexport interface RuntimeLog {\n info(event: unknown): void;\n warn(event: unknown): void;\n error(event: unknown): void;\n debug?(event: unknown): void;\n}\n\n/**\n * Per-execute context threaded through every middleware phase\n * (`beforeExecute`, `onRow`, `afterExecute`). Allocated once per\n * `runtime.execute()` call and shared by reference across all\n * middleware in the chain.\n *\n * - `signal` carries the per-query `AbortSignal` -- the same\n * reference that `runtime.execute(plan, { signal })` was invoked\n * with, and the same reference threaded into the per-call\n * `CodecCallContext` (ADR 207). Middleware that wraps a\n * network-backed SDK forwards `ctx.signal` into that SDK to\n * propagate caller cancellation; pure-CPU middleware ignores it.\n *\n * Symmetric plumbing across all middleware phases (rather than only\n * `beforeExecute`) is a deliberate choice: a middleware that wraps a\n * downstream observability hook or post-processor in `afterExecute` /\n * `onRow` needs the same cancellation reach as its `beforeExecute`\n * counterpart.\n */\nexport interface RuntimeMiddlewareContext {\n readonly contract: unknown;\n readonly mode: 'strict' | 'permissive';\n readonly now: () => number;\n readonly log: RuntimeLog;\n /**\n * Returns a stable string identifying the (storage, statement, params)\n * tuple of an execution. Two semantically equivalent executions return\n * the same string. Used by middleware that need per-execution identity\n * (caching, request coalescing).\n *\n * The family runtime owns the implementation:\n * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`\n * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`\n *\n * The method is `async` because the underlying digest helper\n * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`\n * primitive is asynchronous by design.\n *\n * The returned string is intended to be consumed directly as a `Map` key\n * — it is not (and should not be) further hashed by callers.\n */\n contentHash(exec: ExecutionPlan): Promise<string>;\n /**\n * Per-execute cancellation signal threaded through every middleware\n * phase. Middleware that wraps async work or downstream cancellable\n * primitives should observe this and abort early when the consumer\n * cancels.\n */\n readonly signal?: AbortSignal;\n /**\n * Identifies the queryable scope this execution is running under.\n *\n * - `'runtime'` — top-level `runtime.execute(plan)`. The default scope\n * used by the standard read/write paths.\n * - `'connection'` — `connection.execute(plan)` after\n * `runtime.connection()` checked out a connection from the pool.\n * - `'transaction'` — `transaction.execute(plan)` inside an explicit\n * transaction, or a query routed through `withTransaction`.\n *\n * Middleware that should only act at the top level read this field to\n * bypass non-runtime scopes. The cache middleware uses it to skip\n * caching inside transactions (where read-after-write coherence is the\n * caller's expectation) and dedicated connections (where the user has\n * explicitly stepped outside the shared cache surface). Observers that\n * don't care about the scope can ignore the field.\n *\n * Family runtimes populate this at context-construction time per\n * scope. Existing middleware that ignore the field are unaffected.\n */\n readonly scope: 'runtime' | 'connection' | 'transaction';\n}\n\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\n /**\n * Indicates where the rows observed during this execution came from.\n *\n * - `'driver'` — the default. Rows came from the underlying driver via\n * `runDriver` / `runWithMiddleware`'s normal path.\n * - `'middleware'` — a `RuntimeMiddleware.intercept` hook short-circuited\n * execution and supplied the rows directly. The driver was not invoked.\n *\n * Observers (telemetry, lints, budgets) that need to distinguish between\n * driver-served and middleware-served executions read this field.\n * Observers that don't care can ignore it.\n */\n readonly source: 'driver' | 'middleware';\n}\n\n/**\n * Result of a successful `RuntimeMiddleware.intercept` hook.\n *\n * Carries the rows that the middleware wishes to return in place of\n * invoking the driver. The runtime iterates `rows` in order and yields\n * each row to the consumer; `beforeExecute`, `runDriver`, and `onRow` are\n * all skipped on the hit path. `afterExecute` still fires with\n * `source: 'middleware'`.\n *\n * `rows` accepts both `Iterable` (arrays, sync generators) and\n * `AsyncIterable` (async generators). `for await` natively handles both\n * via `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the\n * orchestrator does not need to branch on the variant. Cached arrays in\n * the cache middleware are the common case; streaming variants support\n * future use cases like mock layers replaying recordings.\n *\n * Row shape is `Record<string, unknown>` — the same untyped shape\n * `onRow` receives. The SQL runtime decodes intercepted rows through its\n * normal codec pass, so interceptors cache and return raw (undecoded)\n * rows.\n */\nexport interface InterceptResult {\n readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;\n}\n\n/**\n * Marker interface for family-specific param-ref mutators threaded into\n * `beforeExecute` as the third argument. The framework treats the mutator\n * opaquely — it allocates and forwards the family's mutator instance so\n * `runWithMiddleware` can stay family-agnostic. SQL extends this with\n * `SqlParamRefMutator` (over `ParamRef`); Mongo extends with\n * `MongoParamRefMutator` (over `MongoParamRef`).\n *\n * Extension authors target the family-specific mutator type, not this\n * marker.\n */\ndeclare const PARAM_REF_MUTATOR_BRAND: unique symbol;\nexport type ParamRefMutator = { readonly [PARAM_REF_MUTATOR_BRAND]?: never };\n\n/**\n * Family-agnostic middleware SPI parameterized over the plan marker.\n *\n * `TPlan` defaults to the framework `QueryPlan` marker so a generic\n * middleware (e.g. cross-family telemetry) can be authored without\n * naming a family. Family-specific middleware (`SqlMiddleware`,\n * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.\n *\n * `TMutator` is the family-specific {@link ParamRefMutator} the runtime\n * threads into `beforeExecute(plan, ctx, params)` as a third argument.\n * Existing `(plan)` / `(plan, ctx)` middleware bodies continue to compile\n * — TypeScript permits assigning a function with fewer parameters to a\n * function-typed slot that declares more. The third arg is additive.\n */\nexport interface RuntimeMiddleware<\n TPlan extends QueryPlan = QueryPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n> {\n readonly name: string;\n readonly familyId?: string;\n readonly targetId?: string;\n /**\n * Optional short-circuit hook. Runs inside `runWithMiddleware`, after\n * the orchestrator receives the lowered plan and before any\n * `beforeExecute` hook fires. Middleware run in registration order; the\n * first to return a non-`undefined` `InterceptResult` wins, and\n * subsequent middleware's `intercept` does not fire.\n *\n * On a hit, `beforeExecute`, `runDriver`, and `onRow` are all skipped.\n * `afterExecute` still fires with `source: 'middleware'`.\n *\n * Returning `undefined` (or omitting the hook entirely) signals\n * passthrough — execution proceeds through the normal driver path.\n *\n * Errors thrown inside `intercept` are rethrown by `runWithMiddleware`\n * as the original `Error` — no envelope is guaranteed at this layer.\n * Before rethrowing, `afterExecute` fires with `completed: false` and\n * `source: 'middleware'`. Errors thrown by `afterExecute` during the\n * error path remain swallowed (existing semantics, unchanged).\n *\n * Used by middleware that need to short-circuit execution and supply\n * rows directly: caching, mocks, rate limiting, circuit breaking.\n */\n intercept?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<InterceptResult | undefined>;\n /**\n * Fires after the family runtime has produced a draft execution\n * plan from the AST, but before the family encodes parameter values\n * to driver wire format. Mutations applied via the\n * family-specific `params` mutator are visible to the subsequent\n * encode step.\n *\n * Lifecycle position (SQL example):\n * `runBeforeCompile → lowerSqlPlan → beforeExecute → encodeParams → intercept → driver`.\n *\n * The `params` argument is a family-specific {@link ParamRefMutator}\n * scoped to the value slots of `ParamRef` nodes in the plan's AST.\n * Middleware that doesn't need to mutate params can ignore the\n * argument; existing `(plan)` / `(plan, ctx)` bodies stay compatible.\n *\n * `ctx.signal` carries the per-query `AbortSignal`; middleware that\n * wraps a network SDK forwards it. Cooperative cancellation\n * surfaces a `RUNTIME.ABORTED { phase: 'beforeExecute' }` envelope\n * promptly even when the body ignores the signal.\n *\n * Intercept ordering: `intercept` runs *after* this hook; an\n * interceptor that short-circuits the driver path still observes\n * the post-`beforeExecute`, fully-encoded plan. The trade-off is\n * that any `beforeExecute` SDK round-trips happen even when a\n * downstream interceptor would have skipped the driver entirely.\n */\n beforeExecute?(\n plan: TPlan,\n ctx: RuntimeMiddlewareContext,\n params?: TMutator,\n ): void | Promise<void>;\n onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;\n afterExecute?(\n plan: TPlan,\n result: AfterExecuteResult,\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n}\n\n/**\n * Cross-family middleware — one that doesn't constrain `familyId` or\n * `targetId` and is therefore compatible with any family runtime's\n * middleware array (`SqlMiddleware[]`, `MongoMiddleware[]`, etc.).\n *\n * The intersection `RuntimeMiddleware & { familyId?: undefined; targetId?: undefined }`\n * pins both optional properties to exactly `undefined` (intersecting\n * `string | undefined` with `undefined` collapses to `undefined`). Under\n * `exactOptionalPropertyTypes: true`, the plain `RuntimeMiddleware` shape\n * — with `familyId?: string` — is *not* assignable to `SqlMiddleware`\n * (which narrows `familyId?: 'sql'`) because `string` is wider than\n * `'sql'`. Pinning the property to `undefined` makes the value a subtype\n * of every narrowed variant: `undefined` extends both `'sql' | undefined`\n * and `'mongo' | undefined`, so a `CrossFamilyMiddleware` value drops\n * into a SQL or Mongo middleware slot without a cast.\n *\n * Cross-family middleware factories (`createCacheMiddleware`, future\n * `audit` / OTel middleware) declare this as their return type so the\n * cross-family typing is named once rather than re-spelled at every call\n * site.\n */\nexport type CrossFamilyMiddleware<TPlan extends QueryPlan = QueryPlan> =\n RuntimeMiddleware<TPlan> & {\n readonly familyId?: undefined;\n readonly targetId?: undefined;\n };\n\n/**\n * Optional per-`execute` options accepted by every family runtime.\n *\n * `signal` is the per-query cancellation signal. The runtime threads the\n * signal through to every codec call for the query and uses it to short-\n * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.\n * Omitting the option (or passing `undefined`) preserves today's behavior\n * bit-for-bit.\n */\nexport interface RuntimeExecuteOptions {\n readonly signal?: AbortSignal;\n readonly scope?: 'runtime' | 'connection' | 'transaction';\n}\n\n/**\n * Cross-family SPI for any runtime that can execute plans and be shut down.\n * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,\n * Mongo structurally (due to its phantom Row parameter using a unique symbol).\n *\n * The `_row` intersection on `execute` connects the `Row` type parameter to the\n * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.\n */\nexport interface RuntimeExecutor<TPlan extends QueryPlan> {\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nexport function checkMiddlewareCompatibility(\n middleware: RuntimeMiddleware,\n runtimeFamilyId: string,\n runtimeTargetId: string,\n): void {\n if (middleware.targetId !== undefined && middleware.familyId === undefined) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',\n `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,\n { middleware: middleware.name, targetId: middleware.targetId },\n );\n }\n\n if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',\n `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,\n { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },\n );\n }\n\n if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',\n `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,\n { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },\n );\n }\n}\n","import {\n type AnnotationValue,\n assertAnnotationsApplicable,\n type OperationKind,\n} from './annotations';\n\n/**\n * Per-terminal meta configurator handed to user callbacks. The terminal's\n * operation kind `K` is fixed by the terminal that constructed the builder;\n * `annotate(...)` accepts only annotations whose declared `Kinds` include\n * `K`.\n *\n * The conditional parameter type\n * `K extends Kinds ? AnnotationValue<P, Kinds> : never` collapses to `never`\n * for inapplicable annotations, surfacing the mismatch as a type error at\n * the call site of `meta.annotate(...)`. No variadic-tuple inference is\n * involved — TypeScript infers `Kinds` from the annotation argument and\n * checks the conditional directly.\n *\n * The runtime gate inside `annotate` (via\n * `assertAnnotationsApplicable`) catches cast / `any` / dynamic bypasses\n * and throws `RUNTIME.ANNOTATION_INAPPLICABLE`.\n *\n * `annotate` returns the builder for chaining; the return value of the\n * configurator callback is unused, so both block-body and expression-body\n * callbacks compile.\n *\n * @example\n * ```typescript\n * await db.User.find({ id }, (meta) => meta.annotate(cacheAnnotation({ ttl: 60 })));\n * await db.User.create(input, (meta) => {\n * meta.annotate(auditAnnotation({ actor: 'system' }));\n * meta.annotate(otelAnnotation({ traceId }));\n * });\n * ```\n */\nexport interface MetaBuilder<K extends OperationKind> {\n annotate<P, Kinds extends OperationKind>(\n annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never,\n ): this;\n}\n\n/**\n * Lane-side view of a meta builder. Extends the public `MetaBuilder<K>`\n * surface with `annotations` so lane terminals can read the recorded map\n * after invoking the user configurator.\n *\n * Lane terminals construct one of these via `createMetaBuilder(kind, terminalName)`,\n * pass it to the user callback as `MetaBuilder<K>` (the narrower public\n * view), then read `meta.annotations` to thread the recorded values into\n * `plan.meta.annotations`.\n */\nexport interface LaneMetaBuilder<K extends OperationKind> extends MetaBuilder<K> {\n readonly annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n}\n\nclass MetaBuilderImpl<K extends OperationKind> implements LaneMetaBuilder<K> {\n readonly #kind: K;\n readonly #terminalName: string;\n readonly #annotations = new Map<string, AnnotationValue<unknown, OperationKind>>();\n\n constructor(kind: K, terminalName: string) {\n this.#kind = kind;\n this.#terminalName = terminalName;\n }\n\n get annotations(): ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> {\n return this.#annotations;\n }\n\n annotate<P, Kinds extends OperationKind>(\n annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never,\n ): this {\n // Inside the body, the conditional `K extends Kinds ? AnnotationValue<P, Kinds> : never`\n // is opaque to TypeScript — it can't pick a branch without a concrete\n // K. Widen to the structural shape so we can call into the runtime\n // gate. The runtime gate (assertAnnotationsApplicable) is what\n // catches cast bypasses where the conditional would have resolved to\n // `never` had the type checker been allowed to specialise.\n const value = annotation as AnnotationValue<unknown, OperationKind>;\n assertAnnotationsApplicable([value], this.#kind, this.#terminalName);\n this.#annotations.set(value.namespace, value);\n return this;\n }\n}\n\n/**\n * Construct a lane-side meta builder for a terminal of operation kind `K`.\n *\n * Lane terminals call this with their `kind` (`'read'` or `'write'`) and a\n * `terminalName` for error messages, hand the resulting builder to the\n * user-supplied configurator callback (typed as `MetaBuilder<K>`, the\n * narrower public view), and read `meta.annotations` afterwards to thread\n * the recorded values into `plan.meta.annotations`.\n */\nexport function createMetaBuilder<K extends OperationKind>(\n kind: K,\n terminalName: string,\n): LaneMetaBuilder<K> {\n return new MetaBuilderImpl(kind, terminalName);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAa,kBAAkB;;;;;;;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AAM,QAAQ;EACd,4BAA4B,CAAC,MAAM,EAAE,KAAKF,OAAO,KAAKC,cAAc;EACpE,KAAKC,aAAa,IAAI,MAAM,WAAW,MAAM;EAC7C,OAAO;;;;;;;;;;;;AAaX,SAAgB,kBACd,MACA,cACoB;CACpB,OAAO,IAAI,gBAAgB,MAAM,aAAa"}
1
+ {"version":3,"file":"runtime.mjs","names":["candidate","#kind","#terminalName","#annotations"],"sources":["../src/execution/runtime-error.ts","../src/annotations.ts","../src/execution/async-iterable-result.ts","../src/execution/race-against-abort.ts","../src/execution/before-execute-chain.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts","../src/execution/runtime-middleware.ts","../src/meta-builder.ts"],"sourcesContent":["export interface RuntimeErrorEnvelope extends Error {\n readonly code: string;\n readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\n/**\n * Stable code emitted by the runtime when an in-flight `execute()`\n * is cancelled via the per-query `AbortSignal`. The envelope's\n * `details.phase` distinguishes where the abort was observed:\n *\n * - `'encode'` — abort fired during `encodeParams` (SQL) or\n * `resolveValue` (Mongo).\n * - `'decode'` — abort fired during `decodeRow` / `decodeField`.\n * - `'stream'` — abort fired between rows or before any codec call\n * (already-aborted at entry).\n * - `'beforeExecute'` / `'afterExecute'` / `'onRow'` — abort fired\n * on entry to or during the corresponding middleware phase\n * (cooperative cancellation per the param-transform seam).\n */\nexport const RUNTIME_ABORTED = 'RUNTIME.ABORTED' as const;\n\n/** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */\nexport type RuntimeAbortedPhase =\n | 'encode'\n | 'decode'\n | 'stream'\n | 'beforeExecute'\n | 'afterExecute'\n | 'onRow';\n\n/**\n * Type guard for the runtime-error envelope produced by `runtimeError`.\n *\n * Prefer this over duck-typing on `error.code` directly so consumers stay\n * insulated from the envelope's internal shape.\n */\nexport function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {\n return (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string' &&\n 'category' in error &&\n 'severity' in error\n );\n}\n\nexport function runtimeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): RuntimeErrorEnvelope {\n const error = new Error(message) as RuntimeErrorEnvelope;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n\n return Object.assign(error, {\n code,\n category: resolveCategory(code),\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction resolveCategory(code: string): RuntimeErrorEnvelope['category'] {\n const prefix = code.split('.')[0] ?? 'RUNTIME';\n switch (prefix) {\n case 'PLAN':\n case 'CONTRACT':\n case 'LINT':\n case 'BUDGET':\n return prefix;\n default:\n return 'RUNTIME';\n }\n}\n\n/**\n * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the\n * abort was observed — codec call sites (`encode` / `decode` / `stream`)\n * or middleware seams (`beforeExecute` / `afterExecute` / `onRow`), as\n * enumerated on {@link RuntimeAbortedPhase}. Cause carries\n * `signal.reason` verbatim from the platform — native abort produces a\n * `DOMException`, explicit `controller.abort(reason)` produces whatever\n * the caller passed. No synthesis happens here.\n */\nexport function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope {\n const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });\n return Object.assign(envelope, { cause });\n}\n","import { runtimeError } from './execution/runtime-error';\n\n/**\n * The kinds of operations an annotation may apply to.\n *\n * - `'read'` — `SELECT` / `find` / `first` / `all` / `count` / aggregates.\n * - `'write'` — `INSERT` / `UPDATE` / `DELETE` / `create` / `update` / `delete` / `upsert`.\n *\n * Annotations declare which kinds they apply to via `defineAnnotation`'s\n * `applicableTo` option; lane terminals enforce the constraint at both the\n * type level (via `ValidAnnotations`) and at runtime (via\n * `assertAnnotationsApplicable`).\n *\n * Finer-grained kinds (`'select' | 'insert' | 'update' | 'delete' | 'upsert'`)\n * are deliberately deferred. The binary covers the common case (the cache\n * middleware applies to reads; an audit annotation would apply to writes;\n * tracing/OTel applies to both). When a real annotation surfaces that needs\n * a finer split, the union widens and existing handles remain typecheckable.\n */\nexport type OperationKind = 'read' | 'write';\n\n/**\n * An applied annotation. Carries the namespace, the typed payload, and the\n * `applicableTo` set the underlying handle declared. The `__annotation`\n * brand lets `read` distinguish branded user annotations from arbitrary\n * data that may happen to live under the same namespace key in\n * `plan.meta.annotations` (e.g. framework-internal metadata such as\n * `meta.annotations.codecs`).\n *\n * Constructed by calling an `AnnotationHandle` directly (e.g.\n * `cacheAnnotation({ ttl: 60 })`); never instantiated by hand.\n */\nexport interface AnnotationValue<Payload, Kinds extends OperationKind> {\n readonly __annotation: true;\n readonly namespace: string;\n readonly value: Payload;\n readonly applicableTo: ReadonlySet<Kinds>;\n}\n\n/**\n * Handle returned by `defineAnnotation`. The handle is **callable**: the\n * call signature wraps a `Payload` into an `AnnotationValue` ready to\n * pass to a lane terminal's variadic `annotations` argument. The handle\n * also carries static metadata as own properties:\n *\n * - `namespace` — the namespace string the handle was declared with.\n * - `applicableTo` — the frozen `ReadonlySet<Kinds>` consumed by both\n * the type-level `ValidAnnotations` gate and the runtime\n * `assertAnnotationsApplicable` gate.\n * - `read(plan)` — extract the `Payload` from a plan's `meta.annotations`\n * if a value was previously written under this handle's namespace.\n * Returns `undefined` when the annotation is absent or when the stored\n * value is not a branded `AnnotationValue` (e.g. framework-internal\n * metadata under the same namespace key).\n *\n * Handles are the only supported public entry point for reading and\n * writing annotations. Direct mutation of `plan.meta.annotations` is not\n * part of the public API.\n *\n * ```typescript\n * const cacheAnnotation = defineAnnotation<{ ttl: number }>()({\n * namespace: 'cache',\n * applicableTo: ['read'],\n * });\n *\n * // Call the handle to construct a value:\n * const applied = cacheAnnotation({ ttl: 60 });\n *\n * // Read a stored value off a plan:\n * const payload = cacheAnnotation.read(plan);\n * ```\n *\n * Note on the inherited `Function.prototype.apply`: because the handle is\n * a function, the property name `apply` resolves to JavaScript's built-in\n * `Function.prototype.apply` (which lets you invoke a function with an\n * array of arguments). This is **not** the construction entry point — to\n * build an `AnnotationValue`, call the handle directly. The\n * `AnnotationHandle` interface deliberately does not declare an `apply`\n * member of its own.\n */\nexport interface AnnotationHandle<Payload, Kinds extends OperationKind> {\n (value: Payload): AnnotationValue<Payload, Kinds>;\n readonly namespace: string;\n readonly applicableTo: ReadonlySet<Kinds>;\n read(plan: {\n readonly meta: { readonly annotations?: Record<string, unknown> };\n }): Payload | undefined;\n}\n\n/**\n * Options accepted by `defineAnnotation`.\n *\n * `namespace` is the string key under which the annotation is stored in\n * `plan.meta.annotations`. **Reserved namespaces** include framework-\n * internal metadata keys; user handles must not use them:\n *\n * - `codecs` — used by the SQL emitter to record per-alias codec ids\n * (`meta.annotations.codecs[alias] = 'pg/text@1'`); the SQL runtime's\n * `decodeRow` reads from this key. A user `defineAnnotation('codecs')`\n * handle is not structurally prevented, but its behavior with the\n * emitter and the runtime is undefined and we make no compatibility\n * guarantees about it.\n * - Target-specific keys such as `pg` (and equivalents on other\n * targets) are similarly reserved for adapter / target use.\n *\n * `applicableTo` declares which operation kinds the annotation may attach\n * to. The lane terminals' type-level `ValidAnnotations<K, As>` gate rejects\n * annotations whose `Kinds` does not include the terminal's `K`; the\n * runtime helper `assertAnnotationsApplicable` does the equivalent at\n * runtime so casts and `any` cannot bypass the gate.\n */\nexport interface DefineAnnotationOptions<Kinds extends OperationKind> {\n readonly namespace: string;\n readonly applicableTo: readonly Kinds[];\n}\n\n/**\n * Defines a typed annotation handle.\n *\n * Two-step call form. The first step takes the `Payload` type argument\n * (TypeScript cannot infer `Payload` from anything in the options, so it\n * must be supplied explicitly); the second step takes the runtime options\n * and infers `Kinds` from the `applicableTo` array via a `const` type\n * parameter, so the operation kinds appear exactly once at the call site.\n *\n * @example\n * ```typescript\n * // Read-only annotation. Lane terminals like `db.User.first(...)` accept\n * // it; `db.User.create(...)` rejects it at the type level.\n * const cacheAnnotation = defineAnnotation<{ ttl?: number; skip?: boolean }>()({\n * namespace: 'cache',\n * applicableTo: ['read'],\n * }); // Kinds inferred as 'read'\n *\n * // Write-only annotation. Mirror image.\n * const auditAnnotation = defineAnnotation<{ actor: string }>()({\n * namespace: 'audit',\n * applicableTo: ['write'],\n * }); // Kinds inferred as 'write'\n *\n * // Annotation applicable to both kinds (e.g. tracing).\n * const otelAnnotation = defineAnnotation<{ traceId: string }>()({\n * namespace: 'otel',\n * applicableTo: ['read', 'write'],\n * }); // Kinds inferred as 'read' | 'write'\n * ```\n *\n * **Reserved namespaces.** See `DefineAnnotationOptions.namespace` for the\n * list of framework-internal namespaces (`codecs`, target-specific keys).\n * `defineAnnotation` does not structurally prevent a user from naming a\n * reserved namespace, but the framework makes no compatibility guarantee\n * about handles that do.\n */\nexport function defineAnnotation<Payload>(): <const Kinds extends OperationKind>(\n options: DefineAnnotationOptions<Kinds>,\n) => AnnotationHandle<Payload, Kinds> {\n return <const Kinds extends OperationKind>(\n options: DefineAnnotationOptions<Kinds>,\n ): AnnotationHandle<Payload, Kinds> => {\n const namespace = options.namespace;\n const applicableTo: ReadonlySet<Kinds> = Object.freeze(new Set(options.applicableTo));\n\n function handle(value: Payload): AnnotationValue<Payload, Kinds> {\n return Object.freeze({\n __annotation: true as const,\n namespace,\n value,\n applicableTo,\n });\n }\n\n function read(plan: {\n readonly meta: { readonly annotations?: Record<string, unknown> };\n }): Payload | undefined {\n const stored = plan.meta.annotations?.[namespace];\n if (!isAnnotationValue(stored)) {\n return undefined;\n }\n if (stored.namespace !== namespace) {\n // Defensive: a different handle wrote under our namespace key.\n return undefined;\n }\n return stored.value as Payload;\n }\n\n return Object.freeze(\n Object.assign(handle, {\n namespace,\n applicableTo,\n read,\n }),\n );\n };\n}\n\n/**\n * Type-level applicability gate consumed by lane terminals.\n *\n * Maps a tuple of `AnnotationValue`s to a tuple where each element either\n * keeps its annotation type (when the annotation's declared `Kinds`\n * includes the terminal's operation kind `K`) or resolves to `never`\n * (when the kinds are incompatible). A `never` element makes the entire\n * tuple unassignable, surfacing the mismatch as a type error at the call\n * site of the terminal.\n *\n * The SQL DSL builders constrain their variadic `...annotations`\n * parameter via `As & ValidAnnotations<K, As>`. **The intersection is\n * load-bearing** — see the note below. The ORM terminals deliberately\n * sidestep this trick by taking one annotation per `meta.annotate(...)`\n * call (no variadic-tuple inference involved), so `ValidAnnotations` is\n * consumed only by the SQL DSL today.\n *\n * @example\n * ```typescript\n * class SelectQuery<Row> {\n * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n * ...annotations: As & ValidAnnotations<'read', As>\n * ): SelectQuery<Row>;\n * }\n *\n * class InsertQuery<Row> {\n * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n * ...annotations: As & ValidAnnotations<'write', As>\n * ): InsertQuery<Row>;\n * }\n *\n * db.users.select('id').annotate(cacheAnnotation({ ttl: 60 }));\n * // ✓ cacheAnnotation declares 'read'; SelectQuery.annotate requires 'read'.\n *\n * db.users.insert([{ name: 'Alice' }]).annotate(cacheAnnotation({ ttl: 60 }));\n * // ✗ cacheAnnotation declares 'read'; InsertQuery.annotate requires 'write'.\n * // Element resolves to `never` → tuple unassignable → type error.\n * ```\n *\n * **Why `As & ValidAnnotations<K, As>` and not `ValidAnnotations<K, As>`\n * alone.** TypeScript's variadic-tuple inference is too forgiving when\n * the parameter type refers to `As` only through `ValidAnnotations`: it\n * will pick an `As` that makes the call valid even when the gated tuple\n * would contain `never` for an inapplicable element. The intersection\n * pins `As` to the actual call-site tuple AND requires it to be\n * assignable to the gated form. A `never` element in the gated tuple\n * then collapses the corresponding intersection position to `never`,\n * and the inapplicable argument fails to assign — surfacing the mismatch\n * as a type error at the call site.\n *\n * The runtime helper `assertAnnotationsApplicable` covers the equivalent\n * check at runtime so casts and `any` cannot bypass this gate.\n */\nexport type ValidAnnotations<\n K extends OperationKind,\n As extends readonly AnnotationValue<unknown, OperationKind>[],\n> = {\n readonly [I in keyof As]: As[I] extends AnnotationValue<infer P, infer Kinds>\n ? K extends Kinds\n ? AnnotationValue<P, Kinds>\n : never\n : never;\n};\n\n/**\n * Runtime applicability gate. Throws `RUNTIME.ANNOTATION_INAPPLICABLE` if\n * any annotation in `annotations` declares an `applicableTo` set that does\n * not include `kind`. Used by lane terminals (SQL DSL builders' `.build()`,\n * ORM `Collection` terminals) to fail closed when the type-level\n * `ValidAnnotations` gate is bypassed via cast / `any` / dynamic\n * invocation.\n *\n * Passes silently on:\n * - empty arrays\n * - annotations whose `applicableTo` includes `kind`\n *\n * Throws on:\n * - any annotation whose `applicableTo` does not include `kind`. The\n * error names the offending annotation's `namespace` and the\n * `terminalName` so users can locate the misuse.\n *\n * @example\n * ```typescript\n * // Inside an ORM read terminal:\n * assertAnnotationsApplicable(annotations, 'read', 'first');\n * ```\n */\nexport function assertAnnotationsApplicable(\n annotations: readonly AnnotationValue<unknown, OperationKind>[],\n kind: OperationKind,\n terminalName: string,\n): void {\n for (const annotation of annotations) {\n if (!annotation.applicableTo.has(kind)) {\n throw runtimeError(\n 'RUNTIME.ANNOTATION_INAPPLICABLE',\n `Annotation '${annotation.namespace}' is not applicable to '${kind}' operations (terminal: '${terminalName}'). The annotation declares applicableTo = [${Array.from(\n annotation.applicableTo,\n )\n .map((k) => `'${k}'`)\n .join(', ')}].`,\n {\n namespace: annotation.namespace,\n terminalName,\n kind,\n applicableTo: Array.from(annotation.applicableTo),\n },\n );\n }\n }\n}\n\n/**\n * Type guard for branded annotation values stored in `plan.meta.annotations`.\n *\n * Internal — used by `AnnotationHandle.read` to distinguish user\n * annotations (created by calling a handle returned from\n * `defineAnnotation(...)`) from framework-internal metadata that may\n * happen to live under the same namespace key.\n */\nfunction isAnnotationValue(value: unknown): value is AnnotationValue<unknown, OperationKind> {\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const candidate = value as { readonly __annotation?: unknown };\n return candidate.__annotation === true;\n}\n","import { runtimeError } from './runtime-error';\n\nexport class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {\n private readonly generator: AsyncGenerator<Row, void, unknown>;\n private consumed = false;\n private consumedBy: 'bufferedArray' | 'iterator' | undefined;\n private bufferedArrayPromise: Promise<Row[]> | undefined;\n\n constructor(generator: AsyncGenerator<Row, void, unknown>) {\n this.generator = generator;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Row> {\n if (this.consumed) {\n throw runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === 'bufferedArray' ? 'toArray()/then()' : 'for-await loop'}. Each AsyncIterableResult can only be iterated once.`,\n {\n consumedBy: this.consumedBy,\n suggestion:\n this.consumedBy === 'bufferedArray'\n ? 'If you need to iterate multiple times, store the results from toArray() in a variable and reuse that.'\n : 'If you need to iterate multiple times, use toArray() to collect all results first.',\n },\n );\n }\n this.consumed = true;\n this.consumedBy = 'iterator';\n return this.generator;\n }\n\n toArray(): Promise<Row[]> {\n if (this.consumedBy === 'iterator') {\n return Promise.reject(\n runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n 'AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.',\n {\n consumedBy: this.consumedBy,\n suggestion:\n 'The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating.',\n },\n ),\n );\n }\n\n if (this.bufferedArrayPromise) {\n return this.bufferedArrayPromise;\n }\n\n this.consumed = true;\n this.consumedBy = 'bufferedArray';\n this.bufferedArrayPromise = (async () => {\n const out: Row[] = [];\n for await (const item of this.generator) {\n out.push(item);\n }\n return out;\n })();\n return this.bufferedArrayPromise;\n }\n\n async first(): Promise<Row | null> {\n const rows = await this.toArray();\n return rows[0] ?? null;\n }\n\n async firstOrThrow(): Promise<Row> {\n const row = await this.first();\n if (row === null)\n throw runtimeError(\n 'RUNTIME.NO_ROWS',\n 'Expected at least one row, but none were returned',\n {},\n );\n return row;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: PromiseLike implementation is intentional for await support.\n then<TResult1 = Row[], TResult2 = never>(\n onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.toArray().then(onfulfilled, onrejected);\n }\n}\n","import type { RuntimeAbortedPhase } from './runtime-error';\nimport { runtimeAborted } from './runtime-error';\n\n/**\n * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied\n * context is already aborted at the precheck site. Centralises the\n * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that\n * every codec dispatch site (and the `beforeExecute` middleware phase)\n * repeats. Accepts both the framework `CodecCallContext` and the\n * `RuntimeMiddlewareContext`; both expose `signal?: AbortSignal`.\n */\nexport function checkAborted(\n ctx: { readonly signal?: AbortSignal },\n phase: RuntimeAbortedPhase,\n): void {\n if (ctx.signal?.aborted) {\n throw runtimeAborted(phase, ctx.signal.reason);\n }\n}\n\n/**\n * Race a per-cell `Promise.all` (or any other in-flight work promise) against\n * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly\n * even when codec bodies ignore the signal. In-flight bodies that ignore the\n * signal are abandoned and run to completion in the background — the\n * cooperative-cancellation contract documented in ADR 204.\n *\n * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with\n * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —\n * that path is the canonical \"aborted at entry\" surface and avoids\n * scheduling the work promise. As a defensive belt-and-braces, this helper\n * also handles the already-aborted case internally: `AbortSignal` does not\n * replay past abort events to listeners registered after the abort, so we\n * inspect `signal.aborted` synchronously and reject with the sentinel\n * before installing the listener. The rejection is still attributed to the\n * abort path via the sentinel-identity check.\n *\n * Distinguishing the rejection source is load-bearing for AC-ERR4\n * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).\n * The semantically equivalent `abortable(signal)` helper in\n * `@prisma-next/utils` rejects with `signal.reason ?? new DOMException(...)`,\n * which is not stably distinguishable from a codec-thrown error by identity\n * alone (a fresh fallback DOMException is allocated per call). We instead\n * track abort attribution with a unique sentinel: only the `onAbort` listener\n * installed here ever rejects with the sentinel, so an `error === sentinel`\n * identity check after the race is unambiguous.\n *\n * Lives in `framework-components` (rather than the SQL family, where it\n * originated in m2) so every family runtime that needs cooperative\n * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode\n * today, Mongo encode in m3) shares the same attribution logic.\n */\nexport async function raceAgainstAbort<T>(\n work: Promise<T>,\n signal: AbortSignal | undefined,\n phase: RuntimeAbortedPhase,\n): Promise<T> {\n if (signal === undefined) {\n return await work;\n }\n const sentinel: { reason: unknown } = { reason: undefined };\n let onAbort: (() => void) | undefined;\n\n const abortPromise = new Promise<never>((_, reject) => {\n if (signal.aborted) {\n sentinel.reason = signal.reason;\n reject(sentinel);\n return;\n }\n onAbort = () => {\n sentinel.reason = signal.reason;\n reject(sentinel);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n try {\n return await Promise.race([work, abortPromise]);\n } catch (error) {\n if (error === sentinel) {\n throw runtimeAborted(phase, sentinel.reason);\n }\n throw error;\n } finally {\n if (onAbort) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n}\n","import type { ExecutionPlan } from './query-plan';\nimport { checkAborted, raceAgainstAbort } from './race-against-abort';\nimport type {\n ParamRefMutator,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Runs every middleware's `beforeExecute` hook in registration order,\n * threading through the (optional) family-specific `paramsMutator`.\n *\n * Why this lives outside {@link runWithMiddleware}: middleware that\n * mutates parameter values (e.g. cipherstash's bulk-encrypt SDK\n * round-trip) must run *before* the family runtime encodes those\n * parameters to driver wire format. Family runtimes call\n * `runBeforeExecuteChain` between the AST → plan lowering step and\n * the parameter encode step; the encode then observes the mutator's\n * `currentParams()` view. `runWithMiddleware` retains the rest of\n * the lifecycle (`intercept`, driver/row source loop, `onRow`,\n * `afterExecute`) but no longer fires `beforeExecute` itself.\n *\n * Lifecycle within this helper:\n *\n * 1. For each middleware in registration order, if `beforeExecute`\n * is implemented:\n * - `checkAborted(ctx, 'beforeExecute')` short-circuits if the\n * caller already aborted at entry.\n * - The hook is invoked with `(plan, ctx, paramsMutator)`. A\n * middleware body that ignores the mutator stays compatible —\n * JavaScript allows extra positional arguments.\n * - If the hook returns a Promise, it is raced against\n * `ctx.signal` via {@link raceAgainstAbort} so cooperative\n * cancellation surfaces a `RUNTIME.ABORTED { phase:\n * 'beforeExecute' }` envelope even when the body itself\n * ignores the signal.\n *\n * Error propagation: any error thrown by a `beforeExecute` body\n * (or surfaced by the abort race) propagates out of this helper\n * unchanged. The family runtime is responsible for converting it\n * into the appropriate `afterExecute(completed: false)` notification\n * once `runWithMiddleware` runs.\n *\n * Relationship to {@link runWithMiddleware}: the framework's\n * `RuntimeCore.execute` template calls this helper between\n * `lower(plan)` and `runWithMiddleware(...)`. Family runtimes that\n * override `execute` (e.g. SQL, which inlines lower + encode for\n * direct mutator threading) call this helper themselves at the\n * equivalent point — between the family's AST → draft-plan\n * lowering and the parameter-encode step.\n *\n * Intercept ordering: this helper fires unconditionally before\n * `runWithMiddleware`. `intercept` (inside `runWithMiddleware`)\n * therefore observes the post-`beforeExecute` plan — mutator\n * mutations are visible in the params interceptors see. The\n * trade-off is documented on `RuntimeMiddleware.intercept`.\n */\nexport async function runBeforeExecuteChain<\n TExec extends ExecutionPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n>(\n plan: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec, TMutator>>,\n ctx: RuntimeMiddlewareContext,\n paramsMutator?: TMutator,\n): Promise<void> {\n for (const mw of middleware) {\n if (!mw.beforeExecute) {\n continue;\n }\n checkAborted(ctx, 'beforeExecute');\n const work = mw.beforeExecute(plan, ctx, paramsMutator as TMutator);\n if (work !== undefined) {\n await raceAgainstAbort(Promise.resolve(work), ctx.signal, 'beforeExecute');\n }\n }\n}\n","import { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan } from './query-plan';\nimport type { RuntimeMiddleware, RuntimeMiddlewareContext } from './runtime-middleware';\n\n/**\n * Drives a single execution of `runDriver()` through the middleware\n * lifecycle's intercept + row-source + termination phases.\n *\n * Lifecycle, in order:\n * 1. For each middleware in registration order: `intercept(exec, ctx)`. The\n * first non-`undefined` result wins; subsequent middleware's `intercept`\n * does not fire. On a hit, the runtime emits a `middleware.intercept`\n * debug event naming the winning middleware, switches the row source to\n * the intercepted rows, and proceeds with `source: 'middleware'`. On\n * all-passthrough (every `intercept` returns `undefined` or is omitted),\n * `source: 'driver'` is used and the row source is `runDriver()`.\n * 2. Iterate the row source. On the driver path, for each row, for each\n * middleware in registration order: `onRow(row, exec, ctx)`; then yield\n * the row. On the intercepted hit path, `onRow` is skipped — intercepted\n * rows did not originate from a driver row stream — but rows are still\n * yielded to the consumer in order.\n * 3. On successful completion: for each middleware in registration order:\n * `afterExecute(exec, { rowCount, latencyMs, completed: true, source },\n * ctx)`.\n * 4. On any error thrown during steps 1–2: for each middleware in\n * registration order: `afterExecute(exec, { rowCount, latencyMs,\n * completed: false, source }, ctx)`. Errors thrown by `afterExecute`\n * during the error path are swallowed so they do not mask the original\n * error. The original error is then rethrown.\n *\n * `beforeExecute` is **not** fired here — see\n * {@link runBeforeExecuteChain} in `before-execute-chain.ts`. Family\n * runtimes call that helper between the AST → plan lowering step and\n * the parameter encode step so middleware that mutates ParamRef\n * values (e.g. cipherstash bulk-encrypt) can have its mutations\n * visible to encode. `runWithMiddleware` operates on the fully-\n * encoded plan; interceptors therefore observe a fully-mutated,\n * encoded plan.\n *\n * The `source` field on `AfterExecuteResult` lets observers (telemetry,\n * lints, budgets) distinguish driver-served from middleware-served\n * executions without needing their own out-of-band signal.\n *\n * This helper is the single canonical implementation of the\n * intercept-and-row-source loop; family runtimes should not\n * reimplement it.\n */\nexport function runWithMiddleware<TExec extends ExecutionPlan, Row>(\n exec: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec>>,\n ctx: RuntimeMiddlewareContext,\n runDriver: () => AsyncIterable<Row>,\n): AsyncIterableResult<Row> {\n const iterator = async function* (): AsyncGenerator<Row, void, unknown> {\n const startedAt = Date.now();\n let rowCount = 0;\n let completed = false;\n let source: 'driver' | 'middleware' = 'driver';\n // Deferred so a winning interceptor can skip `runDriver()` entirely.\n // For factories that lazily produce async generators this is a no-op,\n // but factories that do eager work (e.g. acquiring a connection,\n // sending a query) must not run on the intercepted hit path.\n let rowSource: AsyncIterable<Row> | Iterable<Row> | undefined;\n\n try {\n for (const mw of middleware) {\n if (!mw.intercept) {\n continue;\n }\n // Mark the lifecycle as middleware-driven *before* awaiting the\n // hook. If `intercept` throws, the catch block reports the failure\n // as `source: 'middleware'` — the failure originated in the\n // intercept chain, not in the driver. If `intercept` returns\n // `undefined` (passthrough), we revert to `'driver'` and continue.\n source = 'middleware';\n const result = await mw.intercept(exec, ctx);\n if (result === undefined) {\n source = 'driver';\n continue;\n }\n ctx.log.debug?.({ event: 'middleware.intercept', middleware: mw.name });\n // The intercepted rows are typed as `Record<string, unknown>` at\n // the SPI level; the consumer's `Row` type parameter is enforced by\n // the caller (via the plan's phantom `_row`) the same way driver\n // rows are. Cast through unknown to bridge the SPI shape to the\n // caller-supplied Row.\n rowSource = result.rows as unknown as AsyncIterable<Row> | Iterable<Row>;\n break;\n }\n\n if (source === 'driver') {\n rowSource = runDriver();\n }\n\n // `rowSource` is always assigned by this point: either the intercepted\n // rows (on a hit) or `runDriver()` (on the driver path).\n for await (const row of rowSource as AsyncIterable<Row> | Iterable<Row>) {\n if (source === 'driver') {\n for (const mw of middleware) {\n if (mw.onRow) {\n await mw.onRow(row as Record<string, unknown>, exec, ctx);\n }\n }\n }\n rowCount++;\n yield row;\n }\n\n completed = true;\n } catch (error) {\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n try {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n } catch {\n // Swallow afterExecute errors during the error path so they do not\n // mask the original error.\n }\n }\n }\n\n throw error;\n }\n\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n }\n }\n };\n\n return new AsyncIterableResult(iterator());\n}\n","import type { CodecCallContext } from '../shared/codec-types';\nimport { AsyncIterableResult } from './async-iterable-result';\nimport { runBeforeExecuteChain } from './before-execute-chain';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { checkAborted } from './race-against-abort';\nimport { runWithMiddleware } from './run-with-middleware';\nimport type {\n RuntimeExecuteOptions,\n RuntimeExecutor,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Constructor options shared by every concrete `RuntimeCore` subclass.\n *\n * Family runtimes typically build the middleware list and the\n * `RuntimeMiddlewareContext` themselves (running compatibility checks,\n * narrowing the context's `contract` field, etc.) before calling `super`.\n */\nexport interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {\n readonly middleware: ReadonlyArray<TMiddleware>;\n readonly ctx: RuntimeMiddlewareContext;\n}\n\n/**\n * Family-agnostic abstract runtime base.\n *\n * Defines the entire `execute(plan)` template in one place:\n *\n * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides\n * this to run its `beforeCompile` middleware-hook chain.\n * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`\n * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).\n * 3. `runBeforeExecuteChain(exec, this.middleware, this.ctx)` — concrete;\n * runs every middleware's `beforeExecute` hook after lowering but\n * before the row source is opened. Family runtimes that need a\n * params mutator visible to a downstream encode step (SQL) override\n * `execute` and call this helper themselves at the equivalent\n * pre-encode point.\n * 4. `runWithMiddleware(exec, this.middleware, this.ctx,\n * () => runDriver(exec))` — concrete; runs the intercept chain,\n * drives the row source, fires `onRow` / `afterExecute`. Does\n * **not** fire `beforeExecute` — see step 3.\n *\n * Concrete subclasses must implement `lower`, `runDriver`, and `close`.\n *\n * The class is generic over:\n * - `TPlan` — the family's pre-lowering plan type.\n * - `TExec` — the family's post-lowering (executable) plan type.\n * - `TMiddleware` — the family's middleware type. Constrained to\n * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the\n * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered\n * `TExec`. (The spec/plan wording \"RuntimeMiddleware<TPlan>\" is\n * tightened to `<TExec>` here so the helper call typechecks; the\n * intent is unchanged — middleware sees the post-lowering plan.)\n */\nexport abstract class RuntimeCore<\n TPlan extends QueryPlan,\n TExec extends ExecutionPlan,\n TMiddleware extends RuntimeMiddleware<TExec>,\n> implements RuntimeExecutor<TPlan>\n{\n protected readonly middleware: ReadonlyArray<TMiddleware>;\n protected readonly ctx: RuntimeMiddlewareContext;\n\n constructor(options: RuntimeCoreOptions<TMiddleware>) {\n this.middleware = options.middleware;\n this.ctx = options.ctx;\n }\n\n /**\n * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses\n * may override to run a `beforeCompile` middleware chain (SQL does this\n * to support typed AST rewrites — see `before-compile-chain.ts`).\n */\n protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan> {\n return plan;\n }\n\n /**\n * Lower a pre-lowering `TPlan` into the family's executable `TExec`.\n * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo\n * produces `{ command, ... }`.\n *\n * `ctx` carries per-query cancellation (and any future fields on\n * `CodecCallContext`); concrete subclasses forward it to the\n * encode-side codec dispatch site (e.g. SQL's `encodeParams` in m2,\n * Mongo's `resolveValue` in m3). The runtime allocates one ctx per\n * `execute()` call and threads the same reference everywhere; the\n * `signal` field inside may be `undefined`, but the ctx object itself\n * is always present.\n */\n protected abstract lower(plan: TPlan, ctx: CodecCallContext): TExec | Promise<TExec>;\n\n /**\n * Drive the underlying transport for a lowered `TExec`. Yields raw rows\n * directly from the driver as `Record<string, unknown>`; codec decoding\n * (if any) is the subclass's responsibility, applied by wrapping\n * `execute()` rather than living inside this hook.\n *\n * The `Row` type parameter on `execute()` is satisfied by the caller via\n * the plan's phantom `_row`; the runtime treats rows as opaque records\n * here and trusts the caller's row typing.\n */\n protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;\n\n abstract close(): Promise<void>;\n\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call. The ctx object is always allocated; the\n // `signal` field is only included when a signal was supplied (required\n // under exactOptionalPropertyTypes — `{ signal: undefined }` would not\n // satisfy `signal?: AbortSignal`).\n const codecCtx: CodecCallContext = signal === undefined ? {} : { signal };\n\n async function* generator(): AsyncGenerator<Row, void, unknown> {\n // Pre-check the signal at entry so an already-aborted caller observes\n // RUNTIME.ABORTED on the first `next()` without any work being done.\n checkAborted(codecCtx, 'stream');\n\n const compiled = await self.runBeforeCompile(plan);\n const exec = await self.lower(compiled, codecCtx);\n // Fire the framework-level `beforeExecute` chain on the lowered\n // plan before opening the row source. Families that need\n // pre-encode mutator visibility (SQL) override `execute` to\n // inject the same chain at the equivalent point.\n await runBeforeExecuteChain<TExec>(exec, self.middleware, self.ctx);\n // The driver yields raw `Record<string, unknown>`; we cast to `Row` here.\n // The Row contract is enforced by the caller via `plan._row`.\n yield* runWithMiddleware<TExec, Row>(\n exec,\n self.middleware,\n self.ctx,\n () => self.runDriver(exec) as AsyncIterable<Row>,\n );\n }\n\n return new AsyncIterableResult(generator());\n }\n}\n","import type { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { runtimeError } from './runtime-error';\n\nexport interface RuntimeLog {\n info(event: unknown): void;\n warn(event: unknown): void;\n error(event: unknown): void;\n debug?(event: unknown): void;\n}\n\n/**\n * Per-execute context threaded through every middleware phase\n * (`beforeExecute`, `onRow`, `afterExecute`). Allocated once per\n * `runtime.execute()` call and shared by reference across all\n * middleware in the chain.\n *\n * - `signal` carries the per-query `AbortSignal` -- the same\n * reference that `runtime.execute(plan, { signal })` was invoked\n * with, and the same reference threaded into the per-call\n * `CodecCallContext` (ADR 207). Middleware that wraps a\n * network-backed SDK forwards `ctx.signal` into that SDK to\n * propagate caller cancellation; pure-CPU middleware ignores it.\n *\n * Symmetric plumbing across all middleware phases (rather than only\n * `beforeExecute`) is a deliberate choice: a middleware that wraps a\n * downstream observability hook or post-processor in `afterExecute` /\n * `onRow` needs the same cancellation reach as its `beforeExecute`\n * counterpart.\n */\nexport interface RuntimeMiddlewareContext {\n readonly contract: unknown;\n readonly mode: 'strict' | 'permissive';\n readonly now: () => number;\n readonly log: RuntimeLog;\n /**\n * Returns a stable string identifying the (storage, statement, params)\n * tuple of an execution. Two semantically equivalent executions return\n * the same string. Used by middleware that need per-execution identity\n * (caching, request coalescing).\n *\n * The family runtime owns the implementation:\n * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`\n * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`\n *\n * The method is `async` because the underlying digest helper\n * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`\n * primitive is asynchronous by design.\n *\n * The returned string is intended to be consumed directly as a `Map` key\n * — it is not (and should not be) further hashed by callers.\n */\n contentHash(exec: ExecutionPlan): Promise<string>;\n /**\n * Per-execute cancellation signal threaded through every middleware\n * phase. Middleware that wraps async work or downstream cancellable\n * primitives should observe this and abort early when the consumer\n * cancels.\n */\n readonly signal?: AbortSignal;\n /**\n * Identifies the queryable scope this execution is running under.\n *\n * - `'runtime'` — top-level `runtime.execute(plan)`. The default scope\n * used by the standard read/write paths.\n * - `'connection'` — `connection.execute(plan)` after\n * `runtime.connection()` checked out a connection from the pool.\n * - `'transaction'` — `transaction.execute(plan)` inside an explicit\n * transaction, or a query routed through `withTransaction`.\n *\n * Middleware that should only act at the top level read this field to\n * bypass non-runtime scopes. The cache middleware uses it to skip\n * caching inside transactions (where read-after-write coherence is the\n * caller's expectation) and dedicated connections (where the user has\n * explicitly stepped outside the shared cache surface). Observers that\n * don't care about the scope can ignore the field.\n *\n * Family runtimes populate this at context-construction time per\n * scope. Existing middleware that ignore the field are unaffected.\n */\n readonly scope: 'runtime' | 'connection' | 'transaction';\n}\n\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\n /**\n * Indicates where the rows observed during this execution came from.\n *\n * - `'driver'` — the default. Rows came from the underlying driver via\n * `runDriver` / `runWithMiddleware`'s normal path.\n * - `'middleware'` — a `RuntimeMiddleware.intercept` hook short-circuited\n * execution and supplied the rows directly. The driver was not invoked.\n *\n * Observers (telemetry, lints, budgets) that need to distinguish between\n * driver-served and middleware-served executions read this field.\n * Observers that don't care can ignore it.\n */\n readonly source: 'driver' | 'middleware';\n}\n\n/**\n * Result of a successful `RuntimeMiddleware.intercept` hook.\n *\n * Carries the rows that the middleware wishes to return in place of\n * invoking the driver. The runtime iterates `rows` in order and yields\n * each row to the consumer; `beforeExecute`, `runDriver`, and `onRow` are\n * all skipped on the hit path. `afterExecute` still fires with\n * `source: 'middleware'`.\n *\n * `rows` accepts both `Iterable` (arrays, sync generators) and\n * `AsyncIterable` (async generators). `for await` natively handles both\n * via `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the\n * orchestrator does not need to branch on the variant. Cached arrays in\n * the cache middleware are the common case; streaming variants support\n * future use cases like mock layers replaying recordings.\n *\n * Row shape is `Record<string, unknown>` — the same untyped shape\n * `onRow` receives. The SQL runtime decodes intercepted rows through its\n * normal codec pass, so interceptors cache and return raw (undecoded)\n * rows.\n */\nexport interface InterceptResult {\n readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;\n}\n\n/**\n * Marker interface for family-specific param-ref mutators threaded into\n * `beforeExecute` as the third argument. The framework treats the mutator\n * opaquely — it allocates and forwards the family's mutator instance so\n * `runWithMiddleware` can stay family-agnostic. SQL extends this with\n * `SqlParamRefMutator` (over `ParamRef`); Mongo extends with\n * `MongoParamRefMutator` (over `MongoParamRef`).\n *\n * Extension authors target the family-specific mutator type, not this\n * marker.\n */\ndeclare const PARAM_REF_MUTATOR_BRAND: unique symbol;\nexport type ParamRefMutator = { readonly [PARAM_REF_MUTATOR_BRAND]?: never };\n\n/**\n * Family-agnostic middleware SPI parameterized over the plan marker.\n *\n * `TPlan` defaults to the framework `QueryPlan` marker so a generic\n * middleware (e.g. cross-family telemetry) can be authored without\n * naming a family. Family-specific middleware (`SqlMiddleware`,\n * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.\n *\n * `TMutator` is the family-specific {@link ParamRefMutator} the runtime\n * threads into `beforeExecute(plan, ctx, params)` as a third argument.\n * Existing `(plan)` / `(plan, ctx)` middleware bodies continue to compile\n * — TypeScript permits assigning a function with fewer parameters to a\n * function-typed slot that declares more. The third arg is additive.\n */\nexport interface RuntimeMiddleware<\n TPlan extends QueryPlan = QueryPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n> {\n readonly name: string;\n readonly familyId?: string;\n readonly targetId?: string;\n /**\n * Optional short-circuit hook. Runs inside `runWithMiddleware`, after\n * the orchestrator receives the lowered plan and before any\n * `beforeExecute` hook fires. Middleware run in registration order; the\n * first to return a non-`undefined` `InterceptResult` wins, and\n * subsequent middleware's `intercept` does not fire.\n *\n * On a hit, `beforeExecute`, `runDriver`, and `onRow` are all skipped.\n * `afterExecute` still fires with `source: 'middleware'`.\n *\n * Returning `undefined` (or omitting the hook entirely) signals\n * passthrough — execution proceeds through the normal driver path.\n *\n * Errors thrown inside `intercept` are rethrown by `runWithMiddleware`\n * as the original `Error` — no envelope is guaranteed at this layer.\n * Before rethrowing, `afterExecute` fires with `completed: false` and\n * `source: 'middleware'`. Errors thrown by `afterExecute` during the\n * error path remain swallowed (existing semantics, unchanged).\n *\n * Used by middleware that need to short-circuit execution and supply\n * rows directly: caching, mocks, rate limiting, circuit breaking.\n */\n intercept?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<InterceptResult | undefined>;\n /**\n * Fires after the family runtime has produced a draft execution\n * plan from the AST, but before the family encodes parameter values\n * to driver wire format. Mutations applied via the\n * family-specific `params` mutator are visible to the subsequent\n * encode step.\n *\n * Lifecycle position (SQL example):\n * `runBeforeCompile → lowerSqlPlan → beforeExecute → encodeParams → intercept → driver`.\n *\n * The `params` argument is a family-specific {@link ParamRefMutator}\n * scoped to the value slots of `ParamRef` nodes in the plan's AST.\n * Middleware that doesn't need to mutate params can ignore the\n * argument; existing `(plan)` / `(plan, ctx)` bodies stay compatible.\n *\n * `ctx.signal` carries the per-query `AbortSignal`; middleware that\n * wraps a network SDK forwards it. Cooperative cancellation\n * surfaces a `RUNTIME.ABORTED { phase: 'beforeExecute' }` envelope\n * promptly even when the body ignores the signal.\n *\n * Intercept ordering: `intercept` runs *after* this hook; an\n * interceptor that short-circuits the driver path still observes\n * the post-`beforeExecute`, fully-encoded plan. The trade-off is\n * that any `beforeExecute` SDK round-trips happen even when a\n * downstream interceptor would have skipped the driver entirely.\n */\n beforeExecute?(\n plan: TPlan,\n ctx: RuntimeMiddlewareContext,\n params?: TMutator,\n ): void | Promise<void>;\n onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;\n afterExecute?(\n plan: TPlan,\n result: AfterExecuteResult,\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n}\n\n/**\n * Cross-family middleware — one that doesn't constrain `familyId` or\n * `targetId` and is therefore compatible with any family runtime's\n * middleware array (`SqlMiddleware[]`, `MongoMiddleware[]`, etc.).\n *\n * The intersection `RuntimeMiddleware & { familyId?: undefined; targetId?: undefined }`\n * pins both optional properties to exactly `undefined` (intersecting\n * `string | undefined` with `undefined` collapses to `undefined`). Under\n * `exactOptionalPropertyTypes: true`, the plain `RuntimeMiddleware` shape\n * — with `familyId?: string` — is *not* assignable to `SqlMiddleware`\n * (which narrows `familyId?: 'sql'`) because `string` is wider than\n * `'sql'`. Pinning the property to `undefined` makes the value a subtype\n * of every narrowed variant: `undefined` extends both `'sql' | undefined`\n * and `'mongo' | undefined`, so a `CrossFamilyMiddleware` value drops\n * into a SQL or Mongo middleware slot without a cast.\n *\n * Cross-family middleware factories (`createCacheMiddleware`, future\n * `audit` / OTel middleware) declare this as their return type so the\n * cross-family typing is named once rather than re-spelled at every call\n * site.\n */\nexport type CrossFamilyMiddleware<TPlan extends QueryPlan = QueryPlan> =\n RuntimeMiddleware<TPlan> & {\n readonly familyId?: undefined;\n readonly targetId?: undefined;\n };\n\n/**\n * Optional per-`execute` options accepted by every family runtime.\n *\n * `signal` is the per-query cancellation signal. The runtime threads the\n * signal through to every codec call for the query and uses it to short-\n * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.\n * Omitting the option (or passing `undefined`) preserves today's behavior\n * bit-for-bit.\n */\nexport interface RuntimeExecuteOptions {\n readonly signal?: AbortSignal;\n readonly scope?: 'runtime' | 'connection' | 'transaction';\n}\n\n/**\n * Cross-family SPI for any runtime that can execute plans and be shut down.\n * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,\n * Mongo structurally (due to its phantom Row parameter using a unique symbol).\n *\n * The `_row` intersection on `execute` connects the `Row` type parameter to the\n * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.\n */\nexport interface RuntimeExecutor<TPlan extends QueryPlan> {\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nexport function checkMiddlewareCompatibility(\n middleware: RuntimeMiddleware,\n runtimeFamilyId: string,\n runtimeTargetId: string,\n): void {\n if (middleware.targetId !== undefined && middleware.familyId === undefined) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',\n `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,\n { middleware: middleware.name, targetId: middleware.targetId },\n );\n }\n\n if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',\n `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,\n { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },\n );\n }\n\n if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',\n `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,\n { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },\n );\n }\n}\n","import {\n type AnnotationValue,\n assertAnnotationsApplicable,\n type OperationKind,\n} from './annotations';\n\n/**\n * Per-terminal meta configurator handed to user callbacks. The terminal's\n * operation kind `K` is fixed by the terminal that constructed the builder;\n * `annotate(...)` accepts only annotations whose declared `Kinds` include\n * `K`.\n *\n * The conditional parameter type\n * `K extends Kinds ? AnnotationValue<P, Kinds> : never` collapses to `never`\n * for inapplicable annotations, surfacing the mismatch as a type error at\n * the call site of `meta.annotate(...)`. No variadic-tuple inference is\n * involved — TypeScript infers `Kinds` from the annotation argument and\n * checks the conditional directly.\n *\n * The runtime gate inside `annotate` (via\n * `assertAnnotationsApplicable`) catches cast / `any` / dynamic bypasses\n * and throws `RUNTIME.ANNOTATION_INAPPLICABLE`.\n *\n * `annotate` returns the builder for chaining; the return value of the\n * configurator callback is unused, so both block-body and expression-body\n * callbacks compile.\n *\n * @example\n * ```typescript\n * await db.User.find({ id }, (meta) => meta.annotate(cacheAnnotation({ ttl: 60 })));\n * await db.User.create(input, (meta) => {\n * meta.annotate(auditAnnotation({ actor: 'system' }));\n * meta.annotate(otelAnnotation({ traceId }));\n * });\n * ```\n */\nexport interface MetaBuilder<K extends OperationKind> {\n annotate<P, Kinds extends OperationKind>(\n annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never,\n ): this;\n}\n\n/**\n * Lane-side view of a meta builder. Extends the public `MetaBuilder<K>`\n * surface with `annotations` so lane terminals can read the recorded map\n * after invoking the user configurator.\n *\n * Lane terminals construct one of these via `createMetaBuilder(kind, terminalName)`,\n * pass it to the user callback as `MetaBuilder<K>` (the narrower public\n * view), then read `meta.annotations` to thread the recorded values into\n * `plan.meta.annotations`.\n */\nexport interface LaneMetaBuilder<K extends OperationKind> extends MetaBuilder<K> {\n readonly annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n}\n\nclass MetaBuilderImpl<K extends OperationKind> implements LaneMetaBuilder<K> {\n readonly #kind: K;\n readonly #terminalName: string;\n readonly #annotations = new Map<string, AnnotationValue<unknown, OperationKind>>();\n\n constructor(kind: K, terminalName: string) {\n this.#kind = kind;\n this.#terminalName = terminalName;\n }\n\n get annotations(): ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> {\n return this.#annotations;\n }\n\n annotate<P, Kinds extends OperationKind>(\n annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never,\n ): this {\n // Inside the body, the conditional `K extends Kinds ? AnnotationValue<P, Kinds> : never`\n // is opaque to TypeScript — it can't pick a branch without a concrete\n // K. Widen to the structural shape so we can call into the runtime\n // gate. The runtime gate (assertAnnotationsApplicable) is what\n // catches cast bypasses where the conditional would have resolved to\n // `never` had the type checker been allowed to specialise.\n const value = annotation as AnnotationValue<unknown, OperationKind>;\n assertAnnotationsApplicable([value], this.#kind, this.#terminalName);\n this.#annotations.set(value.namespace, value);\n return this;\n }\n}\n\n/**\n * Construct a lane-side meta builder for a terminal of operation kind `K`.\n *\n * Lane terminals call this with their `kind` (`'read'` or `'write'`) and a\n * `terminalName` for error messages, hand the resulting builder to the\n * user-supplied configurator callback (typed as `MetaBuilder<K>`, the\n * narrower public view), and read `meta.annotations` afterwards to thread\n * the recorded values into `plan.meta.annotations`.\n */\nexport function createMetaBuilder<K extends OperationKind>(\n kind: K,\n terminalName: string,\n): LaneMetaBuilder<K> {\n return new MetaBuilderImpl(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AY,WAAW;EAAM,oBAAoB,WAAW;EAAU;CAAgB,CAC1F;AAEJ;;;AC7PA,IAAM,kBAAN,MAA6E;CAC3E;CACA;CACA,+BAAwB,IAAI,IAAqD;CAEjF,YAAY,MAAS,cAAsB;EACzC,KAAKC,QAAQ;EACb,KAAKC,gBAAgB;CACvB;CAEA,IAAI,cAA4E;EAC9E,OAAO,KAAKC;CACd;CAEA,SACE,YACM;EAON,MAAM,QAAQ;EACd,4BAA4B,CAAC,KAAK,GAAG,KAAKF,OAAO,KAAKC,aAAa;EACnE,KAAKC,aAAa,IAAI,MAAM,WAAW,KAAK;EAC5C,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAgB,kBACd,MACA,cACoB;CACpB,OAAO,IAAI,gBAAgB,MAAM,YAAY;AAC/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../src/utils/canonicalize-json.ts"],"mappings":";;AAmBA;;;;iBAAgB,gBAAA,CAAiB,KAAA"}
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../src/utils/canonicalize-json.ts"],"mappings":";;AAmBA;;;;iBAAgB,gBAAA,CAAiB,KAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils/canonicalize-json.ts"],"sourcesContent":["function sortKeys(value: unknown): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(sortKeys);\n }\n const sorted: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeys((value as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\n/**\n * `JSON.stringify` with object keys sorted lexicographically at every level. Two structurally equal values produce the same string regardless of object key insertion order, so the result is a stable cache key for JSON-shaped values.\n *\n * Array order is preserved; primitives serialise as their JSON form. Inputs are expected to be JSON-safe (the typeParams shape on {@link CodecRef} is `JsonValue`-constrained for this reason); callers that need to canonicalise non-JSON-safe values (BigInt, Dates, typed arrays) should use `canonicalStringify` from `@prisma-next/utils/canonical-stringify` instead.\n */\nexport function canonicalizeJson(value: unknown): string {\n return JSON.stringify(sortKeys(value));\n}\n"],"mappings":";AAAA,SAAS,SAAS,OAAyB;CACzC,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAET,IAAI,MAAM,QAAQ,MAAM,EACtB,OAAO,MAAM,IAAI,SAAS;CAE5B,MAAM,SAAkC,OAAO,OAAO,KAAK;CAC3D,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,MAAM,EACzC,OAAO,OAAO,SAAU,MAAkC,KAAK;CAEjE,OAAO;;;;;;;AAQT,SAAgB,iBAAiB,OAAwB;CACvD,OAAO,KAAK,UAAU,SAAS,MAAM,CAAC"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../src/utils/canonicalize-json.ts"],"sourcesContent":["function sortKeys(value: unknown): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(sortKeys);\n }\n const sorted: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeys((value as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\n/**\n * `JSON.stringify` with object keys sorted lexicographically at every level. Two structurally equal values produce the same string regardless of object key insertion order, so the result is a stable cache key for JSON-shaped values.\n *\n * Array order is preserved; primitives serialise as their JSON form. Inputs are expected to be JSON-safe (the typeParams shape on {@link CodecRef} is `JsonValue`-constrained for this reason); callers that need to canonicalise non-JSON-safe values (BigInt, Dates, typed arrays) should use `canonicalStringify` from `@prisma-next/utils/canonical-stringify` instead.\n */\nexport function canonicalizeJson(value: unknown): string {\n return JSON.stringify(sortKeys(value));\n}\n"],"mappings":";AAAA,SAAS,SAAS,OAAyB;CACzC,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,QAAQ;CAE3B,MAAM,SAAkC,OAAO,OAAO,IAAI;CAC1D,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,EAAE,KAAK,GACxC,OAAO,OAAO,SAAU,MAAkC,IAAI;CAEhE,OAAO;AACT;;;;;;AAOA,SAAgB,iBAAiB,OAAwB;CACvD,OAAO,KAAK,UAAU,SAAS,KAAK,CAAC;AACvC"}
package/package.json CHANGED
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "name": "@prisma-next/framework-components",
3
- "version": "0.11.0-dev.2",
3
+ "version": "0.11.0-dev.20",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "Framework component types, assembly logic, and stack creation for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/contract": "0.11.0-dev.2",
10
- "@prisma-next/operations": "0.11.0-dev.2",
11
- "@prisma-next/ts-render": "0.11.0-dev.2",
12
- "@prisma-next/utils": "0.11.0-dev.2",
9
+ "@prisma-next/contract": "0.11.0-dev.20",
10
+ "@prisma-next/operations": "0.11.0-dev.20",
11
+ "@prisma-next/ts-render": "0.11.0-dev.20",
12
+ "@prisma-next/utils": "0.11.0-dev.20",
13
13
  "@standard-schema/spec": "^1.1.0",
14
14
  "arktype": "^2.2.0"
15
15
  },
16
16
  "devDependencies": {
17
- "@prisma-next/tsconfig": "0.11.0-dev.2",
18
- "@prisma-next/tsdown": "0.11.0-dev.2",
17
+ "@prisma-next/tsconfig": "0.11.0-dev.20",
18
+ "@prisma-next/tsdown": "0.11.0-dev.20",
19
19
  "tsdown": "0.22.0",
20
20
  "typescript": "5.9.3",
21
21
  "vitest": "4.1.6"
@@ -1,3 +1,4 @@
1
+ export { mergeCapabilityMatrices } from '../shared/capabilities';
1
2
  export type {
2
3
  AdapterDescriptor,
3
4
  AdapterInstance,
package/src/ir/ir-node.ts CHANGED
@@ -17,7 +17,7 @@
17
17
  * through a union of leaves where each leaf carries a literal kind, so
18
18
  * requiring `kind` at the base would be unearned. Future leaves that
19
19
  * earn polymorphic dispatch override with a required literal at that
20
- * leaf (e.g. `override readonly kind = 'postgres-enum' as const`).
20
+ * leaf (e.g. `override readonly kind = 'pack-contributed-kind' as const`).
21
21
  *
22
22
  * `IRNodeBase` carries no methods: the freeze-and-assign affordance
23
23
  * lives in the free `freezeNode` helper below. Keeping `freezeNode` out
@@ -6,7 +6,7 @@ import type { IRNode } from './ir-node';
6
6
  * The slot is polymorphic at the framework level: a family or target can
7
7
  * persist either a JSON-clean codec-triple object literal (carrying
8
8
  * `kind: 'codec-instance'`) or a class-instance IR node with a narrower
9
- * kind discriminator (e.g. `'postgres-enum'`). Hydration walkers,
9
+ * kind discriminator (e.g. `'<kind>'`). Hydration walkers,
10
10
  * verifiers, and planners dispatch on the `kind` literal to recover the
11
11
  * precise variant.
12
12
  *
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Capability matrix merge primitive shared by emit-time and runtime stack composition.
3
+ *
4
+ * The CLI's `enrichContract` and the SQL runtime's `createExecutionContext` both need
5
+ * to fold a stack of component descriptors' `capabilities` declarations into a single
6
+ * matrix keyed by namespace. Keeping the primitive here lets both call sites stay
7
+ * byte-for-byte consistent without one depending on the other.
8
+ */
9
+
10
+ import { blindCast } from '@prisma-next/utils/casts';
11
+
12
+ type CapabilityMatrix = Record<string, Record<string, boolean>>;
13
+
14
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
16
+ }
17
+
18
+ function sortDeep(value: unknown): unknown {
19
+ if (Array.isArray(value)) {
20
+ return value.map(sortDeep);
21
+ }
22
+ if (!isPlainObject(value)) {
23
+ return value;
24
+ }
25
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
26
+ const next: Record<string, unknown> = {};
27
+ for (const [key, child] of entries) {
28
+ next[key] = sortDeep(child);
29
+ }
30
+ return next;
31
+ }
32
+
33
+ function extractCapabilityMatrix(value: unknown): CapabilityMatrix {
34
+ if (!isPlainObject(value)) return {};
35
+
36
+ const out: CapabilityMatrix = {};
37
+ for (const [namespace, maybeCaps] of Object.entries(value)) {
38
+ if (!isPlainObject(maybeCaps)) continue;
39
+ const caps: Record<string, boolean> = {};
40
+ for (const [key, flag] of Object.entries(maybeCaps)) {
41
+ if (typeof flag === 'boolean') {
42
+ caps[key] = flag;
43
+ }
44
+ }
45
+ if (Object.keys(caps).length > 0) {
46
+ out[namespace] = caps;
47
+ }
48
+ }
49
+
50
+ return out;
51
+ }
52
+
53
+ /**
54
+ * Merge an ordered list of contributor capability declarations into a base matrix.
55
+ *
56
+ * Behaviour:
57
+ * - `base` and each contributor's `capabilities` are filtered through the same
58
+ * structural extraction: non-plain-object namespace blocks are dropped,
59
+ * non-boolean leaves inside a namespace block are dropped, and a namespace
60
+ * block that ends up with zero boolean leaves is omitted entirely (so a
61
+ * later contributor with a malformed namespace cannot erase a namespace
62
+ * already present in `base`).
63
+ * - Non-plain-object `capabilities` on a contributor (including `undefined`,
64
+ * `null`, arrays, primitives) are skipped silently — the contributor
65
+ * contributes nothing.
66
+ * - Later contributors win on `(namespace, key)` collisions.
67
+ * - The returned object is fresh — neither `base` nor any contributor is mutated.
68
+ * - Output keys are sorted lexicographically at every plain-object level.
69
+ */
70
+ export function mergeCapabilityMatrices(
71
+ base: Record<string, Record<string, boolean>>,
72
+ contributors: ReadonlyArray<{ readonly capabilities?: unknown }>,
73
+ ): Record<string, Record<string, boolean>> {
74
+ const merged: CapabilityMatrix = extractCapabilityMatrix(base);
75
+
76
+ for (const contributor of contributors) {
77
+ const extracted = extractCapabilityMatrix(contributor.capabilities);
78
+ for (const [namespace, capabilities] of Object.entries(extracted)) {
79
+ merged[namespace] = {
80
+ ...(merged[namespace] ?? {}),
81
+ ...capabilities,
82
+ };
83
+ }
84
+ }
85
+
86
+ return blindCast<
87
+ CapabilityMatrix,
88
+ "sortDeep preserves the matrix shape but the recursive generic relationship can't be expressed to TS"
89
+ >(sortDeep(merged));
90
+ }