@prisma/orm-framework 8.0.0-rc.17-dev.26 → 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.
@@ -0,0 +1,809 @@
1
+ import { t as blindCast } from "./casts-DpaahrlC-Bd5n2coI.mjs";
2
+ import { t as InternalError } from "./internal-error-ChGYPVpq-DhUD05u0.mjs";
3
+ import { n as runtimeError } from "./runtime-error-BA9d7XjZ-BlT8t6LB.mjs";
4
+ //#region ../../../1-framework/1-core/framework-components/dist/runtime.mjs
5
+ /**
6
+ * Stable code emitted by the runtime when an in-flight `execute()`
7
+ * is cancelled via the per-query `AbortSignal`. The envelope's
8
+ * `details.phase` distinguishes where the abort was observed:
9
+ *
10
+ * - `'encode'` — abort fired during `encodeParams` (SQL) or
11
+ * `resolveValue` (Mongo).
12
+ * - `'decode'` — abort fired during `decodeRow` / `decodeField`.
13
+ * - `'stream'` — abort fired between rows or before any codec call
14
+ * (already-aborted at entry).
15
+ * - `'beforeEncode'` / `'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(source) {
83
+ const stored = "meta" in source ? source.meta.annotations?.[namespace] : source.annotations.get(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
+ const noAnnotations = /* @__PURE__ */ new Map();
127
+ /** The branded annotation values in a plan's `meta.annotations`, keyed by namespace. */
128
+ function brandedAnnotations(annotations) {
129
+ if (annotations === void 0) return noAnnotations;
130
+ let branded;
131
+ for (const [namespace, value] of Object.entries(annotations)) {
132
+ if (!isAnnotationValue(value)) continue;
133
+ branded ??= /* @__PURE__ */ new Map();
134
+ branded.set(namespace, value);
135
+ }
136
+ return branded ?? noAnnotations;
137
+ }
138
+ /**
139
+ * Type guard for branded annotation values stored in `plan.meta.annotations`.
140
+ *
141
+ * Internal — used by `AnnotationHandle.read` to distinguish user
142
+ * annotations (created by calling a handle returned from
143
+ * `defineAnnotation(...)`) from framework-internal metadata that may
144
+ * happen to live under the same namespace key.
145
+ */
146
+ function isAnnotationValue(value) {
147
+ if (value === null || typeof value !== "object") return false;
148
+ return value.__annotation === true;
149
+ }
150
+ function createStateStore() {
151
+ let states;
152
+ return {
153
+ state(key) {
154
+ states ??= /* @__PURE__ */ new Map();
155
+ let state = states.get(key);
156
+ if (state === void 0) {
157
+ state = {};
158
+ states.set(key, state);
159
+ }
160
+ return state;
161
+ },
162
+ clear() {
163
+ states = void 0;
164
+ }
165
+ };
166
+ }
167
+ function createActivityRecord(middleware, activity, fields, parent) {
168
+ const store = createStateStore();
169
+ let finalized = false;
170
+ let started = middleware.length;
171
+ const parentCtx = parent?.ctx;
172
+ const parentIsTransaction = parent?.activity.kind === "transaction";
173
+ const ctx = blindCast({
174
+ ...fields,
175
+ parent: parentCtx,
176
+ state: store.state,
177
+ inTransaction: () => parentIsTransaction || (parentCtx?.inTransaction() ?? false)
178
+ });
179
+ return {
180
+ activity,
181
+ ctx,
182
+ async started() {
183
+ for (let index = 0; index < middleware.length; index++) {
184
+ const mw = middleware[index];
185
+ if (!mw?.activityStarted) continue;
186
+ try {
187
+ await mw.activityStarted(activity, ctx);
188
+ } catch (error) {
189
+ started = index + 1;
190
+ throw error;
191
+ }
192
+ }
193
+ },
194
+ async ended(result) {
195
+ let firstError;
196
+ for (let index = 0; index < started; index++) {
197
+ const mw = middleware[index];
198
+ if (!mw?.activityEnded) continue;
199
+ try {
200
+ await mw.activityEnded(activity, result, ctx);
201
+ } catch (error) {
202
+ if (result.outcome === "succeeded") firstError ??= { error };
203
+ else logHookError(ctx, "middleware.activityEnded.error", mw.name, error);
204
+ }
205
+ }
206
+ if (firstError !== void 0) throw firstError.error;
207
+ },
208
+ async finalize(result) {
209
+ if (finalized) return;
210
+ finalized = true;
211
+ for (let index = 0; index < started; index++) {
212
+ const mw = middleware[index];
213
+ if (!mw?.activityFinalized) continue;
214
+ try {
215
+ await mw.activityFinalized(activity, result, ctx);
216
+ } catch (error) {
217
+ logHookError(ctx, "middleware.activityFinalized.error", mw.name, error);
218
+ }
219
+ }
220
+ store.clear();
221
+ }
222
+ };
223
+ }
224
+ function logHookError(ctx, event, middleware, error) {
225
+ try {
226
+ ctx.log.error({
227
+ event,
228
+ middleware,
229
+ error
230
+ });
231
+ } catch {}
232
+ }
233
+ /**
234
+ * Ends an activity: its `activityEnded` hooks, then its finalization, which a parent holds or which happens at once with `committed` or `unknown`. The finalization runs even when an `activityEnded` hook fails the activity; that error is rethrown afterwards.
235
+ */
236
+ async function endActivity(record, result, childEnded) {
237
+ let endedError;
238
+ try {
239
+ await record.ended(result);
240
+ } catch (error) {
241
+ endedError = { error };
242
+ }
243
+ if (childEnded === void 0) await record.finalize({ outcome: result.outcome === "succeeded" ? "committed" : "unknown" });
244
+ else await childEnded(result.outcome);
245
+ if (endedError !== void 0) throw endedError.error;
246
+ }
247
+ var AsyncIterableResult = class {
248
+ generator;
249
+ consumed = false;
250
+ consumedBy;
251
+ bufferedArrayPromise;
252
+ constructor(generator) {
253
+ this.generator = generator;
254
+ }
255
+ [Symbol.asyncIterator]() {
256
+ 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.`, {
257
+ consumedBy: this.consumedBy,
258
+ 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."
259
+ });
260
+ this.consumed = true;
261
+ this.consumedBy = "iterator";
262
+ return this.generator;
263
+ }
264
+ toArray() {
265
+ 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.", {
266
+ consumedBy: this.consumedBy,
267
+ suggestion: "The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating."
268
+ }));
269
+ if (this.bufferedArrayPromise) return this.bufferedArrayPromise;
270
+ this.consumed = true;
271
+ this.consumedBy = "bufferedArray";
272
+ this.bufferedArrayPromise = (async () => {
273
+ const out = [];
274
+ for await (const item of this.generator) out.push(item);
275
+ return out;
276
+ })();
277
+ return this.bufferedArrayPromise;
278
+ }
279
+ async first() {
280
+ return (await this.toArray())[0] ?? null;
281
+ }
282
+ async firstOrThrow() {
283
+ const row = await this.first();
284
+ if (row === null) throw runtimeError("RUNTIME.NO_ROWS", "Expected at least one row, but none were returned", {});
285
+ return row;
286
+ }
287
+ then(onfulfilled, onrejected) {
288
+ return this.toArray().then(onfulfilled, onrejected);
289
+ }
290
+ };
291
+ /** Registers every generator the contributors provide, by id. Two contributors providing one id is an error naming both. */
292
+ function collectMutationDefaultGenerators(contributors) {
293
+ const generators = /* @__PURE__ */ new Map();
294
+ const owners = /* @__PURE__ */ new Map();
295
+ for (const contributor of contributors) {
296
+ const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];
297
+ for (const generator of nextGenerators) {
298
+ const existingOwner = owners.get(generator.id);
299
+ if (existingOwner !== void 0) throw runtimeError("RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR", `Duplicate mutation default generator '${generator.id}'.`, {
300
+ id: generator.id,
301
+ existingOwner,
302
+ incomingOwner: contributor.id
303
+ });
304
+ generators.set(generator.id, generator);
305
+ owners.set(generator.id, contributor.id);
306
+ }
307
+ }
308
+ return generators;
309
+ }
310
+ /** 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. */
311
+ function assertMutationDefaultGeneratorsAvailable(execution, generatorRegistry) {
312
+ const defaults = execution?.mutations.defaults ?? [];
313
+ if (defaults.length === 0) return;
314
+ const fieldsById = /* @__PURE__ */ new Map();
315
+ for (const mutationDefault of defaults) {
316
+ const phaseIds = new Set([mutationDefault.onCreate, mutationDefault.onUpdate].flatMap((phase) => phase?.kind === "generator" && !generatorRegistry.has(phase.id) ? [phase.id] : []));
317
+ for (const id of phaseIds) {
318
+ const fields = fieldsById.get(id) ?? [];
319
+ fields.push(`${mutationDefault.ref.entry}.${mutationDefault.ref.field}`);
320
+ fieldsById.set(id, fields);
321
+ }
322
+ }
323
+ if (fieldsById.size === 0) return;
324
+ const ids = [...fieldsById.keys()];
325
+ const needs = [...fieldsById].map(([id, fields]) => `'${id}' for ${listInProse(fields)}`);
326
+ 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}`, {
327
+ ids,
328
+ fields: [...fieldsById.values()].flat()
329
+ });
330
+ }
331
+ 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.";
332
+ function listInProse(items) {
333
+ return items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}` : items.join("");
334
+ }
335
+ function computeExecutionDefaultValue(spec, generatorRegistry) {
336
+ const generator = generatorRegistry.get(spec.id);
337
+ 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 });
338
+ return generator.generate(spec.params);
339
+ }
340
+ /**
341
+ * 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.
342
+ */
343
+ function applyMutationDefaults(execution, generatorRegistry, options) {
344
+ const defaults = execution?.mutations.defaults ?? [];
345
+ if (defaults.length === 0) return [];
346
+ const isEmptyUpdate = options.op === "update" && Object.keys(options.values).length === 0;
347
+ const applied = [];
348
+ const appliedFields = /* @__PURE__ */ new Set();
349
+ const rowCache = /* @__PURE__ */ new Map();
350
+ for (const mutationDefault of defaults) {
351
+ if (mutationDefault.ref.entry !== options.entry) continue;
352
+ if (mutationDefault.ref.namespace !== options.namespace) continue;
353
+ const defaultSpec = options.op === "create" ? mutationDefault.onCreate : mutationDefault.onUpdate;
354
+ if (!defaultSpec) continue;
355
+ if (isEmptyUpdate) continue;
356
+ const fieldName = mutationDefault.ref.field;
357
+ if (Object.hasOwn(options.values, fieldName) || appliedFields.has(fieldName)) continue;
358
+ applied.push({
359
+ field: fieldName,
360
+ value: resolveScopedValue(defaultSpec, generatorRegistry, rowCache, options.defaultValueCache)
361
+ });
362
+ appliedFields.add(fieldName);
363
+ }
364
+ return applied;
365
+ }
366
+ function resolveScopedValue(spec, generatorRegistry, rowCache, queryCache) {
367
+ const cache = scopedCache(generatorRegistry.get(spec.id)?.stability, rowCache, queryCache);
368
+ if (!cache) return computeExecutionDefaultValue(spec, generatorRegistry);
369
+ if (cache.has(spec.id)) return cache.get(spec.id);
370
+ const value = computeExecutionDefaultValue(spec, generatorRegistry);
371
+ cache.set(spec.id, value);
372
+ return value;
373
+ }
374
+ function scopedCache(stability, rowCache, queryCache) {
375
+ switch (stability) {
376
+ case "row": return rowCache;
377
+ case "query": return queryCache;
378
+ default: return;
379
+ }
380
+ }
381
+ /**
382
+ * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied
383
+ * context is already aborted at the precheck site. Centralises the
384
+ * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that
385
+ * every codec dispatch site (and the `beforeEncode` middleware phase)
386
+ * repeats. Accepts both the framework `CodecCallContext` and the
387
+ * `ActivityContext`; both expose `signal?: AbortSignal`.
388
+ */
389
+ function checkAborted(ctx, phase) {
390
+ if (ctx.signal?.aborted) throw runtimeAborted(phase, ctx.signal.reason);
391
+ }
392
+ /**
393
+ * Race a per-cell `Promise.all` (or any other in-flight work promise) against
394
+ * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly
395
+ * even when codec bodies ignore the signal. In-flight bodies that ignore the
396
+ * signal are abandoned and run to completion in the background — the
397
+ * cooperative-cancellation contract documented in ADR 204.
398
+ *
399
+ * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with
400
+ * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —
401
+ * that path is the canonical "aborted at entry" surface and avoids
402
+ * scheduling the work promise. As a defensive belt-and-braces, this helper
403
+ * also handles the already-aborted case internally: `AbortSignal` does not
404
+ * replay past abort events to listeners registered after the abort, so we
405
+ * inspect `signal.aborted` synchronously and reject with the sentinel
406
+ * before installing the listener. The rejection is still attributed to the
407
+ * abort path via the sentinel-identity check.
408
+ *
409
+ * Distinguishing the rejection source is load-bearing for AC-ERR4
410
+ * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).
411
+ * The semantically equivalent `abortable(signal)` helper in
412
+ * `@internal/utils` rejects with `signal.reason ?? new DOMException(...)`,
413
+ * which is not stably distinguishable from a codec-thrown error by identity
414
+ * alone (a fresh fallback DOMException is allocated per call). We instead
415
+ * track abort attribution with a unique sentinel: only the `onAbort` listener
416
+ * installed here ever rejects with the sentinel, so an `error === sentinel`
417
+ * identity check after the race is unambiguous.
418
+ *
419
+ * Lives in `framework-components` (rather than the SQL family, where it
420
+ * originated in m2) so every family runtime that needs cooperative
421
+ * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode
422
+ * today, Mongo encode in m3) shares the same attribution logic.
423
+ */
424
+ async function raceAgainstAbort(work, signal, phase) {
425
+ if (signal === void 0) return await work;
426
+ const sentinel = { reason: void 0 };
427
+ let onAbort;
428
+ const abortPromise = new Promise((_, reject) => {
429
+ if (signal.aborted) {
430
+ sentinel.reason = signal.reason;
431
+ reject(sentinel);
432
+ return;
433
+ }
434
+ onAbort = () => {
435
+ sentinel.reason = signal.reason;
436
+ reject(sentinel);
437
+ };
438
+ signal.addEventListener("abort", onAbort, { once: true });
439
+ });
440
+ try {
441
+ return await Promise.race([work, abortPromise]);
442
+ } catch (error) {
443
+ if (error === sentinel) throw runtimeAborted(phase, sentinel.reason);
444
+ throw error;
445
+ } finally {
446
+ if (onAbort) signal.removeEventListener("abort", onAbort);
447
+ }
448
+ }
449
+ /**
450
+ * Runs one `query()` statement as an activity. The activity starts on the first `next()`: `activityStarted`, then `body`'s rows, then `activityEnded` and, with no parent, `activityFinalized`. Each fires exactly once, whether the body succeeds, throws (`failed`) or the caller stops reading (`stopped`).
451
+ */
452
+ function streamStatement(options, body) {
453
+ return { [Symbol.asyncIterator]() {
454
+ let thrownByCaller;
455
+ const generator = streamStatementRows(options, body, (error) => thrownByCaller !== void 0 && thrownByCaller.error === error);
456
+ return {
457
+ next: () => generator.next(),
458
+ return: () => generator.return(void 0),
459
+ throw: (error) => {
460
+ thrownByCaller = { error };
461
+ return generator.throw(error);
462
+ }
463
+ };
464
+ } };
465
+ }
466
+ async function* streamStatementRows(options, body, isThrownByCaller) {
467
+ const statement = new StatementActivityRunImpl(options, "rows");
468
+ let outcome = "stopped";
469
+ try {
470
+ await statement.start();
471
+ yield* body(statement);
472
+ outcome = "succeeded";
473
+ } catch (error) {
474
+ if (!isThrownByCaller(error)) outcome = "failed";
475
+ throw error;
476
+ } finally {
477
+ await statement.end(outcome);
478
+ }
479
+ }
480
+ /**
481
+ * Runs one `execute()` statement as an activity: `activityStarted`, then `body`, then `activityEnded` and, with no parent, `activityFinalized`, each exactly once.
482
+ */
483
+ async function executeStatement(options, body) {
484
+ const statement = new StatementActivityRunImpl(options, "stats");
485
+ let outcome = "failed";
486
+ try {
487
+ await statement.start();
488
+ const stats = await body(statement);
489
+ outcome = "succeeded";
490
+ return stats;
491
+ } finally {
492
+ await statement.end(outcome);
493
+ }
494
+ }
495
+ var StatementActivityRunImpl = class {
496
+ activity;
497
+ ctx;
498
+ #middleware;
499
+ #parent;
500
+ #record;
501
+ #childEnded;
502
+ #runStartedAt;
503
+ #source = "driver";
504
+ #rowCount = 0;
505
+ #stats;
506
+ constructor(options, returns) {
507
+ const { plan } = options;
508
+ let annotations;
509
+ this.activity = {
510
+ id: crypto.randomUUID(),
511
+ kind: "statement",
512
+ returns,
513
+ plan,
514
+ get annotations() {
515
+ annotations ??= brandedAnnotations(plan.meta.annotations);
516
+ return annotations;
517
+ }
518
+ };
519
+ this.#middleware = options.middleware;
520
+ this.#parent = options.parent;
521
+ this.#record = createActivityRecord(options.middleware, this.activity, options.context, options.parent);
522
+ this.ctx = this.#record.ctx;
523
+ }
524
+ start() {
525
+ this.#childEnded = this.#parent?.adopt(this.#record);
526
+ return this.#record.started();
527
+ }
528
+ end(outcome) {
529
+ return endActivity(this.#record, this.#endedResult(outcome), this.#childEnded);
530
+ }
531
+ async beforeEncode(draft, params) {
532
+ for (const mw of this.#middleware) {
533
+ if (!mw.beforeEncode) continue;
534
+ checkAborted(this.ctx, "beforeEncode");
535
+ const work = mw.beforeEncode(draft, this.ctx, params);
536
+ if (work !== void 0) await raceAgainstAbort(Promise.resolve(work), this.ctx.signal, "beforeEncode");
537
+ }
538
+ }
539
+ async *runQuery(exec, runDriver) {
540
+ this.#runStartedAt = Date.now();
541
+ let rows;
542
+ for (const mw of this.#middleware) {
543
+ const intercept = mw.intercept;
544
+ if (intercept?.onQuery === void 0) continue;
545
+ this.#source = "middleware";
546
+ const result = await intercept.onQuery(exec, this.ctx);
547
+ if (result === void 0) {
548
+ this.#source = "driver";
549
+ continue;
550
+ }
551
+ this.ctx.log.debug?.({
552
+ event: "middleware.intercept.onQuery",
553
+ middleware: mw.name
554
+ });
555
+ rows = blindCast(result.rows);
556
+ break;
557
+ }
558
+ if (rows === void 0) {
559
+ for await (const row of runDriver()) {
560
+ for (const mw of this.#middleware) if (mw.onRow) await mw.onRow(blindCast(row), exec, this.ctx);
561
+ this.#rowCount++;
562
+ yield row;
563
+ }
564
+ return;
565
+ }
566
+ for await (const row of rows) {
567
+ this.#rowCount++;
568
+ yield row;
569
+ }
570
+ }
571
+ async runExecute(exec, runDriver) {
572
+ this.#runStartedAt = Date.now();
573
+ for (const mw of this.#middleware) {
574
+ const intercept = mw.intercept;
575
+ if (intercept?.onExecute === void 0) continue;
576
+ this.#source = "middleware";
577
+ const result = await intercept.onExecute(exec, this.ctx);
578
+ if (result === void 0) {
579
+ this.#source = "driver";
580
+ continue;
581
+ }
582
+ this.ctx.log.debug?.({
583
+ event: "middleware.intercept.onExecute",
584
+ middleware: mw.name
585
+ });
586
+ this.#stats = result.stats;
587
+ return result.stats;
588
+ }
589
+ this.#stats = await runDriver();
590
+ return this.#stats;
591
+ }
592
+ #endedResult(outcome) {
593
+ const base = {
594
+ kind: "statement",
595
+ outcome,
596
+ latencyMs: this.#runStartedAt === void 0 ? 0 : Date.now() - this.#runStartedAt,
597
+ source: this.#source
598
+ };
599
+ if (this.activity.returns === "rows") return {
600
+ ...base,
601
+ returns: "rows",
602
+ rowCount: this.#rowCount
603
+ };
604
+ return outcome === "succeeded" && this.#stats !== void 0 ? {
605
+ ...base,
606
+ returns: "stats",
607
+ stats: this.#stats
608
+ } : {
609
+ ...base,
610
+ returns: "stats"
611
+ };
612
+ }
613
+ };
614
+ /**
615
+ * Family-agnostic abstract runtime base. Each `query()` and `execute()` call is one statement activity, run in this order: `activityStarted`, `runBeforeCompile`, `lower`, `beforeEncode`, `intercept`, the driver with `onRow`, `activityEnded`, then `activityFinalized`. It has no parent, so it is finalized right after it ends.
616
+ *
617
+ * Concrete subclasses implement `lower`, `runDriver`, `runExecute` and `close`.
618
+ */
619
+ var RuntimeCore = class {
620
+ middleware;
621
+ ctx;
622
+ constructor(options) {
623
+ this.middleware = [...options.middleware];
624
+ this.ctx = options.ctx;
625
+ }
626
+ /** Pre-lowering hook for plan rewriting. Defaults to identity. */
627
+ runBeforeCompile(plan) {
628
+ return plan;
629
+ }
630
+ query(plan, options) {
631
+ const self = this;
632
+ const codecCtx = codecContextOf(options);
633
+ const statement = streamStatement({
634
+ middleware: this.middleware,
635
+ plan,
636
+ context: this.contextFieldsFor(codecCtx, options),
637
+ parent: void 0
638
+ }, async function* (run) {
639
+ checkAborted(codecCtx, "stream");
640
+ const compiled = await self.runBeforeCompile(plan);
641
+ const exec = await self.lower(compiled, codecCtx);
642
+ await run.beforeEncode(exec);
643
+ yield* run.runQuery(exec, () => blindCast(self.runDriver(exec)));
644
+ });
645
+ async function* generator() {
646
+ yield* statement;
647
+ }
648
+ return new AsyncIterableResult(generator());
649
+ }
650
+ execute(plan, options) {
651
+ const codecCtx = codecContextOf(options);
652
+ return executeStatement({
653
+ middleware: this.middleware,
654
+ plan,
655
+ context: this.contextFieldsFor(codecCtx, options),
656
+ parent: void 0
657
+ }, async (run) => {
658
+ checkAborted(codecCtx, "stream");
659
+ const compiled = await this.runBeforeCompile(plan);
660
+ const exec = await this.lower(compiled, codecCtx);
661
+ await run.beforeEncode(exec);
662
+ return run.runExecute(exec, () => this.runExecute(exec));
663
+ });
664
+ }
665
+ contextFieldsFor(codecCtx, options) {
666
+ return {
667
+ ...this.ctx,
668
+ ...codecCtx,
669
+ scope: options?.scope ?? this.ctx.scope
670
+ };
671
+ }
672
+ };
673
+ function codecContextOf(options) {
674
+ const signal = options?.signal;
675
+ return signal === void 0 ? {} : { signal };
676
+ }
677
+ function checkMiddlewareCompatibility(middleware, runtimeFamilyId, runtimeTargetId) {
678
+ if (middleware.targetId !== void 0 && middleware.familyId === void 0) throw runtimeError("RUNTIME.MIDDLEWARE_INCOMPATIBLE", `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`, {
679
+ middleware: middleware.name,
680
+ targetId: middleware.targetId
681
+ });
682
+ 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}'`, {
683
+ middleware: middleware.name,
684
+ middlewareFamilyId: middleware.familyId,
685
+ runtimeFamilyId
686
+ });
687
+ 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}'`, {
688
+ middleware: middleware.name,
689
+ middlewareTargetId: middleware.targetId,
690
+ runtimeTargetId
691
+ });
692
+ }
693
+ /**
694
+ * Phantom key an emitted model type carries to name its relation properties.
695
+ * Never present at runtime; `Scalars` and `Shape` read it to tell relations from fields.
696
+ */
697
+ const RelationKeys = Symbol("RelationKeys");
698
+ /**
699
+ * Starts a transaction activity and runs its `activityStarted` hooks. When one of them throws, the transaction ends `failed`, is finalized `rolled-back`, and the error is rethrown.
700
+ */
701
+ async function startTransactionActivity(options) {
702
+ const run = new TransactionActivityRunImpl(options);
703
+ try {
704
+ await run.start();
705
+ } catch (error) {
706
+ await run.end({
707
+ by: "rollback",
708
+ outcome: "failed",
709
+ commitAttempted: false
710
+ });
711
+ throw error;
712
+ }
713
+ return run;
714
+ }
715
+ var TransactionActivityRunImpl = class {
716
+ activity;
717
+ ctx;
718
+ #record;
719
+ #children = [];
720
+ #aChildFailed = false;
721
+ #ended = false;
722
+ #finalized;
723
+ #holdFinishedChildren;
724
+ constructor(options) {
725
+ this.activity = {
726
+ id: crypto.randomUUID(),
727
+ kind: "transaction",
728
+ annotations: brandedAnnotations(void 0)
729
+ };
730
+ this.#record = createActivityRecord(options.middleware, this.activity, options.context, void 0);
731
+ this.ctx = this.#record.ctx;
732
+ this.#holdFinishedChildren = options.holdFinishedChildren;
733
+ }
734
+ start() {
735
+ return this.#record.started();
736
+ }
737
+ adopt(child) {
738
+ if (this.#ended) throw new InternalError("An activity was started beneath a transaction that has ended");
739
+ if (!this.#holdFinishedChildren) return async (outcome) => {
740
+ if (outcome === "failed") this.#aChildFailed = true;
741
+ };
742
+ const entry = {
743
+ child,
744
+ ended: false
745
+ };
746
+ this.#children.push(entry);
747
+ return async (outcome) => {
748
+ entry.ended = true;
749
+ if (outcome === "failed") this.#aChildFailed = true;
750
+ if (this.#finalized !== void 0) await child.finalize(this.#finalized);
751
+ };
752
+ }
753
+ async end(settlement) {
754
+ if (this.#ended) return;
755
+ this.#ended = true;
756
+ let endedError;
757
+ try {
758
+ await this.#record.ended({
759
+ kind: "transaction",
760
+ outcome: settlement.outcome
761
+ });
762
+ } catch (error) {
763
+ endedError = { error };
764
+ }
765
+ const finalized = this.#finalizedResult(settlement);
766
+ this.#finalized = finalized;
767
+ for (const { child, ended } of this.#children.splice(0)) if (ended) await child.finalize(finalized);
768
+ await this.#record.finalize(finalized);
769
+ if (endedError !== void 0) throw endedError.error;
770
+ }
771
+ #finalizedResult(settlement) {
772
+ if (settlement.by === "rollback") return { outcome: settlement.commitAttempted ? "unknown" : "rolled-back" };
773
+ return { outcome: settlement.outcome === "succeeded" && !this.#aChildFailed ? "committed" : "unknown" };
774
+ }
775
+ };
776
+ var MetaBuilderImpl = class {
777
+ #kind;
778
+ #terminalName;
779
+ #annotations = /* @__PURE__ */ new Map();
780
+ constructor(kind, terminalName) {
781
+ this.#kind = kind;
782
+ this.#terminalName = terminalName;
783
+ }
784
+ get annotations() {
785
+ return this.#annotations;
786
+ }
787
+ annotate(annotation) {
788
+ const value = annotation;
789
+ assertAnnotationsApplicable([value], this.#kind, this.#terminalName);
790
+ this.#annotations.set(value.namespace, value);
791
+ return this;
792
+ }
793
+ };
794
+ /**
795
+ * Construct a lane-side meta builder for a terminal of operation kind `K`.
796
+ *
797
+ * Lane terminals call this with their `kind` (`'read'` or `'write'`) and a
798
+ * `terminalName` for error messages, hand the resulting builder to the
799
+ * user-supplied configurator callback (typed as `MetaBuilder<K>`, the
800
+ * narrower public view), and read `meta.annotations` afterwards to thread
801
+ * the recorded values into `plan.meta.annotations`.
802
+ */
803
+ function createMetaBuilder(kind, terminalName) {
804
+ return new MetaBuilderImpl(kind, terminalName);
805
+ }
806
+ //#endregion
807
+ export { startTransactionActivity as _, applyMutationDefaults as a, checkAborted as c, createMetaBuilder as d, createStateStore as f, runtimeAborted as g, raceAgainstAbort as h, RuntimeCore as i, checkMiddlewareCompatibility as l, executeStatement as m, RUNTIME_ABORTED as n, assertAnnotationsApplicable as o, defineAnnotation as p, RelationKeys as r, assertMutationDefaultGeneratorsAvailable as s, AsyncIterableResult as t, collectMutationDefaultGenerators as u, streamStatement as v };
808
+
809
+ //# sourceMappingURL=runtime-DoZkleC9.mjs.map