@prisma/orm-framework 8.0.0-rc.17-dev.26 → 8.0.0-rc.17-dev.28

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,1177 +0,0 @@
1
- import { G as PlanMeta } from "./domain-envelope-C2vVIWGK-C5x7cBpU.mjs";
2
- import { n as ContractExecutionSection } from "./contract-types-BIaUtO7Z-Bcxx2I74.mjs";
3
- import { a as CodecCallContext } from "./codec-types-CQNZE70G-DZIvCZwY.mjs";
4
- import { t as RuntimeErrorEnvelope } from "./runtime-error-CO4MA3Px-YW5SCUcH.mjs";
5
- //#region ../../../1-framework/1-core/framework-components/dist/runtime.d.mts
6
- //#region src/annotations.d.ts
7
- /**
8
- * The kinds of operations an annotation may apply to.
9
- *
10
- * - `'read'` — `SELECT` / `find` / `first` / `all` / `count` / aggregates.
11
- * - `'write'` — `INSERT` / `UPDATE` / `DELETE` / `create` / `update` / `delete` / `upsert`.
12
- *
13
- * Annotations declare which kinds they apply to via `defineAnnotation`'s
14
- * `applicableTo` option; lane terminals enforce the constraint at both the
15
- * type level (via `ValidAnnotations`) and at runtime (via
16
- * `assertAnnotationsApplicable`).
17
- *
18
- * Finer-grained kinds (`'select' | 'insert' | 'update' | 'delete' | 'upsert'`)
19
- * are deliberately deferred. The binary covers the common case (the cache
20
- * middleware applies to reads; an audit annotation would apply to writes;
21
- * tracing/OTel applies to both). When a real annotation surfaces that needs
22
- * a finer split, the union widens and existing handles remain typecheckable.
23
- */
24
- type OperationKind = 'read' | 'write';
25
- /**
26
- * An applied annotation. Carries the namespace, the typed payload, and the
27
- * `applicableTo` set the underlying handle declared. The `__annotation`
28
- * brand lets `read` distinguish branded user annotations from arbitrary
29
- * data that may happen to live under the same namespace key in
30
- * `plan.meta.annotations` (e.g. framework-internal metadata such as
31
- * `meta.annotations.codecs`).
32
- *
33
- * Constructed by calling an `AnnotationHandle` directly (e.g.
34
- * `cacheAnnotation({ ttl: 60 })`); never instantiated by hand.
35
- */
36
- interface AnnotationValue<Payload, Kinds extends OperationKind> {
37
- readonly __annotation: true;
38
- readonly namespace: string;
39
- readonly value: Payload;
40
- readonly applicableTo: ReadonlySet<Kinds>;
41
- }
42
- /**
43
- * Handle returned by `defineAnnotation`. The handle is **callable**: the
44
- * call signature wraps a `Payload` into an `AnnotationValue` ready to
45
- * pass to a lane terminal's variadic `annotations` argument. The handle
46
- * also carries static metadata as own properties:
47
- *
48
- * - `namespace` — the namespace string the handle was declared with.
49
- * - `applicableTo` — the frozen `ReadonlySet<Kinds>` consumed by both
50
- * the type-level `ValidAnnotations` gate and the runtime
51
- * `assertAnnotationsApplicable` gate.
52
- * - `read(plan)` — extract the `Payload` from a plan's `meta.annotations`
53
- * if a value was previously written under this handle's namespace.
54
- * Returns `undefined` when the annotation is absent or when the stored
55
- * value is not a branded `AnnotationValue` (e.g. framework-internal
56
- * metadata under the same namespace key).
57
- *
58
- * Handles are the only supported public entry point for reading and
59
- * writing annotations. Direct mutation of `plan.meta.annotations` is not
60
- * part of the public API.
61
- *
62
- * ```typescript
63
- * const cacheAnnotation = defineAnnotation<{ ttl: number }>()({
64
- * namespace: 'cache',
65
- * applicableTo: ['read'],
66
- * });
67
- *
68
- * // Call the handle to construct a value:
69
- * const applied = cacheAnnotation({ ttl: 60 });
70
- *
71
- * // Read a stored value off a plan:
72
- * const payload = cacheAnnotation.read(plan);
73
- * ```
74
- *
75
- * Note on the inherited `Function.prototype.apply`: because the handle is
76
- * a function, the property name `apply` resolves to JavaScript's built-in
77
- * `Function.prototype.apply` (which lets you invoke a function with an
78
- * array of arguments). This is **not** the construction entry point — to
79
- * build an `AnnotationValue`, call the handle directly. The
80
- * `AnnotationHandle` interface deliberately does not declare an `apply`
81
- * member of its own.
82
- */
83
- interface AnnotationHandle<Payload, Kinds extends OperationKind> {
84
- (value: Payload): AnnotationValue<Payload, Kinds>;
85
- readonly namespace: string;
86
- readonly applicableTo: ReadonlySet<Kinds>;
87
- read(plan: {
88
- readonly meta: {
89
- readonly annotations?: Record<string, unknown>;
90
- };
91
- }): Payload | undefined;
92
- }
93
- /**
94
- * Options accepted by `defineAnnotation`.
95
- *
96
- * `namespace` is the string key under which the annotation is stored in
97
- * `plan.meta.annotations`. **Reserved namespaces** include framework-
98
- * internal metadata keys; user handles must not use them:
99
- *
100
- * - `codecs` — used by the SQL emitter to record per-alias codec ids
101
- * (`meta.annotations.codecs[alias] = 'pg/text@1'`); the SQL runtime's
102
- * `decodeRow` reads from this key. A user `defineAnnotation('codecs')`
103
- * handle is not structurally prevented, but its behavior with the
104
- * emitter and the runtime is undefined and we make no compatibility
105
- * guarantees about it.
106
- * - Target-specific keys such as `pg` (and equivalents on other
107
- * targets) are similarly reserved for adapter / target use.
108
- *
109
- * `applicableTo` declares which operation kinds the annotation may attach
110
- * to. The lane terminals' type-level `ValidAnnotations<K, As>` gate rejects
111
- * annotations whose `Kinds` does not include the terminal's `K`; the
112
- * runtime helper `assertAnnotationsApplicable` does the equivalent at
113
- * runtime so casts and `any` cannot bypass the gate.
114
- */
115
- interface DefineAnnotationOptions<Kinds extends OperationKind> {
116
- readonly namespace: string;
117
- readonly applicableTo: readonly Kinds[];
118
- }
119
- /**
120
- * Defines a typed annotation handle.
121
- *
122
- * Two-step call form. The first step takes the `Payload` type argument
123
- * (TypeScript cannot infer `Payload` from anything in the options, so it
124
- * must be supplied explicitly); the second step takes the runtime options
125
- * and infers `Kinds` from the `applicableTo` array via a `const` type
126
- * parameter, so the operation kinds appear exactly once at the call site.
127
- *
128
- * @example
129
- * ```typescript
130
- * // Read-only annotation. Lane terminals like `db.User.first(...)` accept
131
- * // it; `db.User.create(...)` rejects it at the type level.
132
- * const cacheAnnotation = defineAnnotation<{ ttl?: number; skip?: boolean }>()({
133
- * namespace: 'cache',
134
- * applicableTo: ['read'],
135
- * }); // Kinds inferred as 'read'
136
- *
137
- * // Write-only annotation. Mirror image.
138
- * const auditAnnotation = defineAnnotation<{ actor: string }>()({
139
- * namespace: 'audit',
140
- * applicableTo: ['write'],
141
- * }); // Kinds inferred as 'write'
142
- *
143
- * // Annotation applicable to both kinds (e.g. tracing).
144
- * const otelAnnotation = defineAnnotation<{ traceId: string }>()({
145
- * namespace: 'otel',
146
- * applicableTo: ['read', 'write'],
147
- * }); // Kinds inferred as 'read' | 'write'
148
- * ```
149
- *
150
- * **Reserved namespaces.** See `DefineAnnotationOptions.namespace` for the
151
- * list of framework-internal namespaces (`codecs`, target-specific keys).
152
- * `defineAnnotation` does not structurally prevent a user from naming a
153
- * reserved namespace, but the framework makes no compatibility guarantee
154
- * about handles that do.
155
- */
156
- declare function defineAnnotation<Payload>(): <const Kinds extends OperationKind>(options: DefineAnnotationOptions<Kinds>) => AnnotationHandle<Payload, Kinds>;
157
- /**
158
- * Type-level applicability gate consumed by lane terminals.
159
- *
160
- * Maps a tuple of `AnnotationValue`s to a tuple where each element either
161
- * keeps its annotation type (when the annotation's declared `Kinds`
162
- * includes the terminal's operation kind `K`) or resolves to `never`
163
- * (when the kinds are incompatible). A `never` element makes the entire
164
- * tuple unassignable, surfacing the mismatch as a type error at the call
165
- * site of the terminal.
166
- *
167
- * The SQL DSL builders constrain their variadic `...annotations`
168
- * parameter via `As & ValidAnnotations<K, As>`. **The intersection is
169
- * load-bearing** — see the note below. The ORM terminals deliberately
170
- * sidestep this trick by taking one annotation per `meta.annotate(...)`
171
- * call (no variadic-tuple inference involved), so `ValidAnnotations` is
172
- * consumed only by the SQL DSL today.
173
- *
174
- * @example
175
- * ```typescript
176
- * class SelectQuery<Row> {
177
- * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(
178
- * ...annotations: As & ValidAnnotations<'read', As>
179
- * ): SelectQuery<Row>;
180
- * }
181
- *
182
- * class InsertQuery<Row> {
183
- * annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(
184
- * ...annotations: As & ValidAnnotations<'write', As>
185
- * ): InsertQuery<Row>;
186
- * }
187
- *
188
- * db.users.select('id').annotate(cacheAnnotation({ ttl: 60 }));
189
- * // ✓ cacheAnnotation declares 'read'; SelectQuery.annotate requires 'read'.
190
- *
191
- * db.users.insert([{ name: 'Alice' }]).annotate(cacheAnnotation({ ttl: 60 }));
192
- * // ✗ cacheAnnotation declares 'read'; InsertQuery.annotate requires 'write'.
193
- * // Element resolves to `never` → tuple unassignable → type error.
194
- * ```
195
- *
196
- * **Why `As & ValidAnnotations<K, As>` and not `ValidAnnotations<K, As>`
197
- * alone.** TypeScript's variadic-tuple inference is too forgiving when
198
- * the parameter type refers to `As` only through `ValidAnnotations`: it
199
- * will pick an `As` that makes the call valid even when the gated tuple
200
- * would contain `never` for an inapplicable element. The intersection
201
- * pins `As` to the actual call-site tuple AND requires it to be
202
- * assignable to the gated form. A `never` element in the gated tuple
203
- * then collapses the corresponding intersection position to `never`,
204
- * and the inapplicable argument fails to assign — surfacing the mismatch
205
- * as a type error at the call site.
206
- *
207
- * The runtime helper `assertAnnotationsApplicable` covers the equivalent
208
- * check at runtime so casts and `any` cannot bypass this gate.
209
- */
210
- type ValidAnnotations<K extends OperationKind, As extends readonly AnnotationValue<unknown, OperationKind>[]> = { readonly [I in keyof As]: As[I] extends AnnotationValue<infer P, infer Kinds> ? K extends Kinds ? AnnotationValue<P, Kinds> : never : never; };
211
- /**
212
- * Runtime applicability gate. Throws `RUNTIME.ANNOTATION_INAPPLICABLE` if
213
- * any annotation in `annotations` declares an `applicableTo` set that does
214
- * not include `kind`. Used by lane terminals (SQL DSL builders' `.build()`,
215
- * ORM `Collection` terminals) to fail closed when the type-level
216
- * `ValidAnnotations` gate is bypassed via cast / `any` / dynamic
217
- * invocation.
218
- *
219
- * Passes silently on:
220
- * - empty arrays
221
- * - annotations whose `applicableTo` includes `kind`
222
- *
223
- * Throws on:
224
- * - any annotation whose `applicableTo` does not include `kind`. The
225
- * error names the offending annotation's `namespace` and the
226
- * `terminalName` so users can locate the misuse.
227
- *
228
- * @example
229
- * ```typescript
230
- * // Inside an ORM read terminal:
231
- * assertAnnotationsApplicable(annotations, 'read', 'first');
232
- * ```
233
- */
234
- declare function assertAnnotationsApplicable(annotations: readonly AnnotationValue<unknown, OperationKind>[], kind: OperationKind, terminalName: string): void;
235
- //#endregion
236
- //#region src/execution/async-iterable-result.d.ts
237
- declare class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {
238
- private readonly generator;
239
- private consumed;
240
- private consumedBy;
241
- private bufferedArrayPromise;
242
- constructor(generator: AsyncGenerator<Row, void, unknown>);
243
- [Symbol.asyncIterator](): AsyncIterator<Row>;
244
- toArray(): Promise<Row[]>;
245
- first(): Promise<Row | null>;
246
- firstOrThrow(): Promise<Row>;
247
- then<TResult1 = Row[], TResult2 = never>(onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
248
- }
249
- //#endregion
250
- //#region src/execution/query-plan.d.ts
251
- /**
252
- * Family-agnostic plan marker.
253
- *
254
- * Carries only `meta` (the family-agnostic plan metadata) and the optional
255
- * phantom `_row` parameter that lets type-level utilities recover the row
256
- * type from a plan value. SQL and Mongo extend this marker with their own
257
- * concrete shapes (`SqlQueryPlan`, `MongoQueryPlan`).
258
- *
259
- * `QueryPlan` is the *pre-lowering* marker — i.e. the surface a builder
260
- * produces before family-specific lowering turns it into an executable
261
- * plan (`ExecutionPlan`).
262
- */
263
- interface QueryPlan<Row = unknown> {
264
- readonly meta: PlanMeta;
265
- /**
266
- * Phantom property to carry the Row generic for type-level utilities.
267
- * Not set at runtime; used only for `ResultType` extraction.
268
- */
269
- readonly _row?: Row;
270
- }
271
- /**
272
- * Family-agnostic execution-plan marker.
273
- *
274
- * Extends `QueryPlan` with no additional structural fields — the marker
275
- * exists to nominally distinguish executable plans from pre-lowering plans
276
- * in the type system. Family-specific execution plans (`SqlExecutionPlan`,
277
- * `MongoExecutionPlan`) extend this marker with their concrete shapes
278
- * (e.g. `sql + params` for SQL, `wireCommand` for Mongo).
279
- */
280
- interface ExecutionPlan<Row = unknown> extends QueryPlan<Row> {}
281
- /**
282
- * Extracts the `Row` type from a plan via the phantom `_row` property.
283
- *
284
- * Works with any plan that extends `QueryPlan<Row>` — including
285
- * `ExecutionPlan<Row>`, `SqlQueryPlan<Row>`, `SqlExecutionPlan<Row>`,
286
- * `MongoQueryPlan<Row>`, and `MongoExecutionPlan<Row>`.
287
- *
288
- * The `_row` property must be present in the plan's static type for the
289
- * conditional to bind `R`; objects whose type lacks `_row` resolve to
290
- * `never`. Without the `keyof` guard, `extends { _row?: infer R }` would
291
- * silently match any object and infer `unknown`.
292
- *
293
- * Example: `type Row = ResultType<typeof plan>`.
294
- */
295
- type ResultType<P> = '_row' extends keyof P ? P extends {
296
- readonly _row?: infer R;
297
- } ? R : never : never;
298
- //#endregion
299
- //#region src/execution/runtime-middleware.d.ts
300
- interface RuntimeLog {
301
- info(event: unknown): void;
302
- warn(event: unknown): void;
303
- error(event: unknown): void;
304
- debug?(event: unknown): void;
305
- }
306
- /**
307
- * Per-operation context threaded through every middleware phase
308
- * (`beforeQuery`, `interceptQuery`, `onRow`, `afterQuery` for queries, and
309
- * `beforeExecute`, `interceptExecute`, `afterExecute` for executes). Allocated
310
- * once per runtime operation and shared by reference across all middleware in
311
- * the chain.
312
- *
313
- * - `signal` carries the per-operation `AbortSignal` -- the same reference
314
- * passed to the runtime call and the same reference threaded into the
315
- * per-call `CodecCallContext` (ADR 207). Middleware that wraps a
316
- * network-backed SDK forwards `ctx.signal` into that SDK to propagate caller
317
- * cancellation; pure-CPU middleware ignores it.
318
- *
319
- * Symmetric plumbing across all middleware phases is a deliberate choice: a
320
- * middleware that wraps a downstream observability hook or post-processor in
321
- * `afterQuery` / `afterExecute`, `interceptQuery` / `interceptExecute`, or
322
- * `onRow` needs the same cancellation reach as its before hook.
323
- */
324
- interface RuntimeMiddlewareContext {
325
- readonly contract: unknown;
326
- readonly mode: 'strict' | 'permissive';
327
- readonly now: () => number;
328
- readonly log: RuntimeLog;
329
- /**
330
- * Returns a stable string identifying the (storage, statement, params)
331
- * tuple of an execution. Two semantically equivalent executions return
332
- * the same string. Used by middleware that need per-execution identity
333
- * (caching, request coalescing).
334
- *
335
- * The family runtime owns the implementation:
336
- * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`
337
- * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`
338
- *
339
- * The method is `async` because the underlying digest helper
340
- * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`
341
- * primitive is asynchronous by design.
342
- *
343
- * The returned string is intended to be consumed directly as a `Map` key
344
- * — it is not (and should not be) further hashed by callers.
345
- */
346
- contentHash(exec: ExecutionPlan): Promise<string>;
347
- /**
348
- * Per-operation cancellation signal threaded through every selected
349
- * middleware phase. Middleware that wraps async work or downstream
350
- * cancellable primitives should observe this and abort early when the
351
- * consumer cancels.
352
- */
353
- readonly signal?: AbortSignal;
354
- /**
355
- * Identifies the queryable scope this operation is running under.
356
- *
357
- * - `'runtime'` — top-level `runtime.query(plan)` or `runtime.execute(plan)`.
358
- * The default scope used by the standard read/write paths.
359
- * - `'connection'` — `connection.query(plan)` or `connection.execute(plan)`
360
- * after `runtime.connection()` checked out a connection from the pool.
361
- * - `'transaction'` — `transaction.query(plan)` or
362
- * `transaction.execute(plan)` inside an explicit transaction, or an
363
- * operation routed through `withTransaction`.
364
- *
365
- * Middleware that should only act at the top level read this field to
366
- * bypass non-runtime scopes. The cache middleware uses it to skip
367
- * caching inside transactions (where read-after-write coherence is the
368
- * caller's expectation) and dedicated connections (where the user has
369
- * explicitly stepped outside the shared cache surface). Observers that
370
- * don't care about the scope can ignore the field.
371
- *
372
- * Family runtimes populate this at context-construction time per
373
- * scope. Existing middleware that ignore the field are unaffected.
374
- */
375
- readonly scope: 'runtime' | 'connection' | 'transaction';
376
- /**
377
- * Identity for one `query()` or `execute()` call. The runtime mints a fresh
378
- * value via `crypto.randomUUID()` when it constructs the per-operation
379
- * context, then threads that context through every hook in the selected
380
- * query or execute lifecycle. Every hook in one call therefore observes
381
- * the same `planExecutionId`; two calls for the same plan observe distinct
382
- * values. Use this to correlate observations across a single operation
383
- * (tracing, timing, audit). See ADR 220.
384
- */
385
- readonly planExecutionId: string;
386
- }
387
- interface AfterResultBase {
388
- readonly latencyMs: number;
389
- /**
390
- * Indicates which execution path was selected.
391
- *
392
- * - `'driver'` — the default. The result came from the underlying driver via
393
- * `runDriver` / `runQueryWithMiddleware` or
394
- * `runExecuteWithMiddleware`'s normal path.
395
- * - `'middleware'` — a `RuntimeMiddleware.interceptQuery` or
396
- * `RuntimeMiddleware.interceptExecute` hook selected the middleware
397
- * interception path. This includes both supplying the result directly and
398
- * completing with an interceptor error; the driver was not invoked.
399
- *
400
- * Observers (telemetry, lints, budgets) that need to distinguish between
401
- * driver-served and middleware-served executions read this field.
402
- * Observers that don't care can ignore it.
403
- */
404
- readonly source: 'driver' | 'middleware';
405
- }
406
- interface AfterQueryResult extends AfterResultBase {
407
- readonly rowCount: number;
408
- readonly completed: boolean;
409
- }
410
- type AfterExecuteResult = AfterResultBase & ({
411
- readonly stats: RuntimeStatementStats;
412
- readonly completed: true;
413
- } | {
414
- readonly completed: false;
415
- });
416
- interface AfterTransactionResult {
417
- readonly outcome: 'committed' | 'rolled-back' | 'unknown';
418
- }
419
- interface QueryInterceptResult {
420
- readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;
421
- }
422
- interface ExecuteInterceptResult {
423
- readonly stats: RuntimeStatementStats;
424
- }
425
- /**
426
- * Marker interface for family-specific param-ref mutators threaded into
427
- * `beforeQuery` or `beforeExecute` as the third argument. The framework treats
428
- * the mutator opaquely — it allocates and forwards the family's mutator
429
- * instance so the operation-specific middleware runners can stay
430
- * family-agnostic. SQL extends this with `SqlParamRefMutator` (over
431
- * `ParamRef`); Mongo extends this with `MongoParamRefMutator` (over
432
- * `MongoParamRef`).
433
- *
434
- * Extension authors target the family-specific mutator type, not this
435
- * marker.
436
- */
437
- declare const PARAM_REF_MUTATOR_BRAND: unique symbol;
438
- type ParamRefMutator = {
439
- readonly [PARAM_REF_MUTATOR_BRAND]?: never;
440
- };
441
- /**
442
- * Family-agnostic middleware SPI parameterized over the plan marker.
443
- *
444
- * `TPlan` defaults to the framework `QueryPlan` marker so a generic
445
- * middleware (e.g. cross-family telemetry) can be authored without
446
- * naming a family. Family-specific middleware (`SqlMiddleware`,
447
- * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.
448
- *
449
- * `TMutator` is the family-specific {@link ParamRefMutator} the runtime
450
- * threads into `beforeQuery(plan, ctx, params)` or
451
- * `beforeExecute(plan, ctx, params)` as a third argument. Existing
452
- * `(plan)` / `(plan, ctx)` middleware bodies continue to compile — TypeScript
453
- * permits assigning a function with fewer parameters to a function-typed slot
454
- * that declares more. The third arg is additive.
455
- */
456
- interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan, TMutator extends ParamRefMutator = ParamRefMutator> {
457
- readonly name: string;
458
- readonly familyId?: string;
459
- readonly targetId?: string;
460
- /**
461
- * Fires after the family runtime has produced a draft execution plan from
462
- * the AST, but before the family encodes parameter values to driver wire
463
- * format. Mutations applied via the family-specific `params` mutator are
464
- * visible to the subsequent encode step.
465
- *
466
- * Lifecycle position (SQL example):
467
- * `runBeforeCompile → lowerSqlPlan → beforeQuery → encodeParams → interceptQuery → driver query`.
468
- *
469
- * The `params` argument is a family-specific {@link ParamRefMutator}
470
- * scoped to the value slots of `ParamRef` nodes in the plan's AST.
471
- * Middleware that doesn't need to mutate params can ignore the argument;
472
- * existing `(plan)` / `(plan, ctx)` bodies stay compatible.
473
- *
474
- * `ctx.signal` carries the per-operation `AbortSignal`; middleware that
475
- * wraps a network SDK forwards it. Cooperative cancellation surfaces a
476
- * `RUNTIME.ABORTED { phase: 'beforeQuery' }` envelope promptly even when the
477
- * body ignores the signal.
478
- *
479
- * Intercept ordering: `interceptQuery` runs *after* this hook; an
480
- * interceptor that short-circuits the driver path still observes the
481
- * post-`beforeQuery`, fully-encoded plan. The trade-off is that any
482
- * `beforeQuery` SDK round-trips happen even when a downstream interceptor
483
- * would have skipped the driver entirely.
484
- */
485
- beforeQuery?(plan: TPlan, ctx: RuntimeMiddlewareContext, params?: TMutator): void | Promise<void>;
486
- /**
487
- * Optional short-circuit hook for query executions. Runs inside
488
- * `runQueryWithMiddleware`, after the orchestrator receives the lowered plan
489
- * and after the `beforeQuery` hook fires. Middleware run in registration
490
- * order; the first to return a non-`undefined` `QueryInterceptResult` wins,
491
- * and subsequent middleware's `interceptQuery` does not fire.
492
- *
493
- * On a hit, `beforeQuery` has already fired; `runDriver` and `onRow` are
494
- * skipped. `afterQuery` still fires with `source: 'middleware'`.
495
- *
496
- * Returning `undefined` (or omitting the hook entirely) signals passthrough
497
- * — execution proceeds through the normal driver path.
498
- *
499
- * Errors thrown inside `interceptQuery` are rethrown by
500
- * `runQueryWithMiddleware` as the original `Error` — no envelope is
501
- * guaranteed at this layer. Before rethrowing, `afterQuery` fires with
502
- * `completed: false` and `source: 'middleware'`. Errors thrown by
503
- * `afterQuery` during the error path remain swallowed (existing semantics,
504
- * unchanged).
505
- *
506
- * Used by middleware that need to short-circuit query execution and supply
507
- * rows directly: caching, mocks, rate limiting, circuit breaking.
508
- *
509
- * `rows` accepts both `Iterable` (arrays, sync generators) and `AsyncIterable`
510
- * (async generators). `for await` natively handles both via
511
- * `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the orchestrator
512
- * does not need to branch on the variant. Cached arrays in the cache
513
- * middleware are the common case; streaming variants support future use
514
- * cases like mock layers replaying recordings.
515
- *
516
- * Row shape is `Record<string, unknown>` — the same untyped shape `onRow`
517
- * receives. The SQL runtime decodes intercepted rows through its normal
518
- * codec pass, so interceptors cache and return raw (undecoded) rows.
519
- */
520
- interceptQuery?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<QueryInterceptResult | undefined>;
521
- onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
522
- afterQuery?(plan: TPlan, result: AfterQueryResult, ctx: RuntimeMiddlewareContext): Promise<void>;
523
- /**
524
- * Fires after the family runtime has produced a draft execution plan from
525
- * the AST, but before the family encodes parameter values to driver wire
526
- * format. Mutations applied via the family-specific `params` mutator are
527
- * visible to the subsequent encode step.
528
- *
529
- * Lifecycle position (SQL example):
530
- * `runBeforeCompile → lowerSqlPlan → beforeExecute → encodeParams → interceptExecute → driver execute`.
531
- *
532
- * The `params` argument is a family-specific {@link ParamRefMutator}
533
- * scoped to the value slots of `ParamRef` nodes in the plan's AST.
534
- * Middleware that doesn't need to mutate params can ignore the argument;
535
- * existing `(plan)` / `(plan, ctx)` bodies stay compatible.
536
- *
537
- * `ctx.signal` carries the per-operation `AbortSignal`; middleware that
538
- * wraps a network SDK forwards it. Cooperative cancellation surfaces a
539
- * `RUNTIME.ABORTED { phase: 'beforeExecute' }` envelope promptly even when
540
- * the body ignores the signal.
541
- *
542
- * Intercept ordering: `interceptExecute` runs *after* this hook; an
543
- * interceptor that short-circuits the driver path still observes the
544
- * post-`beforeExecute`, fully-encoded plan. The trade-off is that any
545
- * `beforeExecute` SDK round-trips happen even when a downstream interceptor
546
- * would have skipped the driver entirely.
547
- */
548
- beforeExecute?(plan: TPlan, ctx: RuntimeMiddlewareContext, params?: TMutator): void | Promise<void>;
549
- /**
550
- * Optional short-circuit hook for execute operations. Middleware run in
551
- * registration order; the first to return a non-`undefined`
552
- * `ExecuteInterceptResult` wins, and subsequent middleware's
553
- * `interceptExecute` does not fire.
554
- *
555
- * On a hit, `beforeExecute` has already fired; only the driver execute is
556
- * skipped. The statistics supplied in `stats` are returned eagerly; there is
557
- * no row stream and `onRow` is not fired. `afterExecute` still fires with
558
- * `source: 'middleware'`.
559
- *
560
- * Returning `undefined` (or omitting the hook entirely) signals passthrough
561
- * — execution proceeds through the normal driver path. Errors thrown inside
562
- * `interceptExecute` are rethrown by `runExecuteWithMiddleware` as the
563
- * original `Error`. Before rethrowing, `afterExecute` fires with
564
- * `completed: false`; errors thrown by `afterExecute` during the error path
565
- * remain swallowed.
566
- */
567
- interceptExecute?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<ExecuteInterceptResult | undefined>;
568
- afterExecute?(plan: TPlan, result: AfterExecuteResult, ctx: RuntimeMiddlewareContext): Promise<void>;
569
- /**
570
- * The query's last hook. Fires exactly once for every query whose before-hooks and parameter encoding succeeded, when the transaction enclosing the query has ended, with its outcome. Outside a transaction it fires when the query ends: `committed` when it completed, `unknown` when it failed or the caller stopped reading its rows. A query is inside a transaction when it is sent on the transaction or on its connection after the transaction has begun and before its `commit()` or `rollback()` is called. A query sent on the connection while the transaction is still beginning counts as outside, although the database may run it inside. Inside a transaction, a resolved commit reports `unknown` when one of the transaction's queries failed. When the transaction ends while the query still runs, this fires at the end, before the query's after-hook, with the transaction's outcome, which may not be the query's: the query may reach the database after the transaction ends and run outside it, and its own failure is not counted. Receives the same plan and context as `afterQuery` or `afterExecute`. The runner logs and swallows thrown errors.
571
- *
572
- * Inside a transaction the hooks run one after another while its connection is still checked out, so their time adds to how long it is held. The hook must not use the connection, and must not wait on a connection from the same pool, for example by awaiting a query through the same runtime. A write it sends through the same runtime gets its own `afterTransaction`.
573
- */
574
- afterTransaction?(plan: TPlan, result: AfterTransactionResult, ctx: RuntimeMiddlewareContext): Promise<void>;
575
- }
576
- /**
577
- * Cross-family middleware — one that doesn't constrain `familyId` or
578
- * `targetId` and is therefore compatible with any family runtime's
579
- * middleware array (`SqlMiddleware[]`, `MongoMiddleware[]`, etc.).
580
- *
581
- * The intersection `RuntimeMiddleware & { familyId?: undefined; targetId?: undefined }`
582
- * pins both optional properties to exactly `undefined` (intersecting
583
- * `string | undefined` with `undefined` collapses to `undefined`). Under
584
- * `exactOptionalPropertyTypes: true`, the plain `RuntimeMiddleware` shape
585
- * — with `familyId?: string` — is *not* assignable to `SqlMiddleware`
586
- * (which narrows `familyId?: 'sql'`) because `string` is wider than
587
- * `'sql'`. Pinning the property to `undefined` makes the value a subtype
588
- * of every narrowed variant: `undefined` extends both `'sql' | undefined`
589
- * and `'mongo' | undefined`, so a `CrossFamilyMiddleware` value drops
590
- * into a SQL or Mongo middleware slot without a cast.
591
- *
592
- * Cross-family middleware factories (`createCacheMiddleware`, future
593
- * `audit` / OTel middleware) declare this as their return type so the
594
- * cross-family typing is named once rather than re-spelled at every call
595
- * site.
596
- */
597
- type CrossFamilyMiddleware<TPlan extends QueryPlan = QueryPlan> = RuntimeMiddleware<TPlan> & {
598
- readonly familyId?: undefined;
599
- readonly targetId?: undefined;
600
- };
601
- /**
602
- * Optional per-operation options accepted by every family runtime.
603
- *
604
- * `signal` is the per-operation cancellation signal. The runtime threads it
605
- * through middleware and codec calls; query row streams stop with
606
- * `RUNTIME.ABORTED` when the caller aborts. Omitting the option (or passing
607
- * `undefined`) preserves today's behavior bit-for-bit.
608
- */
609
- interface RuntimeExecuteOptions {
610
- readonly signal?: AbortSignal;
611
- readonly scope?: 'runtime' | 'connection' | 'transaction';
612
- }
613
- /**
614
- * Cross-family SPI for any runtime that can query or execute plans and be shut down.
615
- * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,
616
- * Mongo structurally (due to its phantom Row parameter using a unique symbol).
617
- *
618
- * The `_row` intersection on `query` connects the `Row` type parameter to the
619
- * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.
620
- */
621
- interface RuntimeStatementStats {
622
- readonly affectedRows: number;
623
- }
624
- interface RuntimeExecutor<TPlan extends QueryPlan> {
625
- query<Row>(plan: TPlan & {
626
- readonly _row?: Row;
627
- }, options?: RuntimeExecuteOptions): AsyncIterableResult<Row>;
628
- execute(plan: TPlan, options?: RuntimeExecuteOptions): Promise<RuntimeStatementStats>;
629
- close(): Promise<void>;
630
- }
631
- declare function checkMiddlewareCompatibility(middleware: RuntimeMiddleware, runtimeFamilyId: string, runtimeTargetId: string): void;
632
- //#endregion
633
- //#region src/execution/before-execute-chain.d.ts
634
- /**
635
- * Runs every middleware's `beforeQuery` hook in registration order,
636
- * threading through the (optional) family-specific `paramsMutator`.
637
- *
638
- * Why this lives outside {@link runQueryWithMiddleware}: middleware that
639
- * mutates parameter values (e.g. cipherstash's bulk-encrypt SDK
640
- * round-trip) must run *before* the family runtime encodes those
641
- * parameters to driver wire format. Family runtimes call
642
- * `runBeforeQueryChain` between the AST → plan lowering step and
643
- * the parameter encode step; the encode then observes the mutator's
644
- * `currentParams()` view. `runQueryWithMiddleware` retains the rest of
645
- * the query lifecycle (`interceptQuery`, driver/row source loop, `onRow`,
646
- * `afterQuery`) but no longer fires `beforeQuery` itself.
647
- *
648
- * Lifecycle within this helper:
649
- *
650
- * 1. For each middleware in registration order, if `beforeQuery`
651
- * is implemented:
652
- * - `checkAborted(ctx, 'beforeQuery')` short-circuits if the
653
- * caller already aborted at entry.
654
- * - The hook is invoked with `(plan, ctx, paramsMutator)`. A
655
- * middleware body that ignores the mutator stays compatible —
656
- * JavaScript allows extra positional arguments.
657
- * - If the hook returns a Promise, it is raced against
658
- * `ctx.signal` via {@link raceAgainstAbort} so cooperative
659
- * cancellation surfaces a `RUNTIME.ABORTED { phase:
660
- * 'beforeQuery' }` envelope even when the body itself
661
- * ignores the signal.
662
- *
663
- * Error propagation: any error thrown by a `beforeQuery` body
664
- * (or surfaced by the abort race) propagates out of this helper
665
- * unchanged. Family runtime entry points await this helper before invoking
666
- * `runQueryWithMiddleware`, so a rejection prevents the runner and its
667
- * `afterQuery` hook from running.
668
- *
669
- * Relationship to {@link runQueryWithMiddleware}: the framework's
670
- * `RuntimeCore.query` template calls this helper between
671
- * `lower(plan)` and `runQueryWithMiddleware(...)`. Family runtimes that
672
- * override query preparation (e.g. SQL, which inlines lower + encode for
673
- * direct mutator threading) call this helper themselves at the
674
- * equivalent point — between the family's AST → draft-plan
675
- * lowering and the parameter-encode step.
676
- *
677
- * Intercept ordering: this helper fires unconditionally before
678
- * `runQueryWithMiddleware`. `interceptQuery` (inside
679
- * `runQueryWithMiddleware`) therefore observes the post-`beforeQuery`
680
- * plan — mutator mutations are visible in the params interceptors see.
681
- * The trade-off is documented on `RuntimeMiddleware.interceptQuery`.
682
- */
683
- declare function runBeforeQueryChain<TExec extends ExecutionPlan, TMutator extends ParamRefMutator = ParamRefMutator>(plan: TExec, middleware: ReadonlyArray<RuntimeMiddleware<TExec, TMutator>>, ctx: RuntimeMiddlewareContext, paramsMutator?: TMutator): Promise<void>;
684
- /**
685
- * Runs every middleware's `beforeExecute` hook in registration order,
686
- * threading through the (optional) family-specific `paramsMutator`.
687
- *
688
- * Why this lives outside {@link runExecuteWithMiddleware}: middleware that
689
- * mutates parameter values (e.g. cipherstash's bulk-encrypt SDK
690
- * round-trip) must run *before* the family runtime encodes those
691
- * parameters to driver wire format. Family runtimes call
692
- * `runBeforeExecuteChain` between the AST → plan lowering step and
693
- * the parameter encode step; the encode then observes the mutator's
694
- * `currentParams()` view. `runExecuteWithMiddleware` retains the rest of
695
- * the execute lifecycle (`interceptExecute`, driver statistics execution,
696
- * `afterExecute`) but no longer fires `beforeExecute` itself.
697
- *
698
- * Lifecycle within this helper:
699
- *
700
- * 1. For each middleware in registration order, if `beforeExecute`
701
- * is implemented:
702
- * - `checkAborted(ctx, 'beforeExecute')` short-circuits if the
703
- * caller already aborted at entry.
704
- * - The hook is invoked with `(plan, ctx, paramsMutator)`. A
705
- * middleware body that ignores the mutator stays compatible —
706
- * JavaScript allows extra positional arguments.
707
- * - If the hook returns a Promise, it is raced against
708
- * `ctx.signal` via {@link raceAgainstAbort} so cooperative
709
- * cancellation surfaces a `RUNTIME.ABORTED { phase:
710
- * 'beforeExecute' }` envelope even when the body itself
711
- * ignores the signal.
712
- *
713
- * Error propagation: any error thrown by a `beforeExecute` body
714
- * (or surfaced by the abort race) propagates out of this helper
715
- * unchanged. Family runtime entry points await this helper before invoking
716
- * `runExecuteWithMiddleware`, so a rejection prevents the runner and its
717
- * `afterExecute` hook from running.
718
- *
719
- * Relationship to {@link runExecuteWithMiddleware}: the framework's
720
- * `RuntimeCore.execute` template calls this helper between
721
- * `lower(plan)` and `runExecuteWithMiddleware(...)`. Family runtimes that
722
- * override execute (e.g. SQL, which inlines lower + encode for
723
- * direct mutator threading) call this helper themselves at the
724
- * equivalent point — between the family's AST → draft-plan
725
- * lowering and the parameter-encode step.
726
- *
727
- * Intercept ordering: this helper fires unconditionally before
728
- * `runExecuteWithMiddleware`. `interceptExecute` (inside
729
- * `runExecuteWithMiddleware`) therefore observes the post-`beforeExecute`
730
- * plan — mutator mutations are visible in the params interceptors see.
731
- * The trade-off is documented on `RuntimeMiddleware.interceptExecute`.
732
- */
733
- declare function runBeforeExecuteChain<TExec extends ExecutionPlan, TMutator extends ParamRefMutator = ParamRefMutator>(plan: TExec, middleware: ReadonlyArray<RuntimeMiddleware<TExec, TMutator>>, ctx: RuntimeMiddlewareContext, paramsMutator?: TMutator): Promise<void>;
734
- //#endregion
735
- //#region src/execution/mutation-defaults.d.ts
736
- /**
737
- * Scope across which a generator's value is constant.
738
- *
739
- * - `'field'` — one value per defaulting site (one field of one record). Cache strategy: no cache; call per defaulting site. Right for per-record identifiers (UUIDs, CUIDs, ULIDs, nanoid, ksuid).
740
- * - `'row'` — one value across all defaulting sites of one record of one operation. Cache strategy: per-call cache keyed by generator id. Right for correlation ids stamped into several fields of one record.
741
- * - `'query'` — one value across all records and fields of one ORM operation. Cache strategy: caller-provided cache keyed by generator id. Right for `timestampNow` (a single timestamp per bulk create or update).
742
- */
743
- type GeneratorStability = 'field' | 'row' | 'query';
744
- interface RuntimeMutationDefaultGenerator {
745
- readonly id: string;
746
- readonly generate: (params?: Record<string, unknown>) => unknown;
747
- /**
748
- * Scope across which the generator's value is constant. The framework derives the cache strategy from this declaration; generator authors never need to know about cache keys. See `GeneratorStability` for the per-value semantics.
749
- */
750
- readonly stability: GeneratorStability;
751
- }
752
- /** A runtime component (target, adapter, or extension) that may contribute generators. */
753
- interface MutationDefaultGeneratorContributor {
754
- readonly id: string;
755
- readonly mutationDefaultGenerators?: () => ReadonlyArray<RuntimeMutationDefaultGenerator>;
756
- }
757
- type MutationDefaultsOp = 'create' | 'update';
758
- interface MutationDefaultsOptions {
759
- readonly op: MutationDefaultsOp;
760
- /** Required: refs are namespace-scoped, so only defaults of `(namespace, entry)` apply, which tells same-named entries in different namespaces apart. */
761
- readonly namespace: string;
762
- readonly entry: string;
763
- /** The values the caller writes. A key present here is explicit, whatever its value, and gets no default. */
764
- readonly values: Readonly<Record<string, unknown>>;
765
- /** Cache shared by the calls of one ORM operation, for `'query'`-stable generators. */
766
- readonly defaultValueCache?: Map<string, unknown>;
767
- }
768
- interface AppliedMutationDefault {
769
- readonly field: string;
770
- readonly value: unknown;
771
- }
772
- interface MutationDefaults {
773
- applyMutationDefaults(options: MutationDefaultsOptions): ReadonlyArray<AppliedMutationDefault>;
774
- }
775
- /** Registers every generator the contributors provide, by id. Two contributors providing one id is an error naming both. */
776
- declare function collectMutationDefaultGenerators(contributors: ReadonlyArray<MutationDefaultGeneratorContributor>): ReadonlyMap<string, RuntimeMutationDefaultGenerator>;
777
- /** Fails when the contract's mutation defaults name a generator the registry does not hold, listing every missing id and the fields that need it. */
778
- declare function assertMutationDefaultGeneratorsAvailable(execution: ContractExecutionSection | undefined, generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>): void;
779
- /**
780
- * The defaults to write for one record: for each mutation default of the entry and namespace whose phase matches `op`, the generated value of every field the values do not carry. An update with no keys gets none.
781
- */
782
- declare function applyMutationDefaults(execution: ContractExecutionSection | undefined, generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>, options: MutationDefaultsOptions): ReadonlyArray<AppliedMutationDefault>;
783
- //#endregion
784
- //#region src/execution/runtime-error.d.ts
785
- /**
786
- * Stable code emitted by the runtime when an in-flight `execute()`
787
- * is cancelled via the per-query `AbortSignal`. The envelope's
788
- * `details.phase` distinguishes where the abort was observed:
789
- *
790
- * - `'encode'` — abort fired during `encodeParams` (SQL) or
791
- * `resolveValue` (Mongo).
792
- * - `'decode'` — abort fired during `decodeRow` / `decodeField`.
793
- * - `'stream'` — abort fired between rows or before any codec call
794
- * (already-aborted at entry).
795
- * - `'beforeQuery'` / `'beforeExecute'` / `'afterQuery'` /
796
- * `'afterExecute'` / `'onRow'` — abort fired on entry to or during
797
- * the corresponding middleware phase
798
- * (cooperative cancellation per the param-transform seam).
799
- */
800
- declare const RUNTIME_ABORTED: "RUNTIME.ABORTED";
801
- /** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */
802
- type RuntimeAbortedPhase = 'encode' | 'decode' | 'stream' | 'beforeQuery' | 'beforeExecute' | 'afterQuery' | 'afterExecute' | 'onRow';
803
- /**
804
- * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the
805
- * abort was observed — codec call sites (`encode` / `decode` / `stream`)
806
- * or operation-specific middleware seams, as
807
- * enumerated on {@link RuntimeAbortedPhase}. Cause carries
808
- * `signal.reason` verbatim from the platform — native abort produces a
809
- * `DOMException`, explicit `controller.abort(reason)` produces whatever
810
- * the caller passed. No synthesis happens here.
811
- */
812
- declare function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope;
813
- //#endregion
814
- //#region src/execution/race-against-abort.d.ts
815
- /**
816
- * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied
817
- * context is already aborted at the precheck site. Centralises the
818
- * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that
819
- * every codec dispatch site (and the `beforeExecute` middleware phase)
820
- * repeats. Accepts both the framework `CodecCallContext` and the
821
- * `RuntimeMiddlewareContext`; both expose `signal?: AbortSignal`.
822
- */
823
- declare function checkAborted(ctx: {
824
- readonly signal?: AbortSignal;
825
- }, phase: RuntimeAbortedPhase): void;
826
- /**
827
- * Race a per-cell `Promise.all` (or any other in-flight work promise) against
828
- * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly
829
- * even when codec bodies ignore the signal. In-flight bodies that ignore the
830
- * signal are abandoned and run to completion in the background — the
831
- * cooperative-cancellation contract documented in ADR 204.
832
- *
833
- * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with
834
- * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —
835
- * that path is the canonical "aborted at entry" surface and avoids
836
- * scheduling the work promise. As a defensive belt-and-braces, this helper
837
- * also handles the already-aborted case internally: `AbortSignal` does not
838
- * replay past abort events to listeners registered after the abort, so we
839
- * inspect `signal.aborted` synchronously and reject with the sentinel
840
- * before installing the listener. The rejection is still attributed to the
841
- * abort path via the sentinel-identity check.
842
- *
843
- * Distinguishing the rejection source is load-bearing for AC-ERR4
844
- * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).
845
- * The semantically equivalent `abortable(signal)` helper in
846
- * `@internal/utils` rejects with `signal.reason ?? new DOMException(...)`,
847
- * which is not stably distinguishable from a codec-thrown error by identity
848
- * alone (a fresh fallback DOMException is allocated per call). We instead
849
- * track abort attribution with a unique sentinel: only the `onAbort` listener
850
- * installed here ever rejects with the sentinel, so an `error === sentinel`
851
- * identity check after the race is unambiguous.
852
- *
853
- * Lives in `framework-components` (rather than the SQL family, where it
854
- * originated in m2) so every family runtime that needs cooperative
855
- * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode
856
- * today, Mongo encode in m3) shares the same attribution logic.
857
- */
858
- declare function raceAgainstAbort<T>(work: Promise<T>, signal: AbortSignal | undefined, phase: RuntimeAbortedPhase): Promise<T>;
859
- //#endregion
860
- //#region src/execution/run-with-middleware.d.ts
861
- /**
862
- * Drives a single query execution of `runDriver()` through the middleware
863
- * lifecycle's `interceptQuery` + row-source + termination phases.
864
- *
865
- * Lifecycle, in order:
866
- * 1. For each middleware in registration order: `interceptQuery(exec, ctx)`.
867
- * The first non-`undefined` result wins; subsequent middleware's
868
- * `interceptQuery` does not fire. On a hit, the runtime emits a
869
- * `middleware.interceptQuery` debug event naming the winning middleware,
870
- * switches the row source to the intercepted rows, and proceeds with
871
- * `source: 'middleware'`. On all-passthrough (every `interceptQuery`
872
- * returns `undefined` or is omitted), `source: 'driver'` is used and the
873
- * row source is `runDriver()`.
874
- * 2. Iterate the row source. On the driver path, for each row, for each
875
- * middleware in registration order: `onRow(row, exec, ctx)`; then yield
876
- * the row. On the intercepted hit path, `onRow` is skipped — intercepted
877
- * rows did not originate from a driver row stream — but rows are still
878
- * yielded to the consumer in order.
879
- * 3. On successful completion: for each middleware in registration order:
880
- * `afterQuery(exec, { rowCount, latencyMs, completed: true, source },
881
- * ctx)`.
882
- * 4. On any error thrown during steps 1–2: for each middleware in
883
- * registration order: `afterQuery(exec, { rowCount, latencyMs,
884
- * completed: false, source }, ctx)`. Errors thrown by `afterQuery`
885
- * during the error path are swallowed so they do not mask the original
886
- * error. The original error is then rethrown.
887
- *
888
- * `beforeQuery` is **not** fired here — see
889
- * {@link runBeforeQueryChain} in `before-execute-chain.ts`. Family runtimes
890
- * call that helper between the AST → plan lowering step and the parameter
891
- * encode step so middleware that mutates ParamRef values can have its
892
- * mutations visible to encode. `runQueryWithMiddleware` operates on the
893
- * fully-encoded plan; interceptors therefore observe a fully-mutated,
894
- * encoded plan.
895
- *
896
- * The `source` field on `AfterQueryResult` lets observers (telemetry, lints,
897
- * budgets) distinguish driver-served from middleware-served executions
898
- * without needing their own out-of-band signal.
899
- *
900
- * This helper is the single canonical implementation of the
901
- * intercept-and-row-source loop; family runtimes should not reimplement it.
902
- */
903
- declare function runQueryWithMiddleware<TExec extends ExecutionPlan, Row>(exec: TExec, middleware: ReadonlyArray<RuntimeMiddleware<TExec>>, ctx: RuntimeMiddlewareContext, runDriver: () => AsyncIterable<Row>): AsyncIterableResult<Row>;
904
- /**
905
- * Drives a single execute operation through the middleware
906
- * `interceptExecute` + statistics + termination phases.
907
- *
908
- * Lifecycle, in order:
909
- * 1. For each middleware in registration order: `interceptExecute(exec, ctx)`.
910
- * The first non-`undefined` result wins; subsequent middleware's
911
- * `interceptExecute` does not fire. On a hit, the runtime emits a
912
- * `middleware.interceptExecute` debug event naming the winning middleware,
913
- * uses the returned `stats`, and proceeds with `source: 'middleware'`.
914
- * On all-passthrough (every `interceptExecute` returns `undefined` or is
915
- * omitted), `source: 'driver'` is used and `runDriver()` supplies the
916
- * statistics.
917
- * 2. Execute operations return eager statistics. There is no row stream and
918
- * `onRow` does not fire.
919
- * 3. On successful completion: for each middleware in registration order:
920
- * `afterExecute(exec, { stats, latencyMs, completed: true, source }, ctx)`.
921
- * 4. On any error thrown during steps 1–2: for each middleware in
922
- * registration order: `afterExecute(exec, { latencyMs, completed: false,
923
- * source }, ctx)`. Errors thrown by `afterExecute` during the error path
924
- * are swallowed so they do not mask the original error. The original
925
- * error is then rethrown.
926
- *
927
- * `beforeExecute` is **not** fired here — see
928
- * {@link runBeforeExecuteChain} in `before-execute-chain.ts`. Family runtimes
929
- * call that helper between the AST → plan lowering step and the parameter
930
- * encode step so middleware that mutates ParamRef values can have its
931
- * mutations visible to encode. `runExecuteWithMiddleware` operates on the
932
- * fully-encoded plan; interceptors therefore observe a fully-mutated,
933
- * encoded plan.
934
- *
935
- * The `source` field on `AfterExecuteResult` lets observers (telemetry, lints,
936
- * budgets) distinguish driver-served from middleware-served executions
937
- * without needing their own out-of-band signal.
938
- */
939
- declare function runExecuteWithMiddleware<TExec extends ExecutionPlan>(exec: TExec, middleware: ReadonlyArray<RuntimeMiddleware<TExec>>, ctx: RuntimeMiddlewareContext, runDriver: () => Promise<RuntimeStatementStats>): Promise<RuntimeStatementStats>;
940
- /**
941
- * Calls each middleware's `afterTransaction` hook in registration order. A
942
- * thrown error is passed to `ctx.log.error` and swallowed, and later
943
- * middleware still run. Never rejects, so a query's result or a resolved
944
- * commit is never replaced by a hook's failure.
945
- */
946
- declare function runAfterTransaction<TExec extends ExecutionPlan>(exec: TExec, middleware: ReadonlyArray<RuntimeMiddleware<TExec>>, result: AfterTransactionResult, ctx: RuntimeMiddlewareContext): Promise<void>;
947
- /** How a query ended: its rows or statistics all arrived, an error came out of it, or the caller stopped reading its rows. */
948
- type QueryEnding = 'completed' | 'failed' | 'stopped';
949
- /**
950
- * Returns what a query outside a transaction calls when it ends: it runs `runStage` with `committed` when the query completed and `unknown` otherwise. Returns `undefined` when `runStage` is `undefined`.
951
- */
952
- declare function onQueryEndOutsideTransaction(runStage: ((result: AfterTransactionResult) => Promise<void>) | undefined): ((ending: QueryEnding) => Promise<void>) | undefined;
953
- /**
954
- * Streams `rows()` and then calls `onQueryEnd` exactly once with how the query ended: `completed` when the stream completes, `failed` when an error comes out of it, and `stopped` when the caller stops reading, calls `return()` or throws into the iterator, before or after the first row. Returns `rows()` itself when `onQueryEnd` is `undefined`.
955
- */
956
- declare function reportQueryEnding<Row>(onQueryEnd: ((ending: QueryEnding) => Promise<void>) | undefined, rows: () => AsyncIterable<Row>): AsyncIterable<Row>;
957
- /**
958
- * Runs `execute()` and then calls `onQueryEnd` exactly once: with `completed` when it resolves, and with `failed` when it rejects.
959
- */
960
- declare function reportExecuteEnding<T>(onQueryEnd: ((ending: QueryEnding) => Promise<void>) | undefined, execute: () => Promise<T>): Promise<T>;
961
- //#endregion
962
- //#region src/execution/runtime-core.d.ts
963
- /**
964
- * Constructor options shared by every concrete `RuntimeCore` subclass.
965
- *
966
- * Family runtimes typically build the middleware list and the
967
- * `RuntimeMiddlewareContext` themselves (running compatibility checks,
968
- * narrowing the context's `contract` field, etc.) before calling `super`.
969
- */
970
- interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {
971
- readonly middleware: ReadonlyArray<TMiddleware>;
972
- readonly ctx: RuntimeMiddlewareContext;
973
- }
974
- /**
975
- * Family-agnostic abstract runtime base.
976
- *
977
- * Defines the shared operation-specific middleware lifecycles:
978
- *
979
- * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides
980
- * this to run its shared `beforeCompile` middleware-hook chain.
981
- * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`
982
- * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).
983
- * 3. Queries run `beforeQuery`; statements run `beforeExecute`. Both chains
984
- * run after lowering and before their matching driver terminal. Family
985
- * runtimes that expose a params mutator to downstream encoding override
986
- * the operation and call the matching helper at the pre-encode point.
987
- * 4. The matching runner processes `interceptQuery` or `interceptExecute`
988
- * before invoking the driver. Queries then fire `onRow` and `afterQuery`;
989
- * statements fire `afterExecute`.
990
- * 5. Every operation whose lowering (which encodes parameters) and before-hooks
991
- * succeeded fires `afterTransaction` once, as its last hook: `committed`
992
- * when it completed, `unknown` when it threw or the caller stopped reading
993
- * its rows. `reportQueryEnding` and `reportExecuteEnding` report how the
994
- * operation ended, and `onQueryEndOutsideTransaction` turns that into the
995
- * outcome; family runtimes that override `query` or `execute` call them
996
- * too, with {@link afterTransactionStageFor}.
997
- *
998
- * Concrete subclasses must implement `lower`, `runDriver`, `runExecute`, and
999
- * `close`.
1000
- *
1001
- * The class is generic over:
1002
- * - `TPlan` — the family's pre-lowering plan type.
1003
- * - `TExec` — the family's post-lowering (executable) plan type.
1004
- * - `TMiddleware` — the family's middleware type. Constrained to
1005
- * `RuntimeMiddleware<TExec>` because the operation-specific runners invoke
1006
- * hooks with the lowered `TExec`. Middleware therefore sees the
1007
- * post-lowering plan.
1008
- */
1009
- declare abstract class RuntimeCore<TPlan extends QueryPlan, TExec extends ExecutionPlan, TMiddleware extends RuntimeMiddleware<TExec>> implements RuntimeExecutor<TPlan> {
1010
- protected readonly middleware: ReadonlyArray<TMiddleware>;
1011
- protected readonly ctx: RuntimeMiddlewareContext;
1012
- protected readonly anyMiddlewareDeclaresAfterTransaction: boolean;
1013
- constructor(options: RuntimeCoreOptions<TMiddleware>);
1014
- /**
1015
- * Returns the function that runs every middleware's `afterTransaction` hook for one operation with a given result, or `undefined` when no middleware declared the hook when the runtime was created.
1016
- */
1017
- protected afterTransactionStageFor(exec: TExec, ctx: RuntimeMiddlewareContext): ((result: AfterTransactionResult) => Promise<void>) | undefined;
1018
- /**
1019
- * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses
1020
- * may override to run a `beforeCompile` middleware chain (SQL does this
1021
- * to support typed AST rewrites — see `before-compile-chain.ts`).
1022
- */
1023
- protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan>;
1024
- /**
1025
- * Lower a pre-lowering `TPlan` into the family's executable `TExec`.
1026
- * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo
1027
- * produces `{ command, ... }`.
1028
- *
1029
- * `ctx` carries per-operation cancellation (and any future fields on
1030
- * `CodecCallContext`); concrete subclasses forward it to the encode-side
1031
- * codec dispatch site. The runtime allocates one ctx per operation call
1032
- * and threads the same reference everywhere; the
1033
- * `signal` field inside may be `undefined`, but the ctx object itself
1034
- * is always present.
1035
- */
1036
- protected abstract lower(plan: TPlan, ctx: CodecCallContext): TExec | Promise<TExec>;
1037
- /**
1038
- * Drive the underlying transport for a lowered `TExec`. Yields raw rows
1039
- * directly from the driver as `Record<string, unknown>`; codec decoding
1040
- * (if any) is the subclass's responsibility, applied by wrapping
1041
- * `query()` rather than living inside this hook.
1042
- *
1043
- * The `Row` type parameter on `query()` is satisfied by the caller via
1044
- * the plan's phantom `_row`; the runtime treats rows as opaque records
1045
- * here and trusts the caller's row typing.
1046
- */
1047
- protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;
1048
- protected abstract runExecute(exec: TExec): Promise<RuntimeStatementStats>;
1049
- abstract close(): Promise<void>;
1050
- query<Row>(plan: TPlan & {
1051
- readonly _row?: Row;
1052
- }, options?: RuntimeExecuteOptions): AsyncIterableResult<Row>;
1053
- execute(plan: TPlan, options?: RuntimeExecuteOptions): Promise<RuntimeStatementStats>;
1054
- }
1055
- //#endregion
1056
- //#region src/execution/shape.d.ts
1057
- /**
1058
- * Phantom key an emitted model type carries to name its relation properties.
1059
- * Never present at runtime; `Scalars` and `Shape` read it to tell relations from fields.
1060
- */
1061
- declare const RelationKeys: unique symbol;
1062
- /**
1063
- * The relation names an emitted model type declares.
1064
- */
1065
- type RelationNamesOf<M> = Rel<M>;
1066
- /**
1067
- * Without `exactOptionalPropertyTypes` the optional phantom infers `R | undefined`, so the
1068
- * inferred type is filtered rather than constrained: `infer R extends string` would fall back to
1069
- * `string` there.
1070
- */
1071
- type Rel<M> = M extends {
1072
- readonly [RelationKeys]?: infer R;
1073
- } ? Extract<R, string> : never;
1074
- /**
1075
- * The scalar row of a model: every field, no relations, no phantom.
1076
- * Distributes over a union, so the row of a polymorphic `Any<Base>` is the union of its variants' rows.
1077
- */
1078
- type Scalars<M> = M extends {
1079
- readonly [RelationKeys]?: unknown;
1080
- } ? Omit<M, Rel<M> | typeof RelationKeys> : M;
1081
- /**
1082
- * An application data structure derived from a model.
1083
- *
1084
- * At every level of `Spec`: `'+'` names scalars and relations to keep, and narrows the scalars only
1085
- * when it names one; `'-'` names scalars to drop; any other key is a relation whose value is a spec
1086
- * that narrows the related model. A relation named in `'+'` comes with all of its scalars and none of
1087
- * its relations. Relations are absent unless asked for; cardinality and nullability come from the
1088
- * model. Distributes over a union, so each variant of `Any<Base>` keeps only its own relations.
1089
- */
1090
- type Shape<M, Spec extends ShapeSpec<M, Spec> = Record<never, never>> = ShapeOf<M, Spec>;
1091
- /**
1092
- * The constraint a `Shape` spec satisfies. A generic that forwards a spec needs it:
1093
- * `type Response<S extends ShapeSpec<User, S>> = Shape<User, S>`.
1094
- */
1095
- type ShapeSpec<M, Spec> = { readonly [K in keyof Spec]: K extends '+' ? Exclude<PlusNames<M, Spec>, keyof Spec> : K extends '-' ? ScalarNamesOf<M> : K extends RelationNamesOf<M> ? ShapeSpec<RelatedModel<M, K>, Spec[K]> : UnknownSpecKey<M, K>; };
1096
- type PlusNames<M, Spec> = '-' extends keyof Spec ? RelationNamesOf<M> : ScalarNamesOf<M> | RelationNamesOf<M>;
1097
- type UnknownSpecKey<M, K> = [RelationNamesOf<M>] extends [never] ? `'${K & string}' is not a relation of the model, which has none; try '+' or '-'` : `'${K & string}' is not a relation of the model; try '+', '-', or '${RelationNamesOf<M>}'`;
1098
- type ScalarNamesOf<M> = M extends unknown ? keyof Scalars<M> & string : never;
1099
- type RelatedModel<M, K> = M extends unknown ? K extends keyof M ? UnwrapRelation<M[K]> : never : never;
1100
- type UnwrapRelation<V> = V extends (infer Item)[] ? Item : NonNullable<V>;
1101
- type ShapeOf<M, Spec> = ShapeOfEach<M, Spec, PlusNamesAScalar<M, Spec>>;
1102
- type PlusNamesAScalar<M, Spec> = Spec extends {
1103
- readonly '+': infer Keep;
1104
- } ? [Extract<Keep, ScalarNamesOf<M>>] extends [never] ? false : true : false;
1105
- type ShapeOfEach<M, Spec, Narrow extends boolean> = M extends unknown ? Flatten<KeptScalars<M, Spec, Narrow> & { [K in IncludedRelations<M, Spec>]: WrapLike<M[K], ShapeOf<RelatedModel<M, K>, NestedSpec<Spec, K>>>; }> : never;
1106
- type KeptScalars<M, Spec, Narrow extends boolean> = Narrow extends true ? Spec extends {
1107
- readonly '+': infer Keep;
1108
- } ? Pick<Scalars<M>, Extract<Keep, keyof Scalars<M>>> : never : Spec extends {
1109
- readonly '-': infer Drop extends PropertyKey;
1110
- } ? Omit<Scalars<M>, Drop> : Scalars<M>;
1111
- type IncludedRelations<M, Spec> = Extract<keyof Spec | (Spec extends {
1112
- readonly '+': infer Keep;
1113
- } ? Keep : never), RelationNamesOf<M> & keyof M>;
1114
- type NestedSpec<Spec, K> = K extends keyof Spec ? Spec[K] : Record<never, never>;
1115
- type WrapLike<V, R> = V extends unknown[] ? R[] : null extends V ? R | null : R;
1116
- type Flatten<T> = { [K in keyof T]: T[K]; };
1117
- //#endregion
1118
- //#region src/meta-builder.d.ts
1119
- /**
1120
- * Per-terminal meta configurator handed to user callbacks. The terminal's
1121
- * operation kind `K` is fixed by the terminal that constructed the builder;
1122
- * `annotate(...)` accepts only annotations whose declared `Kinds` include
1123
- * `K`.
1124
- *
1125
- * The conditional parameter type
1126
- * `K extends Kinds ? AnnotationValue<P, Kinds> : never` collapses to `never`
1127
- * for inapplicable annotations, surfacing the mismatch as a type error at
1128
- * the call site of `meta.annotate(...)`. No variadic-tuple inference is
1129
- * involved — TypeScript infers `Kinds` from the annotation argument and
1130
- * checks the conditional directly.
1131
- *
1132
- * The runtime gate inside `annotate` (via
1133
- * `assertAnnotationsApplicable`) catches cast / `any` / dynamic bypasses
1134
- * and throws `RUNTIME.ANNOTATION_INAPPLICABLE`.
1135
- *
1136
- * `annotate` returns the builder for chaining; the return value of the
1137
- * configurator callback is unused, so both block-body and expression-body
1138
- * callbacks compile.
1139
- *
1140
- * @example
1141
- * ```typescript
1142
- * await db.User.find({ id }, (meta) => meta.annotate(cacheAnnotation({ ttl: 60 })));
1143
- * await db.User.create(input, (meta) => {
1144
- * meta.annotate(auditAnnotation({ actor: 'system' }));
1145
- * meta.annotate(otelAnnotation({ traceId }));
1146
- * });
1147
- * ```
1148
- */
1149
- interface MetaBuilder<K extends OperationKind> {
1150
- annotate<P, Kinds extends OperationKind>(annotation: K extends Kinds ? AnnotationValue<P, Kinds> : never): this;
1151
- }
1152
- /**
1153
- * Lane-side view of a meta builder. Extends the public `MetaBuilder<K>`
1154
- * surface with `annotations` so lane terminals can read the recorded map
1155
- * after invoking the user configurator.
1156
- *
1157
- * Lane terminals construct one of these via `createMetaBuilder(kind, terminalName)`,
1158
- * pass it to the user callback as `MetaBuilder<K>` (the narrower public
1159
- * view), then read `meta.annotations` to thread the recorded values into
1160
- * `plan.meta.annotations`.
1161
- */
1162
- interface LaneMetaBuilder<K extends OperationKind> extends MetaBuilder<K> {
1163
- readonly annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;
1164
- }
1165
- /**
1166
- * Construct a lane-side meta builder for a terminal of operation kind `K`.
1167
- *
1168
- * Lane terminals call this with their `kind` (`'read'` or `'write'`) and a
1169
- * `terminalName` for error messages, hand the resulting builder to the
1170
- * user-supplied configurator callback (typed as `MetaBuilder<K>`, the
1171
- * narrower public view), and read `meta.annotations` afterwards to thread
1172
- * the recorded values into `plan.meta.annotations`.
1173
- */
1174
- declare function createMetaBuilder<K extends OperationKind>(kind: K, terminalName: string): LaneMetaBuilder<K>;
1175
- //#endregion
1176
- export { reportQueryEnding as $, RuntimeCoreOptions as A, ShapeSpec as B, QueryPlan as C, ResultType as D, RelationNamesOf as E, RuntimeMiddlewareContext as F, checkAborted as G, applyMutationDefaults as H, RuntimeMutationDefaultGenerator as I, createMetaBuilder as J, checkMiddlewareCompatibility as K, RuntimeStatementStats as L, RuntimeExecutor as M, RuntimeLog as N, RuntimeAbortedPhase as O, RuntimeMiddleware as P, reportExecuteEnding as Q, Scalars as R, QueryInterceptResult as S, RelationKeys as T, assertAnnotationsApplicable as U, ValidAnnotations as V, assertMutationDefaultGeneratorsAvailable as W, onQueryEndOutsideTransaction as X, defineAnnotation as Y, raceAgainstAbort as Z, MutationDefaultsOp as _, AnnotationValue as a, runtimeAborted as at, ParamRefMutator as b, CrossFamilyMiddleware as c, ExecutionPlan as d, runAfterTransaction as et, GeneratorStability as f, MutationDefaults as g, MutationDefaultGeneratorContributor as h, AnnotationHandle as i, runQueryWithMiddleware as it, RuntimeExecuteOptions as j, RuntimeCore as k, DefineAnnotationOptions as l, MetaBuilder as m, AfterQueryResult as n, runBeforeQueryChain as nt, AppliedMutationDefault as o, LaneMetaBuilder as p, collectMutationDefaultGenerators as q, AfterTransactionResult as r, runExecuteWithMiddleware as rt, AsyncIterableResult as s, AfterExecuteResult as t, runBeforeExecuteChain as tt, ExecuteInterceptResult as u, MutationDefaultsOptions as v, RUNTIME_ABORTED as w, QueryEnding as x, OperationKind as y, Shape as z };
1177
- //# sourceMappingURL=runtime-CJ0h4apE.d.mts.map