@prisma-next/framework-components 0.5.0-dev.9 → 0.5.1

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.
Files changed (95) hide show
  1. package/README.md +51 -4
  2. package/dist/authoring.d.mts +2 -2
  3. package/dist/authoring.mjs +2 -122
  4. package/dist/codec-m_-FAyQn.d.mts +168 -0
  5. package/dist/codec-m_-FAyQn.d.mts.map +1 -0
  6. package/dist/codec.d.mts +48 -2
  7. package/dist/codec.d.mts.map +1 -0
  8. package/dist/codec.mjs +67 -4
  9. package/dist/codec.mjs.map +1 -1
  10. package/dist/components.d.mts +1 -1
  11. package/dist/components.mjs +2 -3
  12. package/dist/control.d.mts +421 -78
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +83 -58
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/emission-types-CMv_053d.d.mts +38 -0
  17. package/dist/emission-types-CMv_053d.d.mts.map +1 -0
  18. package/dist/emission.d.mts +2 -2
  19. package/dist/emission.mjs +1 -1
  20. package/dist/execution.d.mts +5 -5
  21. package/dist/execution.d.mts.map +1 -1
  22. package/dist/execution.mjs +4 -6
  23. package/dist/execution.mjs.map +1 -1
  24. package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-DGIQbNPt.d.mts} +43 -12
  25. package/dist/framework-authoring-DGIQbNPt.d.mts.map +1 -0
  26. package/dist/framework-authoring-DxXcjyJX.mjs +209 -0
  27. package/dist/framework-authoring-DxXcjyJX.mjs.map +1 -0
  28. package/dist/{framework-components-DFZMi2h7.d.mts → framework-components-CHuBHXQN.d.mts} +45 -58
  29. package/dist/framework-components-CHuBHXQN.d.mts.map +1 -0
  30. package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-FdqmlGUj.mjs} +3 -3
  31. package/dist/framework-components-FdqmlGUj.mjs.map +1 -0
  32. package/dist/psl-ast-Ckn_G-jv.d.mts +159 -0
  33. package/dist/psl-ast-Ckn_G-jv.d.mts.map +1 -0
  34. package/dist/psl-ast.d.mts +2 -0
  35. package/dist/psl-ast.mjs +1 -0
  36. package/dist/runtime.d.mts +273 -37
  37. package/dist/runtime.d.mts.map +1 -1
  38. package/dist/runtime.mjs +172 -30
  39. package/dist/runtime.mjs.map +1 -1
  40. package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-BxI5cSQy.d.mts} +2 -2
  41. package/dist/types-import-spec-BxI5cSQy.d.mts.map +1 -0
  42. package/package.json +12 -8
  43. package/src/control/control-capabilities.ts +96 -0
  44. package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
  45. package/src/{control-instances.ts → control/control-instances.ts} +52 -6
  46. package/src/{control-migration-types.ts → control/control-migration-types.ts} +251 -63
  47. package/src/control/control-operation-preview.ts +23 -0
  48. package/src/{control-result-types.ts → control/control-result-types.ts} +0 -2
  49. package/src/control/control-spaces.ts +82 -0
  50. package/src/{control-stack.ts → control/control-stack.ts} +77 -111
  51. package/src/control/emission-types.ts +48 -0
  52. package/src/control/psl-ast.ts +193 -0
  53. package/src/{execution-descriptors.ts → execution/execution-descriptors.ts} +7 -7
  54. package/src/{execution-instances.ts → execution/execution-instances.ts} +1 -1
  55. package/src/{execution-requirements.ts → execution/execution-requirements.ts} +1 -1
  56. package/src/execution/race-against-abort.ts +89 -0
  57. package/src/execution/run-with-middleware.ts +153 -0
  58. package/src/{runtime-core.ts → execution/runtime-core.ts} +27 -3
  59. package/src/execution/runtime-error.ts +94 -0
  60. package/src/execution/runtime-middleware.ts +235 -0
  61. package/src/exports/authoring.ts +5 -2
  62. package/src/exports/codec.ts +27 -2
  63. package/src/exports/components.ts +2 -2
  64. package/src/exports/control.ts +41 -14
  65. package/src/exports/emission.ts +2 -2
  66. package/src/exports/execution.ts +5 -5
  67. package/src/exports/psl-ast.ts +1 -0
  68. package/src/exports/runtime.ts +18 -9
  69. package/src/shared/codec-descriptor.ts +87 -0
  70. package/src/shared/codec-types.ts +79 -0
  71. package/src/shared/codec.ts +80 -0
  72. package/src/shared/column-spec.ts +83 -0
  73. package/src/{framework-authoring.ts → shared/framework-authoring.ts} +210 -23
  74. package/src/{framework-components.ts → shared/framework-components.ts} +22 -49
  75. package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +22 -2
  76. package/dist/authoring.mjs.map +0 -1
  77. package/dist/codec-types-DQ1Agjom.d.mts +0 -58
  78. package/dist/codec-types-DQ1Agjom.d.mts.map +0 -1
  79. package/dist/emission-types-BPAALJbF.d.mts +0 -24
  80. package/dist/emission-types-BPAALJbF.d.mts.map +0 -1
  81. package/dist/framework-authoring-D1-JZ37B.d.mts.map +0 -1
  82. package/dist/framework-components-C8ZhSwXe.mjs.map +0 -1
  83. package/dist/framework-components-DFZMi2h7.d.mts.map +0 -1
  84. package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
  85. package/src/codec-types.ts +0 -64
  86. package/src/control-capabilities.ts +0 -34
  87. package/src/emission-types.ts +0 -28
  88. package/src/run-with-middleware.ts +0 -77
  89. package/src/runtime-error.ts +0 -55
  90. package/src/runtime-middleware.ts +0 -87
  91. /package/src/{control-schema-view.ts → control/control-schema-view.ts} +0 -0
  92. /package/src/{async-iterable-result.ts → execution/async-iterable-result.ts} +0 -0
  93. /package/src/{execution-stack.ts → execution/execution-stack.ts} +0 -0
  94. /package/src/{query-plan.ts → execution/query-plan.ts} +0 -0
  95. /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
@@ -1,6 +1,7 @@
1
+ import { o as CodecCallContext } from "./codec-m_-FAyQn.mjs";
1
2
  import { PlanMeta } from "@prisma-next/contract/types";
2
3
 
3
- //#region src/async-iterable-result.d.ts
4
+ //#region src/execution/async-iterable-result.d.ts
4
5
  declare class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {
5
6
  private readonly generator;
6
7
  private consumed;
@@ -14,7 +15,7 @@ declare class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLik
14
15
  then<TResult1 = Row[], TResult2 = never>(onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
15
16
  }
16
17
  //#endregion
17
- //#region src/query-plan.d.ts
18
+ //#region src/execution/query-plan.d.ts
18
19
  /**
19
20
  * Family-agnostic plan marker.
20
21
  *
@@ -63,24 +64,209 @@ type ResultType<P> = '_row' extends keyof P ? P extends {
63
64
  readonly _row?: infer R;
64
65
  } ? R : never : never;
65
66
  //#endregion
66
- //#region src/runtime-middleware.d.ts
67
+ //#region src/execution/runtime-error.d.ts
68
+ interface RuntimeErrorEnvelope extends Error {
69
+ readonly code: string;
70
+ readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';
71
+ readonly severity: 'error';
72
+ readonly details?: Record<string, unknown>;
73
+ }
74
+ /**
75
+ * Stable code emitted by the runtime when an in-flight `execute()`
76
+ * is cancelled via the per-query `AbortSignal`. The envelope's
77
+ * `details.phase` distinguishes where the abort was observed:
78
+ *
79
+ * - `'encode'` — abort fired during `encodeParams` (SQL) or
80
+ * `resolveValue` (Mongo).
81
+ * - `'decode'` — abort fired during `decodeRow` / `decodeField`.
82
+ * - `'stream'` — abort fired between rows or before any codec call
83
+ * (already-aborted at entry).
84
+ * - `'beforeExecute'` / `'afterExecute'` / `'onRow'` — abort fired
85
+ * on entry to or during the corresponding middleware phase
86
+ * (cooperative cancellation per the param-transform seam).
87
+ */
88
+ declare const RUNTIME_ABORTED: "RUNTIME.ABORTED";
89
+ /** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */
90
+ type RuntimeAbortedPhase = 'encode' | 'decode' | 'stream' | 'beforeExecute' | 'afterExecute' | 'onRow';
91
+ /**
92
+ * Type guard for the runtime-error envelope produced by `runtimeError`.
93
+ *
94
+ * Prefer this over duck-typing on `error.code` directly so consumers stay
95
+ * insulated from the envelope's internal shape.
96
+ */
97
+ declare function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope;
98
+ declare function runtimeError(code: string, message: string, details?: Record<string, unknown>): RuntimeErrorEnvelope;
99
+ /**
100
+ * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the
101
+ * abort was observed — codec call sites (`encode` / `decode` / `stream`)
102
+ * or middleware seams (`beforeExecute` / `afterExecute` / `onRow`), as
103
+ * enumerated on {@link RuntimeAbortedPhase}. Cause carries
104
+ * `signal.reason` verbatim from the platform — native abort produces a
105
+ * `DOMException`, explicit `controller.abort(reason)` produces whatever
106
+ * the caller passed. No synthesis happens here.
107
+ */
108
+ declare function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope;
109
+ //#endregion
110
+ //#region src/execution/race-against-abort.d.ts
111
+ /**
112
+ * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied
113
+ * context is already aborted at the precheck site. Centralises the
114
+ * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that
115
+ * every codec dispatch site (and the `beforeExecute` middleware phase)
116
+ * repeats. Accepts both the framework `CodecCallContext` and the
117
+ * `RuntimeMiddlewareContext`; both expose `signal?: AbortSignal`.
118
+ */
119
+ declare function checkAborted(ctx: {
120
+ readonly signal?: AbortSignal;
121
+ }, phase: RuntimeAbortedPhase): void;
122
+ /**
123
+ * Race a per-cell `Promise.all` (or any other in-flight work promise) against
124
+ * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly
125
+ * even when codec bodies ignore the signal. In-flight bodies that ignore the
126
+ * signal are abandoned and run to completion in the background — the
127
+ * cooperative-cancellation contract documented in ADR 204.
128
+ *
129
+ * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with
130
+ * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —
131
+ * that path is the canonical "aborted at entry" surface and avoids
132
+ * scheduling the work promise. As a defensive belt-and-braces, this helper
133
+ * also handles the already-aborted case internally: `AbortSignal` does not
134
+ * replay past abort events to listeners registered after the abort, so we
135
+ * inspect `signal.aborted` synchronously and reject with the sentinel
136
+ * before installing the listener. The rejection is still attributed to the
137
+ * abort path via the sentinel-identity check.
138
+ *
139
+ * Distinguishing the rejection source is load-bearing for AC-ERR4
140
+ * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).
141
+ * The semantically equivalent `abortable(signal)` helper in
142
+ * `@prisma-next/utils` rejects with `signal.reason ?? new DOMException(...)`,
143
+ * which is not stably distinguishable from a codec-thrown error by identity
144
+ * alone (a fresh fallback DOMException is allocated per call). We instead
145
+ * track abort attribution with a unique sentinel: only the `onAbort` listener
146
+ * installed here ever rejects with the sentinel, so an `error === sentinel`
147
+ * identity check after the race is unambiguous.
148
+ *
149
+ * Lives in `framework-components` (rather than the SQL family, where it
150
+ * originated in m2) so every family runtime that needs cooperative
151
+ * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode
152
+ * today, Mongo encode in m3) shares the same attribution logic.
153
+ */
154
+ declare function raceAgainstAbort<T>(work: Promise<T>, signal: AbortSignal | undefined, phase: RuntimeAbortedPhase): Promise<T>;
155
+ //#endregion
156
+ //#region src/execution/runtime-middleware.d.ts
67
157
  interface RuntimeLog {
68
158
  info(event: unknown): void;
69
159
  warn(event: unknown): void;
70
160
  error(event: unknown): void;
71
161
  debug?(event: unknown): void;
72
162
  }
163
+ /**
164
+ * Per-execute context threaded through every middleware phase
165
+ * (`beforeExecute`, `onRow`, `afterExecute`). Allocated once per
166
+ * `runtime.execute()` call and shared by reference across all
167
+ * middleware in the chain.
168
+ *
169
+ * - `signal` carries the per-query `AbortSignal` -- the same
170
+ * reference that `runtime.execute(plan, { signal })` was invoked
171
+ * with, and the same reference threaded into the per-call
172
+ * `CodecCallContext` (ADR 207). Middleware that wraps a
173
+ * network-backed SDK forwards `ctx.signal` into that SDK to
174
+ * propagate caller cancellation; pure-CPU middleware ignores it.
175
+ *
176
+ * Symmetric plumbing across all middleware phases (rather than only
177
+ * `beforeExecute`) is a deliberate choice: a middleware that wraps a
178
+ * downstream observability hook or post-processor in `afterExecute` /
179
+ * `onRow` needs the same cancellation reach as its `beforeExecute`
180
+ * counterpart.
181
+ */
73
182
  interface RuntimeMiddlewareContext {
74
183
  readonly contract: unknown;
75
184
  readonly mode: 'strict' | 'permissive';
76
185
  readonly now: () => number;
77
186
  readonly log: RuntimeLog;
187
+ /**
188
+ * Returns a stable string identifying the (storage, statement, params)
189
+ * tuple of an execution. Two semantically equivalent executions return
190
+ * the same string. Used by middleware that need per-execution identity
191
+ * (caching, request coalescing).
192
+ *
193
+ * The family runtime owns the implementation:
194
+ * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`
195
+ * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`
196
+ *
197
+ * The method is `async` because the underlying digest helper
198
+ * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`
199
+ * primitive is asynchronous by design.
200
+ *
201
+ * The returned string is intended to be consumed directly as a `Map` key
202
+ * — it is not (and should not be) further hashed by callers.
203
+ */
204
+ contentHash(exec: ExecutionPlan): Promise<string>;
205
+ /**
206
+ * Per-execute cancellation signal threaded through every middleware
207
+ * phase. Middleware that wraps async work or downstream cancellable
208
+ * primitives should observe this and abort early when the consumer
209
+ * cancels.
210
+ */
211
+ readonly signal?: AbortSignal;
78
212
  }
79
213
  interface AfterExecuteResult {
80
214
  readonly rowCount: number;
81
215
  readonly latencyMs: number;
82
216
  readonly completed: boolean;
217
+ /**
218
+ * Indicates where the rows observed during this execution came from.
219
+ *
220
+ * - `'driver'` — the default. Rows came from the underlying driver via
221
+ * `runDriver` / `runWithMiddleware`'s normal path.
222
+ * - `'middleware'` — a `RuntimeMiddleware.intercept` hook short-circuited
223
+ * execution and supplied the rows directly. The driver was not invoked.
224
+ *
225
+ * Observers (telemetry, lints, budgets) that need to distinguish between
226
+ * driver-served and middleware-served executions read this field.
227
+ * Observers that don't care can ignore it.
228
+ */
229
+ readonly source: 'driver' | 'middleware';
230
+ }
231
+ /**
232
+ * Result of a successful `RuntimeMiddleware.intercept` hook.
233
+ *
234
+ * Carries the rows that the middleware wishes to return in place of
235
+ * invoking the driver. The runtime iterates `rows` in order and yields
236
+ * each row to the consumer; `beforeExecute`, `runDriver`, and `onRow` are
237
+ * all skipped on the hit path. `afterExecute` still fires with
238
+ * `source: 'middleware'`.
239
+ *
240
+ * `rows` accepts both `Iterable` (arrays, sync generators) and
241
+ * `AsyncIterable` (async generators). `for await` natively handles both
242
+ * via `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the
243
+ * orchestrator does not need to branch on the variant. Cached arrays in
244
+ * the cache middleware are the common case; streaming variants support
245
+ * future use cases like mock layers replaying recordings.
246
+ *
247
+ * Row shape is `Record<string, unknown>` — the same untyped shape
248
+ * `onRow` receives. The SQL runtime decodes intercepted rows through its
249
+ * normal codec pass, so interceptors cache and return raw (undecoded)
250
+ * rows.
251
+ */
252
+ interface InterceptResult {
253
+ readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;
83
254
  }
255
+ /**
256
+ * Marker interface for family-specific param-ref mutators threaded into
257
+ * `beforeExecute` as the third argument. The framework treats the mutator
258
+ * opaquely — it allocates and forwards the family's mutator instance so
259
+ * `runWithMiddleware` can stay family-agnostic. SQL extends this with
260
+ * `SqlParamRefMutator` (over `ParamRef`); Mongo extends with
261
+ * `MongoParamRefMutator` (over `MongoParamRef`).
262
+ *
263
+ * Extension authors target the family-specific mutator type, not this
264
+ * marker.
265
+ */
266
+ declare const PARAM_REF_MUTATOR_BRAND: unique symbol;
267
+ type ParamRefMutator = {
268
+ readonly [PARAM_REF_MUTATOR_BRAND]?: never;
269
+ };
84
270
  /**
85
271
  * Family-agnostic middleware SPI parameterized over the plan marker.
86
272
  *
@@ -88,15 +274,56 @@ interface AfterExecuteResult {
88
274
  * middleware (e.g. cross-family telemetry) can be authored without
89
275
  * naming a family. Family-specific middleware (`SqlMiddleware`,
90
276
  * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.
277
+ *
278
+ * `TMutator` is the family-specific {@link ParamRefMutator} the runtime
279
+ * threads into `beforeExecute(plan, ctx, params)` as a third argument.
280
+ * Existing `(plan)` / `(plan, ctx)` middleware bodies continue to compile
281
+ * — TypeScript permits assigning a function with fewer parameters to a
282
+ * function-typed slot that declares more. The third arg is additive.
91
283
  */
92
- interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan> {
284
+ interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan, TMutator extends ParamRefMutator = ParamRefMutator> {
93
285
  readonly name: string;
94
286
  readonly familyId?: string;
95
287
  readonly targetId?: string;
96
- beforeExecute?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
288
+ /**
289
+ * Optional short-circuit hook. Runs inside `runWithMiddleware`, after
290
+ * the orchestrator receives the lowered plan and before any
291
+ * `beforeExecute` hook fires. Middleware run in registration order; the
292
+ * first to return a non-`undefined` `InterceptResult` wins, and
293
+ * subsequent middleware's `intercept` does not fire.
294
+ *
295
+ * On a hit, `beforeExecute`, `runDriver`, and `onRow` are all skipped.
296
+ * `afterExecute` still fires with `source: 'middleware'`.
297
+ *
298
+ * Returning `undefined` (or omitting the hook entirely) signals
299
+ * passthrough — execution proceeds through the normal driver path.
300
+ *
301
+ * Errors thrown inside `intercept` are rethrown by `runWithMiddleware`
302
+ * as the original `Error` — no envelope is guaranteed at this layer.
303
+ * Before rethrowing, `afterExecute` fires with `completed: false` and
304
+ * `source: 'middleware'`. Errors thrown by `afterExecute` during the
305
+ * error path remain swallowed (existing semantics, unchanged).
306
+ *
307
+ * Used by middleware that need to short-circuit execution and supply
308
+ * rows directly: caching, mocks, rate limiting, circuit breaking.
309
+ */
310
+ intercept?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<InterceptResult | undefined>;
311
+ beforeExecute?(plan: TPlan, ctx: RuntimeMiddlewareContext, params?: TMutator): void | Promise<void>;
97
312
  onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
98
313
  afterExecute?(plan: TPlan, result: AfterExecuteResult, ctx: RuntimeMiddlewareContext): Promise<void>;
99
314
  }
315
+ /**
316
+ * Optional per-`execute` options accepted by every family runtime.
317
+ *
318
+ * `signal` is the per-query cancellation signal. The runtime threads the
319
+ * signal through to every codec call for the query and uses it to short-
320
+ * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.
321
+ * Omitting the option (or passing `undefined`) preserves today's behavior
322
+ * bit-for-bit.
323
+ */
324
+ interface RuntimeExecuteOptions {
325
+ readonly signal?: AbortSignal;
326
+ }
100
327
  /**
101
328
  * Cross-family SPI for any runtime that can execute plans and be shut down.
102
329
  * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,
@@ -108,33 +335,50 @@ interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan> {
108
335
  interface RuntimeExecutor<TPlan extends QueryPlan> {
109
336
  execute<Row>(plan: TPlan & {
110
337
  readonly _row?: Row;
111
- }): AsyncIterableResult<Row>;
338
+ }, options?: RuntimeExecuteOptions): AsyncIterableResult<Row>;
112
339
  close(): Promise<void>;
113
340
  }
114
341
  declare function checkMiddlewareCompatibility(middleware: RuntimeMiddleware, runtimeFamilyId: string, runtimeTargetId: string): void;
115
342
  //#endregion
116
- //#region src/run-with-middleware.d.ts
343
+ //#region src/execution/run-with-middleware.d.ts
117
344
  /**
118
345
  * Drives a single execution of `runDriver()` through the middleware lifecycle.
119
346
  *
120
347
  * Lifecycle, in order:
121
- * 1. For each middleware in registration order: `beforeExecute(exec, ctx)`.
122
- * 2. For each row yielded by `runDriver()`: for each middleware in registration
123
- * order: `onRow(row, exec, ctx)`; then yield the row to the consumer.
124
- * 3. On successful completion: for each middleware in registration order:
125
- * `afterExecute(exec, { rowCount, latencyMs, completed: true }, ctx)`.
126
- * 4. On any error thrown by the driver loop: for each middleware in
348
+ * 1. For each middleware in registration order: `intercept(exec, ctx)`. The
349
+ * first non-`undefined` result wins; subsequent middleware's `intercept`
350
+ * does not fire. On a hit, the runtime emits a `middleware.intercept`
351
+ * debug event naming the winning middleware, switches the row source to
352
+ * the intercepted rows, and proceeds with `source: 'middleware'`. On
353
+ * all-passthrough (every `intercept` returns `undefined` or is omitted),
354
+ * `source: 'driver'` is used and the row source is `runDriver()`.
355
+ * 2. If `source === 'driver'`: for each middleware in registration order,
356
+ * `beforeExecute(exec, ctx)`. Skipped on the intercepted hit path —
357
+ * `beforeExecute` semantically means "about to hit the driver".
358
+ * 3. Iterate the row source. On the driver path, for each row, for each
359
+ * middleware in registration order: `onRow(row, exec, ctx)`; then yield
360
+ * the row. On the intercepted hit path, `onRow` is skipped — intercepted
361
+ * rows did not originate from a driver row stream — but rows are still
362
+ * yielded to the consumer in order.
363
+ * 4. On successful completion: for each middleware in registration order:
364
+ * `afterExecute(exec, { rowCount, latencyMs, completed: true, source },
365
+ * ctx)`.
366
+ * 5. On any error thrown during steps 1–3: for each middleware in
127
367
  * registration order: `afterExecute(exec, { rowCount, latencyMs,
128
- * completed: false }, ctx)`. Errors thrown by `afterExecute` during the
129
- * error path are swallowed so they do not mask the original driver error.
130
- * The original error is then rethrown.
368
+ * completed: false, source }, ctx)`. Errors thrown by `afterExecute`
369
+ * during the error path are swallowed so they do not mask the original
370
+ * error. The original error is then rethrown.
371
+ *
372
+ * The `source` field on `AfterExecuteResult` lets observers (telemetry,
373
+ * lints, budgets) distinguish driver-served from middleware-served
374
+ * executions without needing their own out-of-band signal.
131
375
  *
132
376
  * This helper is the single canonical implementation of the middleware
133
377
  * orchestration loop; family runtimes should not reimplement it.
134
378
  */
135
- declare function runWithMiddleware<TExec extends ExecutionPlan, Row>(exec: TExec, middleware: ReadonlyArray<RuntimeMiddleware<TExec>>, ctx: RuntimeMiddlewareContext, runDriver: () => AsyncIterable<Row>): AsyncIterableResult<Row>;
379
+ declare function runWithMiddleware<TExec extends ExecutionPlan, Row, TMutator extends ParamRefMutator = ParamRefMutator>(exec: TExec, middleware: ReadonlyArray<RuntimeMiddleware<TExec, TMutator>>, ctx: RuntimeMiddlewareContext, runDriver: () => AsyncIterable<Row>, paramsMutator?: TMutator): AsyncIterableResult<Row>;
136
380
  //#endregion
137
- //#region src/runtime-core.d.ts
381
+ //#region src/execution/runtime-core.d.ts
138
382
  /**
139
383
  * Constructor options shared by every concrete `RuntimeCore` subclass.
140
384
  *
@@ -185,8 +429,16 @@ declare abstract class RuntimeCore<TPlan extends QueryPlan, TExec extends Execut
185
429
  * Lower a pre-lowering `TPlan` into the family's executable `TExec`.
186
430
  * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo
187
431
  * produces `{ command, ... }`.
432
+ *
433
+ * `ctx` carries per-query cancellation (and any future fields on
434
+ * `CodecCallContext`); concrete subclasses forward it to the
435
+ * encode-side codec dispatch site (e.g. SQL's `encodeParams` in m2,
436
+ * Mongo's `resolveValue` in m3). The runtime allocates one ctx per
437
+ * `execute()` call and threads the same reference everywhere; the
438
+ * `signal` field inside may be `undefined`, but the ctx object itself
439
+ * is always present.
188
440
  */
189
- protected abstract lower(plan: TPlan): TExec | Promise<TExec>;
441
+ protected abstract lower(plan: TPlan, ctx: CodecCallContext): TExec | Promise<TExec>;
190
442
  /**
191
443
  * Drive the underlying transport for a lowered `TExec`. Yields raw rows
192
444
  * directly from the driver as `Record<string, unknown>`; codec decoding
@@ -201,24 +453,8 @@ declare abstract class RuntimeCore<TPlan extends QueryPlan, TExec extends Execut
201
453
  abstract close(): Promise<void>;
202
454
  execute<Row>(plan: TPlan & {
203
455
  readonly _row?: Row;
204
- }): AsyncIterableResult<Row>;
205
- }
206
- //#endregion
207
- //#region src/runtime-error.d.ts
208
- interface RuntimeErrorEnvelope extends Error {
209
- readonly code: string;
210
- readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';
211
- readonly severity: 'error';
212
- readonly details?: Record<string, unknown>;
456
+ }, options?: RuntimeExecuteOptions): AsyncIterableResult<Row>;
213
457
  }
214
- /**
215
- * Type guard for the runtime-error envelope produced by `runtimeError`.
216
- *
217
- * Prefer this over duck-typing on `error.code` directly so consumers stay
218
- * insulated from the envelope's internal shape.
219
- */
220
- declare function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope;
221
- declare function runtimeError(code: string, message: string, details?: Record<string, unknown>): RuntimeErrorEnvelope;
222
458
  //#endregion
223
- export { type AfterExecuteResult, AsyncIterableResult, type ExecutionPlan, type QueryPlan, type ResultType, RuntimeCore, type RuntimeCoreOptions, type RuntimeErrorEnvelope, type RuntimeExecutor, type RuntimeLog, type RuntimeMiddleware, type RuntimeMiddlewareContext, checkMiddlewareCompatibility, isRuntimeError, runWithMiddleware, runtimeError };
459
+ export { type AfterExecuteResult, AsyncIterableResult, type ExecutionPlan, type InterceptResult, type ParamRefMutator, type QueryPlan, RUNTIME_ABORTED, type ResultType, type RuntimeAbortedPhase, RuntimeCore, type RuntimeCoreOptions, type RuntimeErrorEnvelope, type RuntimeExecuteOptions, type RuntimeExecutor, type RuntimeLog, type RuntimeMiddleware, type RuntimeMiddlewareContext, checkAborted, checkMiddlewareCompatibility, isRuntimeError, raceAgainstAbort, runWithMiddleware, runtimeAborted, runtimeError };
224
460
  //# sourceMappingURL=runtime.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/async-iterable-result.ts","../src/query-plan.ts","../src/runtime-middleware.ts","../src/run-with-middleware.ts","../src/runtime-core.ts","../src/runtime-error.ts"],"sourcesContent":[],"mappings":";;;cAEa,oCAAoC,cAAc,MAAM,YAAY;;;EAApE,QAAA,UAAA;EAAkD,QAAA,oBAAA;EAAkB,WAAA,CAAA,SAAA,EAMxD,cANwD,CAMzC,GANyC,EAAA,IAAA,EAAA,OAAA,CAAA;EAMzC,CAIrC,MAAA,CAAO,aAAA,GAJ8B,EAIZ,aAJY,CAIE,GAJF,CAAA;EAAf,OAAA,CAAA,CAAA,EAuBZ,OAvBY,CAuBJ,GAvBI,EAAA,CAAA;EAIiB,KAAA,CAAA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,EAAA,OAAA,CAAA,EAAA,KAAA,IKlB4C,oBLkB5C;AA+BY,iBKvCT,YAAA,CLuCS,IAAA,EAAA,MAAA,EAAA,OAAA,EAAA,MAAA,EAAA,OAAA,CAAA,EKpCb,MLoCa,CAAA,MAAA,EAAA,OAAA,CAAA,CAAA,EKnCtB,oBLmCsB"}
1
+ {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/execution/async-iterable-result.ts","../src/execution/query-plan.ts","../src/execution/runtime-error.ts","../src/execution/race-against-abort.ts","../src/execution/runtime-middleware.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts"],"mappings":";;;;cAEa,mBAAA,iBAAoC,aAAA,CAAc,GAAA,GAAM,WAAA,CAAY,GAAA;EAAA,iBAC9D,SAAA;EAAA,QACT,QAAA;EAAA,QACA,UAAA;EAAA,QACA,oBAAA;cAEI,SAAA,EAAW,cAAA,CAAe,GAAA;EAAA,CAIrC,MAAA,CAAO,aAAA,KAAkB,aAAA,CAAc,GAAA;EAmBxC,OAAA,CAAA,GAAW,OAAA,CAAQ,GAAA;EA+Bb,KAAA,CAAA,GAAS,OAAA,CAAQ,GAAA;EAKjB,YAAA,CAAA,GAAgB,OAAA,CAAQ,GAAA;EAY9B,IAAA,YAAgB,GAAA,qBAAA,CACd,WAAA,KAAgB,KAAA,EAAO,GAAA,OAAU,QAAA,GAAW,WAAA,CAAY,QAAA,uBACxD,UAAA,KAAe,MAAA,cAAoB,QAAA,GAAW,WAAA,CAAY,QAAA,wBACzD,WAAA,CAAY,QAAA,GAAW,QAAA;AAAA;;;;;;AAhF5B;;;;;;;;;UCYiB,SAAA;EAAA,SACN,IAAA,EAAM,QAAA;EDgBJ;;;;EAAA,SCXF,IAAA,GAAO,GAAA;AAAA;;;;;;;;;;UAYD,aAAA,wBAAqC,SAAA,CAAU,GAAA;;;;;;;;;;;;;;;KAgBpD,UAAA,2BAAqC,CAAA,GAC7C,CAAA;EAAA,SAAqB,IAAA;AAAA,IACnB,CAAA;;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