@prisma/orm-framework 8.0.0-rc.17-dev.25 → 8.0.0-rc.17-dev.27

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,869 +0,0 @@
1
- import { t as blindCast } from "./casts-DpaahrlC-Bd5n2coI.mjs";
2
- import { n as runtimeError } from "./runtime-error-BA9d7XjZ-BlT8t6LB.mjs";
3
- //#region ../../../1-framework/1-core/framework-components/dist/runtime.mjs
4
- /**
5
- * Stable code emitted by the runtime when an in-flight `execute()`
6
- * is cancelled via the per-query `AbortSignal`. The envelope's
7
- * `details.phase` distinguishes where the abort was observed:
8
- *
9
- * - `'encode'` — abort fired during `encodeParams` (SQL) or
10
- * `resolveValue` (Mongo).
11
- * - `'decode'` — abort fired during `decodeRow` / `decodeField`.
12
- * - `'stream'` — abort fired between rows or before any codec call
13
- * (already-aborted at entry).
14
- * - `'beforeQuery'` / `'beforeExecute'` / `'afterQuery'` /
15
- * `'afterExecute'` / `'onRow'` — abort fired on entry to or during
16
- * the corresponding middleware phase
17
- * (cooperative cancellation per the param-transform seam).
18
- */
19
- const RUNTIME_ABORTED = "RUNTIME.ABORTED";
20
- /**
21
- * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the
22
- * abort was observed — codec call sites (`encode` / `decode` / `stream`)
23
- * or operation-specific middleware seams, as
24
- * enumerated on {@link RuntimeAbortedPhase}. Cause carries
25
- * `signal.reason` verbatim from the platform — native abort produces a
26
- * `DOMException`, explicit `controller.abort(reason)` produces whatever
27
- * the caller passed. No synthesis happens here.
28
- */
29
- function runtimeAborted(phase, cause) {
30
- const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });
31
- return Object.assign(envelope, { cause });
32
- }
33
- /**
34
- * Defines a typed annotation handle.
35
- *
36
- * Two-step call form. The first step takes the `Payload` type argument
37
- * (TypeScript cannot infer `Payload` from anything in the options, so it
38
- * must be supplied explicitly); the second step takes the runtime options
39
- * and infers `Kinds` from the `applicableTo` array via a `const` type
40
- * parameter, so the operation kinds appear exactly once at the call site.
41
- *
42
- * @example
43
- * ```typescript
44
- * // Read-only annotation. Lane terminals like `db.User.first(...)` accept
45
- * // it; `db.User.create(...)` rejects it at the type level.
46
- * const cacheAnnotation = defineAnnotation<{ ttl?: number; skip?: boolean }>()({
47
- * namespace: 'cache',
48
- * applicableTo: ['read'],
49
- * }); // Kinds inferred as 'read'
50
- *
51
- * // Write-only annotation. Mirror image.
52
- * const auditAnnotation = defineAnnotation<{ actor: string }>()({
53
- * namespace: 'audit',
54
- * applicableTo: ['write'],
55
- * }); // Kinds inferred as 'write'
56
- *
57
- * // Annotation applicable to both kinds (e.g. tracing).
58
- * const otelAnnotation = defineAnnotation<{ traceId: string }>()({
59
- * namespace: 'otel',
60
- * applicableTo: ['read', 'write'],
61
- * }); // Kinds inferred as 'read' | 'write'
62
- * ```
63
- *
64
- * **Reserved namespaces.** See `DefineAnnotationOptions.namespace` for the
65
- * list of framework-internal namespaces (`codecs`, target-specific keys).
66
- * `defineAnnotation` does not structurally prevent a user from naming a
67
- * reserved namespace, but the framework makes no compatibility guarantee
68
- * about handles that do.
69
- */
70
- function defineAnnotation() {
71
- return (options) => {
72
- const namespace = options.namespace;
73
- const applicableTo = Object.freeze(new Set(options.applicableTo));
74
- function handle(value) {
75
- return Object.freeze({
76
- __annotation: true,
77
- namespace,
78
- value,
79
- applicableTo
80
- });
81
- }
82
- function read(plan) {
83
- const stored = plan.meta.annotations?.[namespace];
84
- if (!isAnnotationValue(stored)) return;
85
- if (stored.namespace !== namespace) return;
86
- return stored.value;
87
- }
88
- return Object.freeze(Object.assign(handle, {
89
- namespace,
90
- applicableTo,
91
- read
92
- }));
93
- };
94
- }
95
- /**
96
- * Runtime applicability gate. Throws `RUNTIME.ANNOTATION_INAPPLICABLE` if
97
- * any annotation in `annotations` declares an `applicableTo` set that does
98
- * not include `kind`. Used by lane terminals (SQL DSL builders' `.build()`,
99
- * ORM `Collection` terminals) to fail closed when the type-level
100
- * `ValidAnnotations` gate is bypassed via cast / `any` / dynamic
101
- * invocation.
102
- *
103
- * Passes silently on:
104
- * - empty arrays
105
- * - annotations whose `applicableTo` includes `kind`
106
- *
107
- * Throws on:
108
- * - any annotation whose `applicableTo` does not include `kind`. The
109
- * error names the offending annotation's `namespace` and the
110
- * `terminalName` so users can locate the misuse.
111
- *
112
- * @example
113
- * ```typescript
114
- * // Inside an ORM read terminal:
115
- * assertAnnotationsApplicable(annotations, 'read', 'first');
116
- * ```
117
- */
118
- function assertAnnotationsApplicable(annotations, kind, terminalName) {
119
- for (const annotation of annotations) if (!annotation.applicableTo.has(kind)) throw runtimeError("RUNTIME.ANNOTATION_INAPPLICABLE", `Annotation '${annotation.namespace}' is not applicable to '${kind}' operations (terminal: '${terminalName}'). The annotation declares applicableTo = [${Array.from(annotation.applicableTo).map((k) => `'${k}'`).join(", ")}].`, {
120
- namespace: annotation.namespace,
121
- terminalName,
122
- kind,
123
- applicableTo: Array.from(annotation.applicableTo)
124
- });
125
- }
126
- /**
127
- * Type guard for branded annotation values stored in `plan.meta.annotations`.
128
- *
129
- * Internal — used by `AnnotationHandle.read` to distinguish user
130
- * annotations (created by calling a handle returned from
131
- * `defineAnnotation(...)`) from framework-internal metadata that may
132
- * happen to live under the same namespace key.
133
- */
134
- function isAnnotationValue(value) {
135
- if (value === null || typeof value !== "object") return false;
136
- return value.__annotation === true;
137
- }
138
- var AsyncIterableResult = class {
139
- generator;
140
- consumed = false;
141
- consumedBy;
142
- bufferedArrayPromise;
143
- constructor(generator) {
144
- this.generator = generator;
145
- }
146
- [Symbol.asyncIterator]() {
147
- if (this.consumed) throw runtimeError("RUNTIME.ITERATOR_CONSUMED", `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === "bufferedArray" ? "toArray()/then()" : "for-await loop"}. Each AsyncIterableResult can only be iterated once.`, {
148
- consumedBy: this.consumedBy,
149
- suggestion: this.consumedBy === "bufferedArray" ? "If you need to iterate multiple times, store the results from toArray() in a variable and reuse that." : "If you need to iterate multiple times, use toArray() to collect all results first."
150
- });
151
- this.consumed = true;
152
- this.consumedBy = "iterator";
153
- return this.generator;
154
- }
155
- toArray() {
156
- if (this.consumedBy === "iterator") return Promise.reject(runtimeError("RUNTIME.ITERATOR_CONSUMED", "AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.", {
157
- consumedBy: this.consumedBy,
158
- suggestion: "The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating."
159
- }));
160
- if (this.bufferedArrayPromise) return this.bufferedArrayPromise;
161
- this.consumed = true;
162
- this.consumedBy = "bufferedArray";
163
- this.bufferedArrayPromise = (async () => {
164
- const out = [];
165
- for await (const item of this.generator) out.push(item);
166
- return out;
167
- })();
168
- return this.bufferedArrayPromise;
169
- }
170
- async first() {
171
- return (await this.toArray())[0] ?? null;
172
- }
173
- async firstOrThrow() {
174
- const row = await this.first();
175
- if (row === null) throw runtimeError("RUNTIME.NO_ROWS", "Expected at least one row, but none were returned", {});
176
- return row;
177
- }
178
- then(onfulfilled, onrejected) {
179
- return this.toArray().then(onfulfilled, onrejected);
180
- }
181
- };
182
- /**
183
- * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied
184
- * context is already aborted at the precheck site. Centralises the
185
- * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that
186
- * every codec dispatch site (and the `beforeExecute` middleware phase)
187
- * repeats. Accepts both the framework `CodecCallContext` and the
188
- * `RuntimeMiddlewareContext`; both expose `signal?: AbortSignal`.
189
- */
190
- function checkAborted(ctx, phase) {
191
- if (ctx.signal?.aborted) throw runtimeAborted(phase, ctx.signal.reason);
192
- }
193
- /**
194
- * Race a per-cell `Promise.all` (or any other in-flight work promise) against
195
- * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly
196
- * even when codec bodies ignore the signal. In-flight bodies that ignore the
197
- * signal are abandoned and run to completion in the background — the
198
- * cooperative-cancellation contract documented in ADR 204.
199
- *
200
- * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with
201
- * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —
202
- * that path is the canonical "aborted at entry" surface and avoids
203
- * scheduling the work promise. As a defensive belt-and-braces, this helper
204
- * also handles the already-aborted case internally: `AbortSignal` does not
205
- * replay past abort events to listeners registered after the abort, so we
206
- * inspect `signal.aborted` synchronously and reject with the sentinel
207
- * before installing the listener. The rejection is still attributed to the
208
- * abort path via the sentinel-identity check.
209
- *
210
- * Distinguishing the rejection source is load-bearing for AC-ERR4
211
- * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).
212
- * The semantically equivalent `abortable(signal)` helper in
213
- * `@internal/utils` rejects with `signal.reason ?? new DOMException(...)`,
214
- * which is not stably distinguishable from a codec-thrown error by identity
215
- * alone (a fresh fallback DOMException is allocated per call). We instead
216
- * track abort attribution with a unique sentinel: only the `onAbort` listener
217
- * installed here ever rejects with the sentinel, so an `error === sentinel`
218
- * identity check after the race is unambiguous.
219
- *
220
- * Lives in `framework-components` (rather than the SQL family, where it
221
- * originated in m2) so every family runtime that needs cooperative
222
- * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode
223
- * today, Mongo encode in m3) shares the same attribution logic.
224
- */
225
- async function raceAgainstAbort(work, signal, phase) {
226
- if (signal === void 0) return await work;
227
- const sentinel = { reason: void 0 };
228
- let onAbort;
229
- const abortPromise = new Promise((_, reject) => {
230
- if (signal.aborted) {
231
- sentinel.reason = signal.reason;
232
- reject(sentinel);
233
- return;
234
- }
235
- onAbort = () => {
236
- sentinel.reason = signal.reason;
237
- reject(sentinel);
238
- };
239
- signal.addEventListener("abort", onAbort, { once: true });
240
- });
241
- try {
242
- return await Promise.race([work, abortPromise]);
243
- } catch (error) {
244
- if (error === sentinel) throw runtimeAborted(phase, sentinel.reason);
245
- throw error;
246
- } finally {
247
- if (onAbort) signal.removeEventListener("abort", onAbort);
248
- }
249
- }
250
- /**
251
- * Runs every middleware's `beforeQuery` hook in registration order,
252
- * threading through the (optional) family-specific `paramsMutator`.
253
- *
254
- * Why this lives outside {@link runQueryWithMiddleware}: middleware that
255
- * mutates parameter values (e.g. cipherstash's bulk-encrypt SDK
256
- * round-trip) must run *before* the family runtime encodes those
257
- * parameters to driver wire format. Family runtimes call
258
- * `runBeforeQueryChain` between the AST → plan lowering step and
259
- * the parameter encode step; the encode then observes the mutator's
260
- * `currentParams()` view. `runQueryWithMiddleware` retains the rest of
261
- * the query lifecycle (`interceptQuery`, driver/row source loop, `onRow`,
262
- * `afterQuery`) but no longer fires `beforeQuery` itself.
263
- *
264
- * Lifecycle within this helper:
265
- *
266
- * 1. For each middleware in registration order, if `beforeQuery`
267
- * is implemented:
268
- * - `checkAborted(ctx, 'beforeQuery')` short-circuits if the
269
- * caller already aborted at entry.
270
- * - The hook is invoked with `(plan, ctx, paramsMutator)`. A
271
- * middleware body that ignores the mutator stays compatible —
272
- * JavaScript allows extra positional arguments.
273
- * - If the hook returns a Promise, it is raced against
274
- * `ctx.signal` via {@link raceAgainstAbort} so cooperative
275
- * cancellation surfaces a `RUNTIME.ABORTED { phase:
276
- * 'beforeQuery' }` envelope even when the body itself
277
- * ignores the signal.
278
- *
279
- * Error propagation: any error thrown by a `beforeQuery` body
280
- * (or surfaced by the abort race) propagates out of this helper
281
- * unchanged. Family runtime entry points await this helper before invoking
282
- * `runQueryWithMiddleware`, so a rejection prevents the runner and its
283
- * `afterQuery` hook from running.
284
- *
285
- * Relationship to {@link runQueryWithMiddleware}: the framework's
286
- * `RuntimeCore.query` template calls this helper between
287
- * `lower(plan)` and `runQueryWithMiddleware(...)`. Family runtimes that
288
- * override query preparation (e.g. SQL, which inlines lower + encode for
289
- * direct mutator threading) call this helper themselves at the
290
- * equivalent point — between the family's AST → draft-plan
291
- * lowering and the parameter-encode step.
292
- *
293
- * Intercept ordering: this helper fires unconditionally before
294
- * `runQueryWithMiddleware`. `interceptQuery` (inside
295
- * `runQueryWithMiddleware`) therefore observes the post-`beforeQuery`
296
- * plan — mutator mutations are visible in the params interceptors see.
297
- * The trade-off is documented on `RuntimeMiddleware.interceptQuery`.
298
- */
299
- function runBeforeQueryChain(plan, middleware, ctx, paramsMutator) {
300
- return runBeforeChain(plan, middleware, ctx, paramsMutator, "beforeQuery", (mw) => mw.beforeQuery);
301
- }
302
- /**
303
- * Runs every middleware's `beforeExecute` hook in registration order,
304
- * threading through the (optional) family-specific `paramsMutator`.
305
- *
306
- * Why this lives outside {@link runExecuteWithMiddleware}: middleware that
307
- * mutates parameter values (e.g. cipherstash's bulk-encrypt SDK
308
- * round-trip) must run *before* the family runtime encodes those
309
- * parameters to driver wire format. Family runtimes call
310
- * `runBeforeExecuteChain` between the AST → plan lowering step and
311
- * the parameter encode step; the encode then observes the mutator's
312
- * `currentParams()` view. `runExecuteWithMiddleware` retains the rest of
313
- * the execute lifecycle (`interceptExecute`, driver statistics execution,
314
- * `afterExecute`) but no longer fires `beforeExecute` itself.
315
- *
316
- * Lifecycle within this helper:
317
- *
318
- * 1. For each middleware in registration order, if `beforeExecute`
319
- * is implemented:
320
- * - `checkAborted(ctx, 'beforeExecute')` short-circuits if the
321
- * caller already aborted at entry.
322
- * - The hook is invoked with `(plan, ctx, paramsMutator)`. A
323
- * middleware body that ignores the mutator stays compatible —
324
- * JavaScript allows extra positional arguments.
325
- * - If the hook returns a Promise, it is raced against
326
- * `ctx.signal` via {@link raceAgainstAbort} so cooperative
327
- * cancellation surfaces a `RUNTIME.ABORTED { phase:
328
- * 'beforeExecute' }` envelope even when the body itself
329
- * ignores the signal.
330
- *
331
- * Error propagation: any error thrown by a `beforeExecute` body
332
- * (or surfaced by the abort race) propagates out of this helper
333
- * unchanged. Family runtime entry points await this helper before invoking
334
- * `runExecuteWithMiddleware`, so a rejection prevents the runner and its
335
- * `afterExecute` hook from running.
336
- *
337
- * Relationship to {@link runExecuteWithMiddleware}: the framework's
338
- * `RuntimeCore.execute` template calls this helper between
339
- * `lower(plan)` and `runExecuteWithMiddleware(...)`. Family runtimes that
340
- * override execute (e.g. SQL, which inlines lower + encode for
341
- * direct mutator threading) call this helper themselves at the
342
- * equivalent point — between the family's AST → draft-plan
343
- * lowering and the parameter-encode step.
344
- *
345
- * Intercept ordering: this helper fires unconditionally before
346
- * `runExecuteWithMiddleware`. `interceptExecute` (inside
347
- * `runExecuteWithMiddleware`) therefore observes the post-`beforeExecute`
348
- * plan — mutator mutations are visible in the params interceptors see.
349
- * The trade-off is documented on `RuntimeMiddleware.interceptExecute`.
350
- */
351
- function runBeforeExecuteChain(plan, middleware, ctx, paramsMutator) {
352
- return runBeforeChain(plan, middleware, ctx, paramsMutator, "beforeExecute", (mw) => mw.beforeExecute);
353
- }
354
- async function runBeforeChain(plan, middleware, ctx, paramsMutator, phase, selectHook) {
355
- for (const mw of middleware) {
356
- const hook = selectHook(mw);
357
- if (hook === void 0) continue;
358
- checkAborted(ctx, phase);
359
- const work = hook(plan, ctx, paramsMutator);
360
- if (work !== void 0) await raceAgainstAbort(Promise.resolve(work), ctx.signal, phase);
361
- }
362
- }
363
- /** Registers every generator the contributors provide, by id. Two contributors providing one id is an error naming both. */
364
- function collectMutationDefaultGenerators(contributors) {
365
- const generators = /* @__PURE__ */ new Map();
366
- const owners = /* @__PURE__ */ new Map();
367
- for (const contributor of contributors) {
368
- const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];
369
- for (const generator of nextGenerators) {
370
- const existingOwner = owners.get(generator.id);
371
- if (existingOwner !== void 0) throw runtimeError("RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR", `Duplicate mutation default generator '${generator.id}'.`, {
372
- id: generator.id,
373
- existingOwner,
374
- incomingOwner: contributor.id
375
- });
376
- generators.set(generator.id, generator);
377
- owners.set(generator.id, contributor.id);
378
- }
379
- }
380
- return generators;
381
- }
382
- /** 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. */
383
- function assertMutationDefaultGeneratorsAvailable(execution, generatorRegistry) {
384
- const defaults = execution?.mutations.defaults ?? [];
385
- if (defaults.length === 0) return;
386
- const fieldsById = /* @__PURE__ */ new Map();
387
- for (const mutationDefault of defaults) {
388
- const phaseIds = new Set([mutationDefault.onCreate, mutationDefault.onUpdate].flatMap((phase) => phase?.kind === "generator" && !generatorRegistry.has(phase.id) ? [phase.id] : []));
389
- for (const id of phaseIds) {
390
- const fields = fieldsById.get(id) ?? [];
391
- fields.push(`${mutationDefault.ref.entry}.${mutationDefault.ref.field}`);
392
- fieldsById.set(id, fields);
393
- }
394
- }
395
- if (fieldsById.size === 0) return;
396
- const ids = [...fieldsById.keys()];
397
- const needs = [...fieldsById].map(([id, fields]) => `'${id}' for ${listInProse(fields)}`);
398
- throw runtimeError("RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING", `${ids.length === 1 ? `Contract requires mutation default generator ${needs[0]}, but no runtime component in the execution stack provides it.` : `Contract requires mutation default generators ${listInProse(needs)}, but no runtime component in the execution stack provides them.`} ${WHERE_GENERATORS_COME_FROM}`, {
399
- ids,
400
- fields: [...fieldsById.values()].flat()
401
- });
402
- }
403
- const WHERE_GENERATORS_COME_FROM = "Built-in generators such as 'timestampNow' come from the database adapter's runtime descriptor, and others from the extension pack that defines them; include that component in the execution stack.";
404
- function listInProse(items) {
405
- return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}` : items.join("");
406
- }
407
- function computeExecutionDefaultValue(spec, generatorRegistry) {
408
- const generator = generatorRegistry.get(spec.id);
409
- if (!generator) throw runtimeError("RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING", `Contract references mutation default generator '${spec.id}' but no runtime component in the execution stack provides it. ${WHERE_GENERATORS_COME_FROM}`, { id: spec.id });
410
- return generator.generate(spec.params);
411
- }
412
- /**
413
- * 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.
414
- */
415
- function applyMutationDefaults(execution, generatorRegistry, options) {
416
- const defaults = execution?.mutations.defaults ?? [];
417
- if (defaults.length === 0) return [];
418
- const isEmptyUpdate = options.op === "update" && Object.keys(options.values).length === 0;
419
- const applied = [];
420
- const appliedFields = /* @__PURE__ */ new Set();
421
- const rowCache = /* @__PURE__ */ new Map();
422
- for (const mutationDefault of defaults) {
423
- if (mutationDefault.ref.entry !== options.entry) continue;
424
- if (mutationDefault.ref.namespace !== options.namespace) continue;
425
- const defaultSpec = options.op === "create" ? mutationDefault.onCreate : mutationDefault.onUpdate;
426
- if (!defaultSpec) continue;
427
- if (isEmptyUpdate) continue;
428
- const fieldName = mutationDefault.ref.field;
429
- if (Object.hasOwn(options.values, fieldName) || appliedFields.has(fieldName)) continue;
430
- applied.push({
431
- field: fieldName,
432
- value: resolveScopedValue(defaultSpec, generatorRegistry, rowCache, options.defaultValueCache)
433
- });
434
- appliedFields.add(fieldName);
435
- }
436
- return applied;
437
- }
438
- function resolveScopedValue(spec, generatorRegistry, rowCache, queryCache) {
439
- const cache = scopedCache(generatorRegistry.get(spec.id)?.stability, rowCache, queryCache);
440
- if (!cache) return computeExecutionDefaultValue(spec, generatorRegistry);
441
- if (cache.has(spec.id)) return cache.get(spec.id);
442
- const value = computeExecutionDefaultValue(spec, generatorRegistry);
443
- cache.set(spec.id, value);
444
- return value;
445
- }
446
- function scopedCache(stability, rowCache, queryCache) {
447
- switch (stability) {
448
- case "row": return rowCache;
449
- case "query": return queryCache;
450
- default: return;
451
- }
452
- }
453
- /**
454
- * Drives a single query execution of `runDriver()` through the middleware
455
- * lifecycle's `interceptQuery` + row-source + termination phases.
456
- *
457
- * Lifecycle, in order:
458
- * 1. For each middleware in registration order: `interceptQuery(exec, ctx)`.
459
- * The first non-`undefined` result wins; subsequent middleware's
460
- * `interceptQuery` does not fire. On a hit, the runtime emits a
461
- * `middleware.interceptQuery` debug event naming the winning middleware,
462
- * switches the row source to the intercepted rows, and proceeds with
463
- * `source: 'middleware'`. On all-passthrough (every `interceptQuery`
464
- * returns `undefined` or is omitted), `source: 'driver'` is used and the
465
- * row source is `runDriver()`.
466
- * 2. Iterate the row source. On the driver path, for each row, for each
467
- * middleware in registration order: `onRow(row, exec, ctx)`; then yield
468
- * the row. On the intercepted hit path, `onRow` is skipped — intercepted
469
- * rows did not originate from a driver row stream — but rows are still
470
- * yielded to the consumer in order.
471
- * 3. On successful completion: for each middleware in registration order:
472
- * `afterQuery(exec, { rowCount, latencyMs, completed: true, source },
473
- * ctx)`.
474
- * 4. On any error thrown during steps 1–2: for each middleware in
475
- * registration order: `afterQuery(exec, { rowCount, latencyMs,
476
- * completed: false, source }, ctx)`. Errors thrown by `afterQuery`
477
- * during the error path are swallowed so they do not mask the original
478
- * error. The original error is then rethrown.
479
- *
480
- * `beforeQuery` is **not** fired here — see
481
- * {@link runBeforeQueryChain} in `before-execute-chain.ts`. Family runtimes
482
- * call that helper between the AST → plan lowering step and the parameter
483
- * encode step so middleware that mutates ParamRef values can have its
484
- * mutations visible to encode. `runQueryWithMiddleware` operates on the
485
- * fully-encoded plan; interceptors therefore observe a fully-mutated,
486
- * encoded plan.
487
- *
488
- * The `source` field on `AfterQueryResult` lets observers (telemetry, lints,
489
- * budgets) distinguish driver-served from middleware-served executions
490
- * without needing their own out-of-band signal.
491
- *
492
- * This helper is the single canonical implementation of the
493
- * intercept-and-row-source loop; family runtimes should not reimplement it.
494
- */
495
- function runQueryWithMiddleware(exec, middleware, ctx, runDriver) {
496
- const iterator = async function* () {
497
- const startedAt = Date.now();
498
- let rowCount = 0;
499
- let completed = false;
500
- let source = "driver";
501
- let rowSource;
502
- try {
503
- for (const mw of middleware) {
504
- if (!mw.interceptQuery) continue;
505
- source = "middleware";
506
- const result = await mw.interceptQuery(exec, ctx);
507
- if (result === void 0) {
508
- source = "driver";
509
- continue;
510
- }
511
- ctx.log.debug?.({
512
- event: "middleware.interceptQuery",
513
- middleware: mw.name
514
- });
515
- rowSource = blindCast(result.rows);
516
- break;
517
- }
518
- if (source === "driver") rowSource = runDriver();
519
- for await (const row of rowSource) {
520
- if (source === "driver") {
521
- for (const mw of middleware) if (mw.onRow) await mw.onRow(row, exec, ctx);
522
- }
523
- rowCount++;
524
- yield row;
525
- }
526
- completed = true;
527
- } catch (error) {
528
- await notifyQueryCompletion(middleware, exec, ctx, {
529
- rowCount,
530
- latencyMs: Date.now() - startedAt,
531
- completed,
532
- source
533
- }, true);
534
- throw error;
535
- }
536
- await notifyQueryCompletion(middleware, exec, ctx, {
537
- rowCount,
538
- latencyMs: Date.now() - startedAt,
539
- completed,
540
- source
541
- }, false);
542
- };
543
- return new AsyncIterableResult(iterator());
544
- }
545
- /**
546
- * Drives a single execute operation through the middleware
547
- * `interceptExecute` + statistics + termination phases.
548
- *
549
- * Lifecycle, in order:
550
- * 1. For each middleware in registration order: `interceptExecute(exec, ctx)`.
551
- * The first non-`undefined` result wins; subsequent middleware's
552
- * `interceptExecute` does not fire. On a hit, the runtime emits a
553
- * `middleware.interceptExecute` debug event naming the winning middleware,
554
- * uses the returned `stats`, and proceeds with `source: 'middleware'`.
555
- * On all-passthrough (every `interceptExecute` returns `undefined` or is
556
- * omitted), `source: 'driver'` is used and `runDriver()` supplies the
557
- * statistics.
558
- * 2. Execute operations return eager statistics. There is no row stream and
559
- * `onRow` does not fire.
560
- * 3. On successful completion: for each middleware in registration order:
561
- * `afterExecute(exec, { stats, latencyMs, completed: true, source }, ctx)`.
562
- * 4. On any error thrown during steps 1–2: for each middleware in
563
- * registration order: `afterExecute(exec, { latencyMs, completed: false,
564
- * source }, ctx)`. Errors thrown by `afterExecute` during the error path
565
- * are swallowed so they do not mask the original error. The original
566
- * error is then rethrown.
567
- *
568
- * `beforeExecute` is **not** fired here — see
569
- * {@link runBeforeExecuteChain} in `before-execute-chain.ts`. Family runtimes
570
- * call that helper between the AST → plan lowering step and the parameter
571
- * encode step so middleware that mutates ParamRef values can have its
572
- * mutations visible to encode. `runExecuteWithMiddleware` operates on the
573
- * fully-encoded plan; interceptors therefore observe a fully-mutated,
574
- * encoded plan.
575
- *
576
- * The `source` field on `AfterExecuteResult` lets observers (telemetry, lints,
577
- * budgets) distinguish driver-served from middleware-served executions
578
- * without needing their own out-of-band signal.
579
- */
580
- async function runExecuteWithMiddleware(exec, middleware, ctx, runDriver) {
581
- const startedAt = Date.now();
582
- let source = "driver";
583
- let stats;
584
- try {
585
- for (const mw of middleware) {
586
- if (!mw.interceptExecute) continue;
587
- source = "middleware";
588
- const result = await mw.interceptExecute(exec, ctx);
589
- if (result === void 0) {
590
- source = "driver";
591
- continue;
592
- }
593
- ctx.log.debug?.({
594
- event: "middleware.interceptExecute",
595
- middleware: mw.name
596
- });
597
- stats = result.stats;
598
- break;
599
- }
600
- if (stats === void 0) stats = await runDriver();
601
- } catch (error) {
602
- const latencyMs = Date.now() - startedAt;
603
- for (const mw of middleware) {
604
- if (!mw.afterExecute) continue;
605
- try {
606
- await mw.afterExecute(exec, {
607
- latencyMs,
608
- completed: false,
609
- source
610
- }, ctx);
611
- } catch {}
612
- }
613
- throw error;
614
- }
615
- const latencyMs = Date.now() - startedAt;
616
- for (const mw of middleware) if (mw.afterExecute) await mw.afterExecute(exec, {
617
- stats,
618
- latencyMs,
619
- completed: true,
620
- source
621
- }, ctx);
622
- return stats;
623
- }
624
- /**
625
- * Calls each middleware's `afterTransaction` hook in registration order. A
626
- * thrown error is passed to `ctx.log.error` and swallowed, and later
627
- * middleware still run. Never rejects, so a query's result or a resolved
628
- * commit is never replaced by a hook's failure.
629
- */
630
- async function runAfterTransaction(exec, middleware, result, ctx) {
631
- for (const mw of middleware) {
632
- if (!mw.afterTransaction) continue;
633
- try {
634
- await mw.afterTransaction(exec, result, ctx);
635
- } catch (error) {
636
- try {
637
- ctx.log.error({
638
- event: "middleware.afterTransaction.error",
639
- middleware: mw.name,
640
- error
641
- });
642
- } catch {}
643
- }
644
- }
645
- }
646
- /**
647
- * 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`.
648
- */
649
- function onQueryEndOutsideTransaction(runStage) {
650
- if (runStage === void 0) return void 0;
651
- return (ending) => runStage({ outcome: ending === "completed" ? "committed" : "unknown" });
652
- }
653
- /**
654
- * 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`.
655
- */
656
- function reportQueryEnding(onQueryEnd, rows) {
657
- return onQueryEnd === void 0 ? rows() : rowsThenQueryEnd(onQueryEnd, rows);
658
- }
659
- function rowsThenQueryEnd(onQueryEnd, rows) {
660
- return { [Symbol.asyncIterator]() {
661
- let thrownByCaller;
662
- const generator = streamThenQueryEnd(onQueryEnd, rows, (error) => thrownByCaller !== void 0 && thrownByCaller.error === error);
663
- let started = false;
664
- const reportStoppedBeforeStart = async () => {
665
- if (started) return;
666
- started = true;
667
- await onQueryEnd("stopped");
668
- };
669
- return {
670
- next: () => {
671
- started = true;
672
- return generator.next();
673
- },
674
- return: async () => {
675
- await reportStoppedBeforeStart();
676
- return generator.return(void 0);
677
- },
678
- throw: async (error) => {
679
- thrownByCaller = { error };
680
- await reportStoppedBeforeStart();
681
- return generator.throw(error);
682
- }
683
- };
684
- } };
685
- }
686
- async function* streamThenQueryEnd(onQueryEnd, rows, isThrownByCaller) {
687
- let ending = "stopped";
688
- try {
689
- yield* rows();
690
- ending = "completed";
691
- } catch (error) {
692
- if (!isThrownByCaller(error)) ending = "failed";
693
- throw error;
694
- } finally {
695
- await onQueryEnd(ending);
696
- }
697
- }
698
- /**
699
- * Runs `execute()` and then calls `onQueryEnd` exactly once: with `completed` when it resolves, and with `failed` when it rejects.
700
- */
701
- async function reportExecuteEnding(onQueryEnd, execute) {
702
- if (onQueryEnd === void 0) return execute();
703
- let ending = "failed";
704
- try {
705
- const result = await execute();
706
- ending = "completed";
707
- return result;
708
- } finally {
709
- await onQueryEnd(ending);
710
- }
711
- }
712
- async function notifyQueryCompletion(middleware, exec, ctx, result, swallowErrors) {
713
- for (const mw of middleware) {
714
- if (!mw.afterQuery) continue;
715
- if (swallowErrors) try {
716
- await mw.afterQuery(exec, result, ctx);
717
- } catch {}
718
- else await mw.afterQuery(exec, result, ctx);
719
- }
720
- }
721
- /**
722
- * Family-agnostic abstract runtime base.
723
- *
724
- * Defines the shared operation-specific middleware lifecycles:
725
- *
726
- * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides
727
- * this to run its shared `beforeCompile` middleware-hook chain.
728
- * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`
729
- * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).
730
- * 3. Queries run `beforeQuery`; statements run `beforeExecute`. Both chains
731
- * run after lowering and before their matching driver terminal. Family
732
- * runtimes that expose a params mutator to downstream encoding override
733
- * the operation and call the matching helper at the pre-encode point.
734
- * 4. The matching runner processes `interceptQuery` or `interceptExecute`
735
- * before invoking the driver. Queries then fire `onRow` and `afterQuery`;
736
- * statements fire `afterExecute`.
737
- * 5. Every operation whose lowering (which encodes parameters) and before-hooks
738
- * succeeded fires `afterTransaction` once, as its last hook: `committed`
739
- * when it completed, `unknown` when it threw or the caller stopped reading
740
- * its rows. `reportQueryEnding` and `reportExecuteEnding` report how the
741
- * operation ended, and `onQueryEndOutsideTransaction` turns that into the
742
- * outcome; family runtimes that override `query` or `execute` call them
743
- * too, with {@link afterTransactionStageFor}.
744
- *
745
- * Concrete subclasses must implement `lower`, `runDriver`, `runExecute`, and
746
- * `close`.
747
- *
748
- * The class is generic over:
749
- * - `TPlan` — the family's pre-lowering plan type.
750
- * - `TExec` — the family's post-lowering (executable) plan type.
751
- * - `TMiddleware` — the family's middleware type. Constrained to
752
- * `RuntimeMiddleware<TExec>` because the operation-specific runners invoke
753
- * hooks with the lowered `TExec`. Middleware therefore sees the
754
- * post-lowering plan.
755
- */
756
- var RuntimeCore = class {
757
- middleware;
758
- ctx;
759
- anyMiddlewareDeclaresAfterTransaction;
760
- constructor(options) {
761
- this.middleware = [...options.middleware];
762
- this.ctx = options.ctx;
763
- this.anyMiddlewareDeclaresAfterTransaction = this.middleware.some((mw) => mw.afterTransaction !== void 0);
764
- }
765
- /**
766
- * 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.
767
- */
768
- afterTransactionStageFor(exec, ctx) {
769
- if (!this.anyMiddlewareDeclaresAfterTransaction) return void 0;
770
- return (result) => runAfterTransaction(exec, this.middleware, result, ctx);
771
- }
772
- /**
773
- * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses
774
- * may override to run a `beforeCompile` middleware chain (SQL does this
775
- * to support typed AST rewrites — see `before-compile-chain.ts`).
776
- */
777
- runBeforeCompile(plan) {
778
- return plan;
779
- }
780
- query(plan, options) {
781
- const self = this;
782
- const signal = options?.signal;
783
- const codecCtx = signal === void 0 ? {} : { signal };
784
- const execCtx = {
785
- ...self.ctx,
786
- ...codecCtx,
787
- scope: options?.scope ?? self.ctx.scope,
788
- planExecutionId: crypto.randomUUID()
789
- };
790
- async function* generator() {
791
- checkAborted(codecCtx, "stream");
792
- const compiled = await self.runBeforeCompile(plan);
793
- const exec = await self.lower(compiled, codecCtx);
794
- await runBeforeQueryChain(exec, self.middleware, execCtx);
795
- yield* reportQueryEnding(onQueryEndOutsideTransaction(self.afterTransactionStageFor(exec, execCtx)), () => runQueryWithMiddleware(exec, self.middleware, execCtx, () => blindCast(self.runDriver(exec))));
796
- }
797
- return new AsyncIterableResult(generator());
798
- }
799
- async execute(plan, options) {
800
- const signal = options?.signal;
801
- const codecCtx = signal === void 0 ? {} : { signal };
802
- const execCtx = {
803
- ...this.ctx,
804
- ...codecCtx,
805
- scope: options?.scope ?? this.ctx.scope,
806
- planExecutionId: crypto.randomUUID()
807
- };
808
- checkAborted(codecCtx, "stream");
809
- const compiled = await this.runBeforeCompile(plan);
810
- const exec = await this.lower(compiled, codecCtx);
811
- await runBeforeExecuteChain(exec, this.middleware, execCtx);
812
- return reportExecuteEnding(onQueryEndOutsideTransaction(this.afterTransactionStageFor(exec, execCtx)), () => runExecuteWithMiddleware(exec, this.middleware, execCtx, () => this.runExecute(exec)));
813
- }
814
- };
815
- function checkMiddlewareCompatibility(middleware, runtimeFamilyId, runtimeTargetId) {
816
- if (middleware.targetId !== void 0 && middleware.familyId === void 0) throw runtimeError("RUNTIME.MIDDLEWARE_INCOMPATIBLE", `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`, {
817
- middleware: middleware.name,
818
- targetId: middleware.targetId
819
- });
820
- if (middleware.familyId !== void 0 && middleware.familyId !== runtimeFamilyId) throw runtimeError("RUNTIME.MIDDLEWARE_FAMILY_MISMATCH", `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`, {
821
- middleware: middleware.name,
822
- middlewareFamilyId: middleware.familyId,
823
- runtimeFamilyId
824
- });
825
- if (middleware.targetId !== void 0 && middleware.targetId !== runtimeTargetId) throw runtimeError("RUNTIME.MIDDLEWARE_TARGET_MISMATCH", `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`, {
826
- middleware: middleware.name,
827
- middlewareTargetId: middleware.targetId,
828
- runtimeTargetId
829
- });
830
- }
831
- /**
832
- * Phantom key an emitted model type carries to name its relation properties.
833
- * Never present at runtime; `Scalars` and `Shape` read it to tell relations from fields.
834
- */
835
- const RelationKeys = Symbol("RelationKeys");
836
- var MetaBuilderImpl = class {
837
- #kind;
838
- #terminalName;
839
- #annotations = /* @__PURE__ */ new Map();
840
- constructor(kind, terminalName) {
841
- this.#kind = kind;
842
- this.#terminalName = terminalName;
843
- }
844
- get annotations() {
845
- return this.#annotations;
846
- }
847
- annotate(annotation) {
848
- const value = annotation;
849
- assertAnnotationsApplicable([value], this.#kind, this.#terminalName);
850
- this.#annotations.set(value.namespace, value);
851
- return this;
852
- }
853
- };
854
- /**
855
- * Construct a lane-side meta builder for a terminal of operation kind `K`.
856
- *
857
- * Lane terminals call this with their `kind` (`'read'` or `'write'`) and a
858
- * `terminalName` for error messages, hand the resulting builder to the
859
- * user-supplied configurator callback (typed as `MetaBuilder<K>`, the
860
- * narrower public view), and read `meta.annotations` afterwards to thread
861
- * the recorded values into `plan.meta.annotations`.
862
- */
863
- function createMetaBuilder(kind, terminalName) {
864
- return new MetaBuilderImpl(kind, terminalName);
865
- }
866
- //#endregion
867
- export { runtimeAborted as S, runAfterTransaction as _, applyMutationDefaults as a, runExecuteWithMiddleware as b, checkAborted as c, createMetaBuilder as d, defineAnnotation as f, reportQueryEnding as g, reportExecuteEnding as h, RuntimeCore as i, checkMiddlewareCompatibility as l, raceAgainstAbort as m, RUNTIME_ABORTED as n, assertAnnotationsApplicable as o, onQueryEndOutsideTransaction as p, RelationKeys as r, assertMutationDefaultGeneratorsAvailable as s, AsyncIterableResult as t, collectMutationDefaultGenerators as u, runBeforeExecuteChain as v, runQueryWithMiddleware as x, runBeforeQueryChain as y };
868
-
869
- //# sourceMappingURL=runtime-7NCyLoeP.mjs.map