@prisma-next/framework-components 0.5.0-dev.8 → 0.5.0-dev.80
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.
- package/README.md +53 -4
- package/dist/authoring.d.mts +2 -2
- package/dist/authoring.mjs +2 -122
- package/dist/codec-m_-FAyQn.d.mts +168 -0
- package/dist/codec-m_-FAyQn.d.mts.map +1 -0
- package/dist/codec.d.mts +48 -2
- package/dist/codec.d.mts.map +1 -0
- package/dist/codec.mjs +67 -4
- package/dist/codec.mjs.map +1 -1
- package/dist/components.d.mts +1 -1
- package/dist/components.mjs +2 -3
- package/dist/control.d.mts +420 -74
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +83 -49
- package/dist/control.mjs.map +1 -1
- package/dist/emission-types-BKa4bR9m.d.mts +39 -0
- package/dist/emission-types-BKa4bR9m.d.mts.map +1 -0
- package/dist/emission.d.mts +2 -2
- package/dist/emission.mjs +1 -1
- package/dist/execution.d.mts +5 -5
- package/dist/execution.d.mts.map +1 -1
- package/dist/execution.mjs +4 -6
- package/dist/execution.mjs.map +1 -1
- package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-DGIQbNPt.d.mts} +43 -12
- package/dist/framework-authoring-DGIQbNPt.d.mts.map +1 -0
- package/dist/framework-authoring-DxXcjyJX.mjs +209 -0
- package/dist/framework-authoring-DxXcjyJX.mjs.map +1 -0
- package/dist/{framework-components-DFZMi2h7.d.mts → framework-components-BGo7HsbL.d.mts} +45 -55
- package/dist/framework-components-BGo7HsbL.d.mts.map +1 -0
- package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-FdqmlGUj.mjs} +3 -3
- package/dist/framework-components-FdqmlGUj.mjs.map +1 -0
- package/dist/psl-ast-Ckn_G-jv.d.mts +159 -0
- package/dist/psl-ast-Ckn_G-jv.d.mts.map +1 -0
- package/dist/psl-ast.d.mts +2 -0
- package/dist/psl-ast.mjs +1 -0
- package/dist/runtime.d.mts +395 -19
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +256 -7
- package/dist/runtime.mjs.map +1 -1
- package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-BxI5cSQy.d.mts} +2 -2
- package/dist/types-import-spec-BxI5cSQy.d.mts.map +1 -0
- package/package.json +10 -6
- package/src/control/control-capabilities.ts +96 -0
- package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
- package/src/{control-instances.ts → control/control-instances.ts} +52 -6
- package/src/{control-migration-types.ts → control/control-migration-types.ts} +251 -63
- package/src/control/control-operation-preview.ts +23 -0
- package/src/control/control-spaces.ts +82 -0
- package/src/{control-stack.ts → control/control-stack.ts} +77 -94
- package/src/control/emission-types.ts +49 -0
- package/src/control/psl-ast.ts +193 -0
- package/src/{execution-descriptors.ts → execution/execution-descriptors.ts} +7 -7
- package/src/{execution-instances.ts → execution/execution-instances.ts} +1 -1
- package/src/{execution-requirements.ts → execution/execution-requirements.ts} +1 -1
- package/src/execution/query-plan.ts +53 -0
- package/src/execution/race-against-abort.ts +89 -0
- package/src/execution/run-with-middleware.ts +153 -0
- package/src/execution/runtime-core.ts +133 -0
- package/src/execution/runtime-error.ts +94 -0
- package/src/execution/runtime-middleware.ts +235 -0
- package/src/exports/authoring.ts +5 -2
- package/src/exports/codec.ts +27 -2
- package/src/exports/components.ts +2 -2
- package/src/exports/control.ts +41 -13
- package/src/exports/emission.ts +2 -2
- package/src/exports/execution.ts +5 -5
- package/src/exports/psl-ast.ts +1 -0
- package/src/exports/runtime.ts +18 -5
- package/src/shared/codec-descriptor.ts +87 -0
- package/src/shared/codec-types.ts +79 -0
- package/src/shared/codec.ts +80 -0
- package/src/shared/column-spec.ts +83 -0
- package/src/{framework-authoring.ts → shared/framework-authoring.ts} +210 -23
- package/src/{framework-components.ts → shared/framework-components.ts} +22 -48
- package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +22 -2
- package/dist/authoring.mjs.map +0 -1
- package/dist/codec-types-DQ1Agjom.d.mts +0 -58
- package/dist/codec-types-DQ1Agjom.d.mts.map +0 -1
- package/dist/emission-types-BPAALJbF.d.mts +0 -24
- package/dist/emission-types-BPAALJbF.d.mts.map +0 -1
- package/dist/framework-authoring-D1-JZ37B.d.mts.map +0 -1
- package/dist/framework-components-C8ZhSwXe.mjs.map +0 -1
- package/dist/framework-components-DFZMi2h7.d.mts.map +0 -1
- package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
- package/src/codec-types.ts +0 -64
- package/src/control-capabilities.ts +0 -34
- package/src/emission-types.ts +0 -28
- package/src/runtime-error.ts +0 -55
- package/src/runtime-middleware.ts +0 -83
- /package/src/{control-result-types.ts → control/control-result-types.ts} +0 -0
- /package/src/{control-schema-view.ts → control/control-schema-view.ts} +0 -0
- /package/src/{async-iterable-result.ts → execution/async-iterable-result.ts} +0 -0
- /package/src/{execution-stack.ts → execution/execution-stack.ts} +0 -0
- /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
package/dist/runtime.mjs
CHANGED
|
@@ -1,4 +1,19 @@
|
|
|
1
|
-
//#region src/runtime-error.ts
|
|
1
|
+
//#region src/execution/runtime-error.ts
|
|
2
|
+
/**
|
|
3
|
+
* Stable code emitted by the runtime when an in-flight `execute()`
|
|
4
|
+
* is cancelled via the per-query `AbortSignal`. The envelope's
|
|
5
|
+
* `details.phase` distinguishes where the abort was observed:
|
|
6
|
+
*
|
|
7
|
+
* - `'encode'` — abort fired during `encodeParams` (SQL) or
|
|
8
|
+
* `resolveValue` (Mongo).
|
|
9
|
+
* - `'decode'` — abort fired during `decodeRow` / `decodeField`.
|
|
10
|
+
* - `'stream'` — abort fired between rows or before any codec call
|
|
11
|
+
* (already-aborted at entry).
|
|
12
|
+
* - `'beforeExecute'` / `'afterExecute'` / `'onRow'` — abort fired
|
|
13
|
+
* on entry to or during the corresponding middleware phase
|
|
14
|
+
* (cooperative cancellation per the param-transform seam).
|
|
15
|
+
*/
|
|
16
|
+
const RUNTIME_ABORTED = "RUNTIME.ABORTED";
|
|
2
17
|
/**
|
|
3
18
|
* Type guard for the runtime-error envelope produced by `runtimeError`.
|
|
4
19
|
*
|
|
@@ -32,9 +47,21 @@ function resolveCategory(code) {
|
|
|
32
47
|
default: return "RUNTIME";
|
|
33
48
|
}
|
|
34
49
|
}
|
|
35
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the
|
|
52
|
+
* abort was observed — codec call sites (`encode` / `decode` / `stream`)
|
|
53
|
+
* or middleware seams (`beforeExecute` / `afterExecute` / `onRow`), as
|
|
54
|
+
* enumerated on {@link RuntimeAbortedPhase}. Cause carries
|
|
55
|
+
* `signal.reason` verbatim from the platform — native abort produces a
|
|
56
|
+
* `DOMException`, explicit `controller.abort(reason)` produces whatever
|
|
57
|
+
* the caller passed. No synthesis happens here.
|
|
58
|
+
*/
|
|
59
|
+
function runtimeAborted(phase, cause) {
|
|
60
|
+
const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });
|
|
61
|
+
return Object.assign(envelope, { cause });
|
|
62
|
+
}
|
|
36
63
|
//#endregion
|
|
37
|
-
//#region src/async-iterable-result.ts
|
|
64
|
+
//#region src/execution/async-iterable-result.ts
|
|
38
65
|
var AsyncIterableResult = class {
|
|
39
66
|
generator;
|
|
40
67
|
consumed = false;
|
|
@@ -79,9 +106,231 @@ var AsyncIterableResult = class {
|
|
|
79
106
|
return this.toArray().then(onfulfilled, onrejected);
|
|
80
107
|
}
|
|
81
108
|
};
|
|
82
|
-
|
|
83
109
|
//#endregion
|
|
84
|
-
//#region src/
|
|
110
|
+
//#region src/execution/race-against-abort.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
|
+
function checkAborted(ctx, phase) {
|
|
120
|
+
if (ctx.signal?.aborted) throw runtimeAborted(phase, ctx.signal.reason);
|
|
121
|
+
}
|
|
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
|
+
async function raceAgainstAbort(work, signal, phase) {
|
|
155
|
+
if (signal === void 0) return await work;
|
|
156
|
+
const sentinel = { reason: void 0 };
|
|
157
|
+
let onAbort;
|
|
158
|
+
const abortPromise = new Promise((_, reject) => {
|
|
159
|
+
if (signal.aborted) {
|
|
160
|
+
sentinel.reason = signal.reason;
|
|
161
|
+
reject(sentinel);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
onAbort = () => {
|
|
165
|
+
sentinel.reason = signal.reason;
|
|
166
|
+
reject(sentinel);
|
|
167
|
+
};
|
|
168
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
169
|
+
});
|
|
170
|
+
try {
|
|
171
|
+
return await Promise.race([work, abortPromise]);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
if (error === sentinel) throw runtimeAborted(phase, sentinel.reason);
|
|
174
|
+
throw error;
|
|
175
|
+
} finally {
|
|
176
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
//#endregion
|
|
180
|
+
//#region src/execution/run-with-middleware.ts
|
|
181
|
+
/**
|
|
182
|
+
* Drives a single execution of `runDriver()` through the middleware lifecycle.
|
|
183
|
+
*
|
|
184
|
+
* Lifecycle, in order:
|
|
185
|
+
* 1. For each middleware in registration order: `intercept(exec, ctx)`. The
|
|
186
|
+
* first non-`undefined` result wins; subsequent middleware's `intercept`
|
|
187
|
+
* does not fire. On a hit, the runtime emits a `middleware.intercept`
|
|
188
|
+
* debug event naming the winning middleware, switches the row source to
|
|
189
|
+
* the intercepted rows, and proceeds with `source: 'middleware'`. On
|
|
190
|
+
* all-passthrough (every `intercept` returns `undefined` or is omitted),
|
|
191
|
+
* `source: 'driver'` is used and the row source is `runDriver()`.
|
|
192
|
+
* 2. If `source === 'driver'`: for each middleware in registration order,
|
|
193
|
+
* `beforeExecute(exec, ctx)`. Skipped on the intercepted hit path —
|
|
194
|
+
* `beforeExecute` semantically means "about to hit the driver".
|
|
195
|
+
* 3. Iterate the row source. On the driver path, for each row, for each
|
|
196
|
+
* middleware in registration order: `onRow(row, exec, ctx)`; then yield
|
|
197
|
+
* the row. On the intercepted hit path, `onRow` is skipped — intercepted
|
|
198
|
+
* rows did not originate from a driver row stream — but rows are still
|
|
199
|
+
* yielded to the consumer in order.
|
|
200
|
+
* 4. On successful completion: for each middleware in registration order:
|
|
201
|
+
* `afterExecute(exec, { rowCount, latencyMs, completed: true, source },
|
|
202
|
+
* ctx)`.
|
|
203
|
+
* 5. On any error thrown during steps 1–3: for each middleware in
|
|
204
|
+
* registration order: `afterExecute(exec, { rowCount, latencyMs,
|
|
205
|
+
* completed: false, source }, ctx)`. Errors thrown by `afterExecute`
|
|
206
|
+
* during the error path are swallowed so they do not mask the original
|
|
207
|
+
* error. The original error is then rethrown.
|
|
208
|
+
*
|
|
209
|
+
* The `source` field on `AfterExecuteResult` lets observers (telemetry,
|
|
210
|
+
* lints, budgets) distinguish driver-served from middleware-served
|
|
211
|
+
* executions without needing their own out-of-band signal.
|
|
212
|
+
*
|
|
213
|
+
* This helper is the single canonical implementation of the middleware
|
|
214
|
+
* orchestration loop; family runtimes should not reimplement it.
|
|
215
|
+
*/
|
|
216
|
+
function runWithMiddleware(exec, middleware, ctx, runDriver, paramsMutator) {
|
|
217
|
+
const iterator = async function* () {
|
|
218
|
+
const startedAt = Date.now();
|
|
219
|
+
let rowCount = 0;
|
|
220
|
+
let completed = false;
|
|
221
|
+
let source = "driver";
|
|
222
|
+
let rowSource;
|
|
223
|
+
try {
|
|
224
|
+
for (const mw of middleware) {
|
|
225
|
+
if (!mw.intercept) continue;
|
|
226
|
+
source = "middleware";
|
|
227
|
+
const result = await mw.intercept(exec, ctx);
|
|
228
|
+
if (result === void 0) {
|
|
229
|
+
source = "driver";
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
ctx.log.debug?.({
|
|
233
|
+
event: "middleware.intercept",
|
|
234
|
+
middleware: mw.name
|
|
235
|
+
});
|
|
236
|
+
rowSource = result.rows;
|
|
237
|
+
break;
|
|
238
|
+
}
|
|
239
|
+
if (source === "driver") {
|
|
240
|
+
for (const mw of middleware) if (mw.beforeExecute) {
|
|
241
|
+
checkAborted(ctx, "beforeExecute");
|
|
242
|
+
const work = mw.beforeExecute(exec, ctx, paramsMutator);
|
|
243
|
+
if (work !== void 0) await raceAgainstAbort(Promise.resolve(work), ctx.signal, "beforeExecute");
|
|
244
|
+
}
|
|
245
|
+
rowSource = runDriver();
|
|
246
|
+
}
|
|
247
|
+
for await (const row of rowSource) {
|
|
248
|
+
if (source === "driver") {
|
|
249
|
+
for (const mw of middleware) if (mw.onRow) await mw.onRow(row, exec, ctx);
|
|
250
|
+
}
|
|
251
|
+
rowCount++;
|
|
252
|
+
yield row;
|
|
253
|
+
}
|
|
254
|
+
completed = true;
|
|
255
|
+
} catch (error) {
|
|
256
|
+
const latencyMs = Date.now() - startedAt;
|
|
257
|
+
for (const mw of middleware) if (mw.afterExecute) try {
|
|
258
|
+
await mw.afterExecute(exec, {
|
|
259
|
+
rowCount,
|
|
260
|
+
latencyMs,
|
|
261
|
+
completed,
|
|
262
|
+
source
|
|
263
|
+
}, ctx);
|
|
264
|
+
} catch {}
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
const latencyMs = Date.now() - startedAt;
|
|
268
|
+
for (const mw of middleware) if (mw.afterExecute) await mw.afterExecute(exec, {
|
|
269
|
+
rowCount,
|
|
270
|
+
latencyMs,
|
|
271
|
+
completed,
|
|
272
|
+
source
|
|
273
|
+
}, ctx);
|
|
274
|
+
};
|
|
275
|
+
return new AsyncIterableResult(iterator());
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/execution/runtime-core.ts
|
|
279
|
+
/**
|
|
280
|
+
* Family-agnostic abstract runtime base.
|
|
281
|
+
*
|
|
282
|
+
* Defines the entire `execute(plan)` template in one place:
|
|
283
|
+
*
|
|
284
|
+
* 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides
|
|
285
|
+
* this to run its `beforeCompile` middleware-hook chain.
|
|
286
|
+
* 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`
|
|
287
|
+
* (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).
|
|
288
|
+
* 3. `runWithMiddleware(exec, this.middleware, this.ctx,
|
|
289
|
+
* () => runDriver(exec))` — concrete; lifts the middleware lifecycle
|
|
290
|
+
* out of the family runtimes into the canonical helper.
|
|
291
|
+
*
|
|
292
|
+
* Concrete subclasses must implement `lower`, `runDriver`, and `close`.
|
|
293
|
+
*
|
|
294
|
+
* The class is generic over:
|
|
295
|
+
* - `TPlan` — the family's pre-lowering plan type.
|
|
296
|
+
* - `TExec` — the family's post-lowering (executable) plan type.
|
|
297
|
+
* - `TMiddleware` — the family's middleware type. Constrained to
|
|
298
|
+
* `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the
|
|
299
|
+
* `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered
|
|
300
|
+
* `TExec`. (The spec/plan wording "RuntimeMiddleware<TPlan>" is
|
|
301
|
+
* tightened to `<TExec>` here so the helper call typechecks; the
|
|
302
|
+
* intent is unchanged — middleware sees the post-lowering plan.)
|
|
303
|
+
*/
|
|
304
|
+
var RuntimeCore = class {
|
|
305
|
+
middleware;
|
|
306
|
+
ctx;
|
|
307
|
+
constructor(options) {
|
|
308
|
+
this.middleware = options.middleware;
|
|
309
|
+
this.ctx = options.ctx;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses
|
|
313
|
+
* may override to run a `beforeCompile` middleware chain (SQL does this
|
|
314
|
+
* to support typed AST rewrites — see `before-compile-chain.ts`).
|
|
315
|
+
*/
|
|
316
|
+
runBeforeCompile(plan) {
|
|
317
|
+
return plan;
|
|
318
|
+
}
|
|
319
|
+
execute(plan, options) {
|
|
320
|
+
const self = this;
|
|
321
|
+
const signal = options?.signal;
|
|
322
|
+
const codecCtx = signal === void 0 ? {} : { signal };
|
|
323
|
+
async function* generator() {
|
|
324
|
+
checkAborted(codecCtx, "stream");
|
|
325
|
+
const compiled = await self.runBeforeCompile(plan);
|
|
326
|
+
const exec = await self.lower(compiled, codecCtx);
|
|
327
|
+
yield* runWithMiddleware(exec, self.middleware, self.ctx, () => self.runDriver(exec));
|
|
328
|
+
}
|
|
329
|
+
return new AsyncIterableResult(generator());
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
//#endregion
|
|
333
|
+
//#region src/execution/runtime-middleware.ts
|
|
85
334
|
function checkMiddlewareCompatibility(middleware, runtimeFamilyId, runtimeTargetId) {
|
|
86
335
|
if (middleware.targetId !== void 0 && middleware.familyId === void 0) throw runtimeError("RUNTIME.MIDDLEWARE_INCOMPATIBLE", `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`, {
|
|
87
336
|
middleware: middleware.name,
|
|
@@ -98,7 +347,7 @@ function checkMiddlewareCompatibility(middleware, runtimeFamilyId, runtimeTarget
|
|
|
98
347
|
runtimeTargetId
|
|
99
348
|
});
|
|
100
349
|
}
|
|
101
|
-
|
|
102
350
|
//#endregion
|
|
103
|
-
export { AsyncIterableResult, checkMiddlewareCompatibility, isRuntimeError, runtimeError };
|
|
351
|
+
export { AsyncIterableResult, RUNTIME_ABORTED, RuntimeCore, checkAborted, checkMiddlewareCompatibility, isRuntimeError, raceAgainstAbort, runWithMiddleware, runtimeAborted, runtimeError };
|
|
352
|
+
|
|
104
353
|
//# sourceMappingURL=runtime.mjs.map
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","names":["out: Row[]"],"sources":["../src/runtime-error.ts","../src/async-iterable-result.ts","../src/runtime-middleware.ts"],"sourcesContent":["export interface RuntimeErrorEnvelope extends Error {\n readonly code: string;\n readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\n/**\n * Type guard for the runtime-error envelope produced by `runtimeError`.\n *\n * Prefer this over duck-typing on `error.code` directly so consumers stay\n * insulated from the envelope's internal shape.\n */\nexport function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {\n return (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string' &&\n 'category' in error &&\n 'severity' in error\n );\n}\n\nexport function runtimeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): RuntimeErrorEnvelope {\n const error = new Error(message) as RuntimeErrorEnvelope;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n\n return Object.assign(error, {\n code,\n category: resolveCategory(code),\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction resolveCategory(code: string): RuntimeErrorEnvelope['category'] {\n const prefix = code.split('.')[0] ?? 'RUNTIME';\n switch (prefix) {\n case 'PLAN':\n case 'CONTRACT':\n case 'LINT':\n case 'BUDGET':\n return prefix;\n default:\n return 'RUNTIME';\n }\n}\n","import { runtimeError } from './runtime-error';\n\nexport class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {\n private readonly generator: AsyncGenerator<Row, void, unknown>;\n private consumed = false;\n private consumedBy: 'bufferedArray' | 'iterator' | undefined;\n private bufferedArrayPromise: Promise<Row[]> | undefined;\n\n constructor(generator: AsyncGenerator<Row, void, unknown>) {\n this.generator = generator;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Row> {\n if (this.consumed) {\n throw runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === 'bufferedArray' ? 'toArray()/then()' : 'for-await loop'}. Each AsyncIterableResult can only be iterated once.`,\n {\n consumedBy: this.consumedBy,\n suggestion:\n this.consumedBy === 'bufferedArray'\n ? 'If you need to iterate multiple times, store the results from toArray() in a variable and reuse that.'\n : 'If you need to iterate multiple times, use toArray() to collect all results first.',\n },\n );\n }\n this.consumed = true;\n this.consumedBy = 'iterator';\n return this.generator;\n }\n\n toArray(): Promise<Row[]> {\n if (this.consumedBy === 'iterator') {\n return Promise.reject(\n runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n 'AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.',\n {\n consumedBy: this.consumedBy,\n suggestion:\n 'The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating.',\n },\n ),\n );\n }\n\n if (this.bufferedArrayPromise) {\n return this.bufferedArrayPromise;\n }\n\n this.consumed = true;\n this.consumedBy = 'bufferedArray';\n this.bufferedArrayPromise = (async () => {\n const out: Row[] = [];\n for await (const item of this.generator) {\n out.push(item);\n }\n return out;\n })();\n return this.bufferedArrayPromise;\n }\n\n async first(): Promise<Row | null> {\n const rows = await this.toArray();\n return rows[0] ?? null;\n }\n\n async firstOrThrow(): Promise<Row> {\n const row = await this.first();\n if (row === null)\n throw runtimeError(\n 'RUNTIME.NO_ROWS',\n 'Expected at least one row, but none were returned',\n {},\n );\n return row;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: PromiseLike implementation is intentional for await support.\n then<TResult1 = Row[], TResult2 = never>(\n onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.toArray().then(onfulfilled, onrejected);\n }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { AsyncIterableResult } from './async-iterable-result';\nimport { runtimeError } from './runtime-error';\n\nexport interface RuntimeLog {\n info(event: unknown): void;\n warn(event: unknown): void;\n error(event: unknown): void;\n debug?(event: unknown): void;\n}\n\nexport interface RuntimeMiddlewareContext {\n readonly contract: unknown;\n readonly mode: 'strict' | 'permissive';\n readonly now: () => number;\n readonly log: RuntimeLog;\n}\n\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\n}\n\nexport interface RuntimeMiddleware {\n readonly name: string;\n readonly familyId?: string;\n readonly targetId?: string;\n beforeExecute?(plan: { readonly meta: PlanMeta }, ctx: RuntimeMiddlewareContext): Promise<void>;\n onRow?(\n row: Record<string, unknown>,\n plan: { readonly meta: PlanMeta },\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n afterExecute?(\n plan: { readonly meta: PlanMeta },\n result: AfterExecuteResult,\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n}\n\n/**\n * Cross-family SPI for any runtime that can execute plans and be shut down.\n * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,\n * Mongo structurally (due to its phantom Row parameter using a unique symbol).\n *\n * The `_row` intersection on `execute` connects the `Row` type parameter to the\n * plan, mirroring how `ExecutionPlan<Row>` carries a phantom `_row?: Row`.\n */\nexport interface RuntimeExecutor<TPlan extends { readonly meta: PlanMeta }> {\n execute<Row>(plan: TPlan & { readonly _row?: Row }): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nexport function checkMiddlewareCompatibility(\n middleware: RuntimeMiddleware,\n runtimeFamilyId: string,\n runtimeTargetId: string,\n): void {\n if (middleware.targetId !== undefined && middleware.familyId === undefined) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',\n `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,\n { middleware: middleware.name, targetId: middleware.targetId },\n );\n }\n\n if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',\n `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,\n { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },\n );\n }\n\n if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',\n `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,\n { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },\n );\n }\n}\n"],"mappings":";;;;;;;AAaA,SAAgB,eAAe,OAA+C;AAC5E,QACE,iBAAiB,SACjB,UAAU,SACV,OAAQ,MAA6B,SAAS,YAC9C,cAAc,SACd,cAAc;;AAIlB,SAAgB,aACd,MACA,SACA,SACsB;CACtB,MAAM,QAAQ,IAAI,MAAM,QAAQ;AAChC,QAAO,eAAe,OAAO,QAAQ;EACnC,OAAO;EACP,cAAc;EACf,CAAC;AAEF,QAAO,OAAO,OAAO,OAAO;EAC1B;EACA,UAAU,gBAAgB,KAAK;EAC/B,UAAU;EACV;EACA;EACD,CAAC;;AAGJ,SAAS,gBAAgB,MAAgD;CACvE,MAAM,SAAS,KAAK,MAAM,IAAI,CAAC,MAAM;AACrC,SAAQ,QAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,SACH,QAAO;EACT,QACE,QAAO;;;;;;AClDb,IAAa,sBAAb,MAAwF;CACtF,AAAiB;CACjB,AAAQ,WAAW;CACnB,AAAQ;CACR,AAAQ;CAER,YAAY,WAA+C;AACzD,OAAK,YAAY;;CAGnB,CAAC,OAAO,iBAAqC;AAC3C,MAAI,KAAK,SACP,OAAM,aACJ,6BACA,8DAA8D,KAAK,eAAe,kBAAkB,qBAAqB,iBAAiB,wDAC1I;GACE,YAAY,KAAK;GACjB,YACE,KAAK,eAAe,kBAChB,0GACA;GACP,CACF;AAEH,OAAK,WAA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
|
+
{"version":3,"file":"runtime.mjs","names":[],"sources":["../src/execution/runtime-error.ts","../src/execution/async-iterable-result.ts","../src/execution/race-against-abort.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts","../src/execution/runtime-middleware.ts"],"sourcesContent":["export interface RuntimeErrorEnvelope extends Error {\n readonly code: string;\n readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\n/**\n * Stable code emitted by the runtime when an in-flight `execute()`\n * is cancelled via the per-query `AbortSignal`. The envelope's\n * `details.phase` distinguishes where the abort was observed:\n *\n * - `'encode'` — abort fired during `encodeParams` (SQL) or\n * `resolveValue` (Mongo).\n * - `'decode'` — abort fired during `decodeRow` / `decodeField`.\n * - `'stream'` — abort fired between rows or before any codec call\n * (already-aborted at entry).\n * - `'beforeExecute'` / `'afterExecute'` / `'onRow'` — abort fired\n * on entry to or during the corresponding middleware phase\n * (cooperative cancellation per the param-transform seam).\n */\nexport const RUNTIME_ABORTED = 'RUNTIME.ABORTED' as const;\n\n/** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */\nexport type RuntimeAbortedPhase =\n | 'encode'\n | 'decode'\n | 'stream'\n | 'beforeExecute'\n | 'afterExecute'\n | 'onRow';\n\n/**\n * Type guard for the runtime-error envelope produced by `runtimeError`.\n *\n * Prefer this over duck-typing on `error.code` directly so consumers stay\n * insulated from the envelope's internal shape.\n */\nexport function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {\n return (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string' &&\n 'category' in error &&\n 'severity' in error\n );\n}\n\nexport function runtimeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): RuntimeErrorEnvelope {\n const error = new Error(message) as RuntimeErrorEnvelope;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n\n return Object.assign(error, {\n code,\n category: resolveCategory(code),\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction resolveCategory(code: string): RuntimeErrorEnvelope['category'] {\n const prefix = code.split('.')[0] ?? 'RUNTIME';\n switch (prefix) {\n case 'PLAN':\n case 'CONTRACT':\n case 'LINT':\n case 'BUDGET':\n return prefix;\n default:\n return 'RUNTIME';\n }\n}\n\n/**\n * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the\n * abort was observed — codec call sites (`encode` / `decode` / `stream`)\n * or middleware seams (`beforeExecute` / `afterExecute` / `onRow`), as\n * enumerated on {@link RuntimeAbortedPhase}. Cause carries\n * `signal.reason` verbatim from the platform — native abort produces a\n * `DOMException`, explicit `controller.abort(reason)` produces whatever\n * the caller passed. No synthesis happens here.\n */\nexport function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope {\n const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });\n return Object.assign(envelope, { cause });\n}\n","import { runtimeError } from './runtime-error';\n\nexport class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {\n private readonly generator: AsyncGenerator<Row, void, unknown>;\n private consumed = false;\n private consumedBy: 'bufferedArray' | 'iterator' | undefined;\n private bufferedArrayPromise: Promise<Row[]> | undefined;\n\n constructor(generator: AsyncGenerator<Row, void, unknown>) {\n this.generator = generator;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Row> {\n if (this.consumed) {\n throw runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === 'bufferedArray' ? 'toArray()/then()' : 'for-await loop'}. Each AsyncIterableResult can only be iterated once.`,\n {\n consumedBy: this.consumedBy,\n suggestion:\n this.consumedBy === 'bufferedArray'\n ? 'If you need to iterate multiple times, store the results from toArray() in a variable and reuse that.'\n : 'If you need to iterate multiple times, use toArray() to collect all results first.',\n },\n );\n }\n this.consumed = true;\n this.consumedBy = 'iterator';\n return this.generator;\n }\n\n toArray(): Promise<Row[]> {\n if (this.consumedBy === 'iterator') {\n return Promise.reject(\n runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n 'AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.',\n {\n consumedBy: this.consumedBy,\n suggestion:\n 'The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating.',\n },\n ),\n );\n }\n\n if (this.bufferedArrayPromise) {\n return this.bufferedArrayPromise;\n }\n\n this.consumed = true;\n this.consumedBy = 'bufferedArray';\n this.bufferedArrayPromise = (async () => {\n const out: Row[] = [];\n for await (const item of this.generator) {\n out.push(item);\n }\n return out;\n })();\n return this.bufferedArrayPromise;\n }\n\n async first(): Promise<Row | null> {\n const rows = await this.toArray();\n return rows[0] ?? null;\n }\n\n async firstOrThrow(): Promise<Row> {\n const row = await this.first();\n if (row === null)\n throw runtimeError(\n 'RUNTIME.NO_ROWS',\n 'Expected at least one row, but none were returned',\n {},\n );\n return row;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: PromiseLike implementation is intentional for await support.\n then<TResult1 = Row[], TResult2 = never>(\n onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.toArray().then(onfulfilled, onrejected);\n }\n}\n","import type { RuntimeAbortedPhase } from './runtime-error';\nimport { runtimeAborted } from './runtime-error';\n\n/**\n * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied\n * context is already aborted at the precheck site. Centralises the\n * `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that\n * every codec dispatch site (and the `beforeExecute` middleware phase)\n * repeats. Accepts both the framework `CodecCallContext` and the\n * `RuntimeMiddlewareContext`; both expose `signal?: AbortSignal`.\n */\nexport function checkAborted(\n ctx: { readonly signal?: AbortSignal },\n phase: RuntimeAbortedPhase,\n): void {\n if (ctx.signal?.aborted) {\n throw runtimeAborted(phase, ctx.signal.reason);\n }\n}\n\n/**\n * Race a per-cell `Promise.all` (or any other in-flight work promise) against\n * the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly\n * even when codec bodies ignore the signal. In-flight bodies that ignore the\n * signal are abandoned and run to completion in the background — the\n * cooperative-cancellation contract documented in ADR 204.\n *\n * Call sites still SHOULD pre-check `signal.aborted` and short-circuit with\n * a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —\n * that path is the canonical \"aborted at entry\" surface and avoids\n * scheduling the work promise. As a defensive belt-and-braces, this helper\n * also handles the already-aborted case internally: `AbortSignal` does not\n * replay past abort events to listeners registered after the abort, so we\n * inspect `signal.aborted` synchronously and reject with the sentinel\n * before installing the listener. The rejection is still attributed to the\n * abort path via the sentinel-identity check.\n *\n * Distinguishing the rejection source is load-bearing for AC-ERR4\n * (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).\n * The semantically equivalent `abortable(signal)` helper in\n * `@prisma-next/utils` rejects with `signal.reason ?? new DOMException(...)`,\n * which is not stably distinguishable from a codec-thrown error by identity\n * alone (a fresh fallback DOMException is allocated per call). We instead\n * track abort attribution with a unique sentinel: only the `onAbort` listener\n * installed here ever rejects with the sentinel, so an `error === sentinel`\n * identity check after the race is unambiguous.\n *\n * Lives in `framework-components` (rather than the SQL family, where it\n * originated in m2) so every family runtime that needs cooperative\n * cancellation around a codec-dispatch `Promise.all` (SQL encode + decode\n * today, Mongo encode in m3) shares the same attribution logic.\n */\nexport async function raceAgainstAbort<T>(\n work: Promise<T>,\n signal: AbortSignal | undefined,\n phase: RuntimeAbortedPhase,\n): Promise<T> {\n if (signal === undefined) {\n return await work;\n }\n const sentinel: { reason: unknown } = { reason: undefined };\n let onAbort: (() => void) | undefined;\n\n const abortPromise = new Promise<never>((_, reject) => {\n if (signal.aborted) {\n sentinel.reason = signal.reason;\n reject(sentinel);\n return;\n }\n onAbort = () => {\n sentinel.reason = signal.reason;\n reject(sentinel);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n try {\n return await Promise.race([work, abortPromise]);\n } catch (error) {\n if (error === sentinel) {\n throw runtimeAborted(phase, sentinel.reason);\n }\n throw error;\n } finally {\n if (onAbort) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n}\n","import { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan } from './query-plan';\nimport { checkAborted, raceAgainstAbort } from './race-against-abort';\nimport type {\n ParamRefMutator,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Drives a single execution of `runDriver()` through the middleware lifecycle.\n *\n * Lifecycle, in order:\n * 1. For each middleware in registration order: `intercept(exec, ctx)`. The\n * first non-`undefined` result wins; subsequent middleware's `intercept`\n * does not fire. On a hit, the runtime emits a `middleware.intercept`\n * debug event naming the winning middleware, switches the row source to\n * the intercepted rows, and proceeds with `source: 'middleware'`. On\n * all-passthrough (every `intercept` returns `undefined` or is omitted),\n * `source: 'driver'` is used and the row source is `runDriver()`.\n * 2. If `source === 'driver'`: for each middleware in registration order,\n * `beforeExecute(exec, ctx)`. Skipped on the intercepted hit path —\n * `beforeExecute` semantically means \"about to hit the driver\".\n * 3. Iterate the row source. On the driver path, for each row, for each\n * middleware in registration order: `onRow(row, exec, ctx)`; then yield\n * the row. On the intercepted hit path, `onRow` is skipped — intercepted\n * rows did not originate from a driver row stream — but rows are still\n * yielded to the consumer in order.\n * 4. On successful completion: for each middleware in registration order:\n * `afterExecute(exec, { rowCount, latencyMs, completed: true, source },\n * ctx)`.\n * 5. On any error thrown during steps 1–3: for each middleware in\n * registration order: `afterExecute(exec, { rowCount, latencyMs,\n * completed: false, source }, ctx)`. Errors thrown by `afterExecute`\n * during the error path are swallowed so they do not mask the original\n * error. The original error is then rethrown.\n *\n * The `source` field on `AfterExecuteResult` lets observers (telemetry,\n * lints, budgets) distinguish driver-served from middleware-served\n * executions without needing their own out-of-band signal.\n *\n * This helper is the single canonical implementation of the middleware\n * orchestration loop; family runtimes should not reimplement it.\n */\nexport function runWithMiddleware<\n TExec extends ExecutionPlan,\n Row,\n TMutator extends ParamRefMutator = ParamRefMutator,\n>(\n exec: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec, TMutator>>,\n ctx: RuntimeMiddlewareContext,\n runDriver: () => AsyncIterable<Row>,\n paramsMutator?: TMutator,\n): AsyncIterableResult<Row> {\n const iterator = async function* (): AsyncGenerator<Row, void, unknown> {\n const startedAt = Date.now();\n let rowCount = 0;\n let completed = false;\n let source: 'driver' | 'middleware' = 'driver';\n // Deferred so a winning interceptor can skip `runDriver()` entirely.\n // For factories that lazily produce async generators this is a no-op,\n // but factories that do eager work (e.g. acquiring a connection,\n // sending a query) must not run on the intercepted hit path.\n let rowSource: AsyncIterable<Row> | Iterable<Row> | undefined;\n\n try {\n for (const mw of middleware) {\n if (!mw.intercept) {\n continue;\n }\n // Mark the lifecycle as middleware-driven *before* awaiting the\n // hook. If `intercept` throws, the catch block reports the failure\n // as `source: 'middleware'` — the failure originated in the\n // intercept chain, not in the driver. If `intercept` returns\n // `undefined` (passthrough), we revert to `'driver'` and continue.\n source = 'middleware';\n const result = await mw.intercept(exec, ctx);\n if (result === undefined) {\n source = 'driver';\n continue;\n }\n ctx.log.debug?.({ event: 'middleware.intercept', middleware: mw.name });\n // The intercepted rows are typed as `Record<string, unknown>` at\n // the SPI level; the consumer's `Row` type parameter is enforced by\n // the caller (via the plan's phantom `_row`) the same way driver\n // rows are. Cast through unknown to bridge the SPI shape to the\n // caller-supplied Row.\n rowSource = result.rows as unknown as AsyncIterable<Row> | Iterable<Row>;\n break;\n }\n\n if (source === 'driver') {\n for (const mw of middleware) {\n if (mw.beforeExecute) {\n checkAborted(ctx, 'beforeExecute');\n // The framework only forwards the mutator the caller supplied; a\n // pass-through `undefined` for non-mutating families is safe — the\n // base `RuntimeMiddleware` declares the third parameter, and\n // existing `(plan, ctx)` bodies that ignore it stay unchanged.\n // The cast below is the single point at which the framework's\n // generic mutator slot meets the (possibly absent) caller value;\n // `runWithMiddleware` cannot synthesize a TMutator instance.\n const work = mw.beforeExecute(exec, ctx, paramsMutator as TMutator);\n if (work !== undefined) {\n await raceAgainstAbort(Promise.resolve(work), ctx.signal, 'beforeExecute');\n }\n }\n }\n rowSource = runDriver();\n }\n\n // `rowSource` is always assigned by this point: either the intercepted\n // rows (on a hit) or `runDriver()` (on the driver path).\n for await (const row of rowSource as AsyncIterable<Row> | Iterable<Row>) {\n if (source === 'driver') {\n for (const mw of middleware) {\n if (mw.onRow) {\n await mw.onRow(row as Record<string, unknown>, exec, ctx);\n }\n }\n }\n rowCount++;\n yield row;\n }\n\n completed = true;\n } catch (error) {\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n try {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n } catch {\n // Swallow afterExecute errors during the error path so they do not\n // mask the original error.\n }\n }\n }\n\n throw error;\n }\n\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);\n }\n }\n };\n\n return new AsyncIterableResult(iterator());\n}\n","import type { CodecCallContext } from '../shared/codec-types';\nimport { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { checkAborted } from './race-against-abort';\nimport { runWithMiddleware } from './run-with-middleware';\nimport type {\n RuntimeExecuteOptions,\n RuntimeExecutor,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Constructor options shared by every concrete `RuntimeCore` subclass.\n *\n * Family runtimes typically build the middleware list and the\n * `RuntimeMiddlewareContext` themselves (running compatibility checks,\n * narrowing the context's `contract` field, etc.) before calling `super`.\n */\nexport interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {\n readonly middleware: ReadonlyArray<TMiddleware>;\n readonly ctx: RuntimeMiddlewareContext;\n}\n\n/**\n * Family-agnostic abstract runtime base.\n *\n * Defines the entire `execute(plan)` template in one place:\n *\n * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides\n * this to run its `beforeCompile` middleware-hook chain.\n * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`\n * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).\n * 3. `runWithMiddleware(exec, this.middleware, this.ctx,\n * () => runDriver(exec))` — concrete; lifts the middleware lifecycle\n * out of the family runtimes into the canonical helper.\n *\n * Concrete subclasses must implement `lower`, `runDriver`, and `close`.\n *\n * The class is generic over:\n * - `TPlan` — the family's pre-lowering plan type.\n * - `TExec` — the family's post-lowering (executable) plan type.\n * - `TMiddleware` — the family's middleware type. Constrained to\n * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the\n * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered\n * `TExec`. (The spec/plan wording \"RuntimeMiddleware<TPlan>\" is\n * tightened to `<TExec>` here so the helper call typechecks; the\n * intent is unchanged — middleware sees the post-lowering plan.)\n */\nexport abstract class RuntimeCore<\n TPlan extends QueryPlan,\n TExec extends ExecutionPlan,\n TMiddleware extends RuntimeMiddleware<TExec>,\n> implements RuntimeExecutor<TPlan>\n{\n protected readonly middleware: ReadonlyArray<TMiddleware>;\n protected readonly ctx: RuntimeMiddlewareContext;\n\n constructor(options: RuntimeCoreOptions<TMiddleware>) {\n this.middleware = options.middleware;\n this.ctx = options.ctx;\n }\n\n /**\n * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses\n * may override to run a `beforeCompile` middleware chain (SQL does this\n * to support typed AST rewrites — see `before-compile-chain.ts`).\n */\n protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan> {\n return plan;\n }\n\n /**\n * Lower a pre-lowering `TPlan` into the family's executable `TExec`.\n * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo\n * produces `{ command, ... }`.\n *\n * `ctx` carries per-query cancellation (and any future fields on\n * `CodecCallContext`); concrete subclasses forward it to the\n * encode-side codec dispatch site (e.g. SQL's `encodeParams` in m2,\n * Mongo's `resolveValue` in m3). The runtime allocates one ctx per\n * `execute()` call and threads the same reference everywhere; the\n * `signal` field inside may be `undefined`, but the ctx object itself\n * is always present.\n */\n protected abstract lower(plan: TPlan, ctx: CodecCallContext): TExec | Promise<TExec>;\n\n /**\n * Drive the underlying transport for a lowered `TExec`. Yields raw rows\n * directly from the driver as `Record<string, unknown>`; codec decoding\n * (if any) is the subclass's responsibility, applied by wrapping\n * `execute()` rather than living inside this hook.\n *\n * The `Row` type parameter on `execute()` is satisfied by the caller via\n * the plan's phantom `_row`; the runtime treats rows as opaque records\n * here and trusts the caller's row typing.\n */\n protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;\n\n abstract close(): Promise<void>;\n\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call. The ctx object is always allocated; the\n // `signal` field is only included when a signal was supplied (required\n // under exactOptionalPropertyTypes — `{ signal: undefined }` would not\n // satisfy `signal?: AbortSignal`).\n const codecCtx: CodecCallContext = signal === undefined ? {} : { signal };\n\n async function* generator(): AsyncGenerator<Row, void, unknown> {\n // Pre-check the signal at entry so an already-aborted caller observes\n // RUNTIME.ABORTED on the first `next()` without any work being done.\n checkAborted(codecCtx, 'stream');\n\n const compiled = await self.runBeforeCompile(plan);\n const exec = await self.lower(compiled, codecCtx);\n // The driver yields raw `Record<string, unknown>`; we cast to `Row` here.\n // The Row contract is enforced by the caller via `plan._row`.\n yield* runWithMiddleware<TExec, Row>(\n exec,\n self.middleware,\n self.ctx,\n () => self.runDriver(exec) as AsyncIterable<Row>,\n );\n }\n\n return new AsyncIterableResult(generator());\n }\n}\n","import type { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { runtimeError } from './runtime-error';\n\nexport interface RuntimeLog {\n info(event: unknown): void;\n warn(event: unknown): void;\n error(event: unknown): void;\n debug?(event: unknown): void;\n}\n\n/**\n * Per-execute context threaded through every middleware phase\n * (`beforeExecute`, `onRow`, `afterExecute`). Allocated once per\n * `runtime.execute()` call and shared by reference across all\n * middleware in the chain.\n *\n * - `signal` carries the per-query `AbortSignal` -- the same\n * reference that `runtime.execute(plan, { signal })` was invoked\n * with, and the same reference threaded into the per-call\n * `CodecCallContext` (ADR 207). Middleware that wraps a\n * network-backed SDK forwards `ctx.signal` into that SDK to\n * propagate caller cancellation; pure-CPU middleware ignores it.\n *\n * Symmetric plumbing across all middleware phases (rather than only\n * `beforeExecute`) is a deliberate choice: a middleware that wraps a\n * downstream observability hook or post-processor in `afterExecute` /\n * `onRow` needs the same cancellation reach as its `beforeExecute`\n * counterpart.\n */\nexport interface RuntimeMiddlewareContext {\n readonly contract: unknown;\n readonly mode: 'strict' | 'permissive';\n readonly now: () => number;\n readonly log: RuntimeLog;\n /**\n * Returns a stable string identifying the (storage, statement, params)\n * tuple of an execution. Two semantically equivalent executions return\n * the same string. Used by middleware that need per-execution identity\n * (caching, request coalescing).\n *\n * The family runtime owns the implementation:\n * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`\n * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`\n *\n * The method is `async` because the underlying digest helper\n * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`\n * primitive is asynchronous by design.\n *\n * The returned string is intended to be consumed directly as a `Map` key\n * — it is not (and should not be) further hashed by callers.\n */\n contentHash(exec: ExecutionPlan): Promise<string>;\n /**\n * Per-execute cancellation signal threaded through every middleware\n * phase. Middleware that wraps async work or downstream cancellable\n * primitives should observe this and abort early when the consumer\n * cancels.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\n /**\n * Indicates where the rows observed during this execution came from.\n *\n * - `'driver'` — the default. Rows came from the underlying driver via\n * `runDriver` / `runWithMiddleware`'s normal path.\n * - `'middleware'` — a `RuntimeMiddleware.intercept` hook short-circuited\n * execution and supplied the rows directly. The driver was not invoked.\n *\n * Observers (telemetry, lints, budgets) that need to distinguish between\n * driver-served and middleware-served executions read this field.\n * Observers that don't care can ignore it.\n */\n readonly source: 'driver' | 'middleware';\n}\n\n/**\n * Result of a successful `RuntimeMiddleware.intercept` hook.\n *\n * Carries the rows that the middleware wishes to return in place of\n * invoking the driver. The runtime iterates `rows` in order and yields\n * each row to the consumer; `beforeExecute`, `runDriver`, and `onRow` are\n * all skipped on the hit path. `afterExecute` still fires with\n * `source: 'middleware'`.\n *\n * `rows` accepts both `Iterable` (arrays, sync generators) and\n * `AsyncIterable` (async generators). `for await` natively handles both\n * via `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the\n * orchestrator does not need to branch on the variant. Cached arrays in\n * the cache middleware are the common case; streaming variants support\n * future use cases like mock layers replaying recordings.\n *\n * Row shape is `Record<string, unknown>` — the same untyped shape\n * `onRow` receives. The SQL runtime decodes intercepted rows through its\n * normal codec pass, so interceptors cache and return raw (undecoded)\n * rows.\n */\nexport interface InterceptResult {\n readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;\n}\n\n/**\n * Marker interface for family-specific param-ref mutators threaded into\n * `beforeExecute` as the third argument. The framework treats the mutator\n * opaquely — it allocates and forwards the family's mutator instance so\n * `runWithMiddleware` can stay family-agnostic. SQL extends this with\n * `SqlParamRefMutator` (over `ParamRef`); Mongo extends with\n * `MongoParamRefMutator` (over `MongoParamRef`).\n *\n * Extension authors target the family-specific mutator type, not this\n * marker.\n */\ndeclare const PARAM_REF_MUTATOR_BRAND: unique symbol;\nexport type ParamRefMutator = { readonly [PARAM_REF_MUTATOR_BRAND]?: never };\n\n/**\n * Family-agnostic middleware SPI parameterized over the plan marker.\n *\n * `TPlan` defaults to the framework `QueryPlan` marker so a generic\n * middleware (e.g. cross-family telemetry) can be authored without\n * naming a family. Family-specific middleware (`SqlMiddleware`,\n * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.\n *\n * `TMutator` is the family-specific {@link ParamRefMutator} the runtime\n * threads into `beforeExecute(plan, ctx, params)` as a third argument.\n * Existing `(plan)` / `(plan, ctx)` middleware bodies continue to compile\n * — TypeScript permits assigning a function with fewer parameters to a\n * function-typed slot that declares more. The third arg is additive.\n */\nexport interface RuntimeMiddleware<\n TPlan extends QueryPlan = QueryPlan,\n TMutator extends ParamRefMutator = ParamRefMutator,\n> {\n readonly name: string;\n readonly familyId?: string;\n readonly targetId?: string;\n /**\n * Optional short-circuit hook. Runs inside `runWithMiddleware`, after\n * the orchestrator receives the lowered plan and before any\n * `beforeExecute` hook fires. Middleware run in registration order; the\n * first to return a non-`undefined` `InterceptResult` wins, and\n * subsequent middleware's `intercept` does not fire.\n *\n * On a hit, `beforeExecute`, `runDriver`, and `onRow` are all skipped.\n * `afterExecute` still fires with `source: 'middleware'`.\n *\n * Returning `undefined` (or omitting the hook entirely) signals\n * passthrough — execution proceeds through the normal driver path.\n *\n * Errors thrown inside `intercept` are rethrown by `runWithMiddleware`\n * as the original `Error` — no envelope is guaranteed at this layer.\n * Before rethrowing, `afterExecute` fires with `completed: false` and\n * `source: 'middleware'`. Errors thrown by `afterExecute` during the\n * error path remain swallowed (existing semantics, unchanged).\n *\n * Used by middleware that need to short-circuit execution and supply\n * rows directly: caching, mocks, rate limiting, circuit breaking.\n */\n intercept?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<InterceptResult | undefined>;\n beforeExecute?(\n plan: TPlan,\n ctx: RuntimeMiddlewareContext,\n params?: TMutator,\n ): void | Promise<void>;\n onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;\n afterExecute?(\n plan: TPlan,\n result: AfterExecuteResult,\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n}\n\n/**\n * Optional per-`execute` options accepted by every family runtime.\n *\n * `signal` is the per-query cancellation signal. The runtime threads the\n * signal through to every codec call for the query and uses it to short-\n * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.\n * Omitting the option (or passing `undefined`) preserves today's behavior\n * bit-for-bit.\n */\nexport interface RuntimeExecuteOptions {\n readonly signal?: AbortSignal;\n}\n\n/**\n * Cross-family SPI for any runtime that can execute plans and be shut down.\n * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,\n * Mongo structurally (due to its phantom Row parameter using a unique symbol).\n *\n * The `_row` intersection on `execute` connects the `Row` type parameter to the\n * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.\n */\nexport interface RuntimeExecutor<TPlan extends QueryPlan> {\n execute<Row>(\n plan: TPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nexport function checkMiddlewareCompatibility(\n middleware: RuntimeMiddleware,\n runtimeFamilyId: string,\n runtimeTargetId: string,\n): void {\n if (middleware.targetId !== undefined && middleware.familyId === undefined) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',\n `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,\n { middleware: middleware.name, targetId: middleware.targetId },\n );\n }\n\n if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',\n `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,\n { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },\n );\n }\n\n if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',\n `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,\n { middleware: middleware.name, middlewareTargetId: middleware.targetId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region src/types-import-spec.d.ts
|
|
1
|
+
//#region src/shared/types-import-spec.d.ts
|
|
2
2
|
/**
|
|
3
3
|
* Specifies how to import TypeScript types from a package.
|
|
4
4
|
* Used in extension pack manifests to declare codec and operation type imports.
|
|
@@ -10,4 +10,4 @@ interface TypesImportSpec {
|
|
|
10
10
|
}
|
|
11
11
|
//#endregion
|
|
12
12
|
export { TypesImportSpec as t };
|
|
13
|
-
//# sourceMappingURL=types-import-spec-
|
|
13
|
+
//# sourceMappingURL=types-import-spec-BxI5cSQy.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-import-spec-BxI5cSQy.d.mts","names":[],"sources":["../src/shared/types-import-spec.ts"],"mappings":";;AAIA;;;UAAiB,eAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA;EAAA,SACA,KAAA;AAAA"}
|
package/package.json
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/framework-components",
|
|
3
|
-
"version": "0.5.0-dev.
|
|
3
|
+
"version": "0.5.0-dev.80",
|
|
4
|
+
"license": "Apache-2.0",
|
|
4
5
|
"type": "module",
|
|
5
6
|
"sideEffects": false,
|
|
6
7
|
"description": "Framework component types, assembly logic, and stack creation for Prisma Next",
|
|
7
8
|
"dependencies": {
|
|
8
|
-
"@
|
|
9
|
-
"@prisma-next/
|
|
10
|
-
"@prisma-next/
|
|
9
|
+
"@standard-schema/spec": "^1.1.0",
|
|
10
|
+
"@prisma-next/contract": "0.5.0-dev.80",
|
|
11
|
+
"@prisma-next/ts-render": "0.5.0-dev.80",
|
|
12
|
+
"@prisma-next/utils": "0.5.0-dev.80",
|
|
13
|
+
"@prisma-next/operations": "0.5.0-dev.80"
|
|
11
14
|
},
|
|
12
15
|
"devDependencies": {
|
|
13
|
-
"tsdown": "0.
|
|
16
|
+
"tsdown": "0.22.0",
|
|
14
17
|
"typescript": "5.9.3",
|
|
15
|
-
"vitest": "4.
|
|
18
|
+
"vitest": "4.1.5",
|
|
16
19
|
"@prisma-next/tsconfig": "0.0.0",
|
|
17
20
|
"@prisma-next/tsdown": "0.0.0"
|
|
18
21
|
},
|
|
@@ -27,6 +30,7 @@
|
|
|
27
30
|
"./control": "./dist/control.mjs",
|
|
28
31
|
"./emission": "./dist/emission.mjs",
|
|
29
32
|
"./execution": "./dist/execution.mjs",
|
|
33
|
+
"./psl-ast": "./dist/psl-ast.mjs",
|
|
30
34
|
"./runtime": "./dist/runtime.mjs",
|
|
31
35
|
"./package.json": "./package.json"
|
|
32
36
|
},
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { ControlTargetDescriptor } from './control-descriptors';
|
|
2
|
+
import type { ControlFamilyInstance } from './control-instances';
|
|
3
|
+
import type {
|
|
4
|
+
MigrationPlanOperation,
|
|
5
|
+
MigrationRunner,
|
|
6
|
+
MultiSpaceCapableRunner,
|
|
7
|
+
TargetMigrationsCapability,
|
|
8
|
+
} from './control-migration-types';
|
|
9
|
+
import type { OperationPreview } from './control-operation-preview';
|
|
10
|
+
import type { CoreSchemaView } from './control-schema-view';
|
|
11
|
+
import type { PslDocumentAst } from './psl-ast';
|
|
12
|
+
|
|
13
|
+
export interface MigratableTargetDescriptor<
|
|
14
|
+
TFamilyId extends string,
|
|
15
|
+
TTargetId extends string,
|
|
16
|
+
TFamilyInstance extends ControlFamilyInstance<TFamilyId, unknown> = ControlFamilyInstance<
|
|
17
|
+
TFamilyId,
|
|
18
|
+
unknown
|
|
19
|
+
>,
|
|
20
|
+
> extends ControlTargetDescriptor<TFamilyId, TTargetId> {
|
|
21
|
+
readonly migrations: TargetMigrationsCapability<TFamilyId, TTargetId, TFamilyInstance>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function hasMigrations<TFamilyId extends string, TTargetId extends string>(
|
|
25
|
+
target: ControlTargetDescriptor<TFamilyId, TTargetId>,
|
|
26
|
+
): target is MigratableTargetDescriptor<TFamilyId, TTargetId> {
|
|
27
|
+
return 'migrations' in target && !!(target as Record<string, unknown>)['migrations'];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SchemaViewCapable<TSchemaIR = unknown> {
|
|
31
|
+
toSchemaView(schema: TSchemaIR): CoreSchemaView;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function hasSchemaView<TFamilyId extends string, TSchemaIR>(
|
|
35
|
+
instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,
|
|
36
|
+
): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & SchemaViewCapable<TSchemaIR> {
|
|
37
|
+
return (
|
|
38
|
+
'toSchemaView' in instance &&
|
|
39
|
+
typeof (instance as Record<string, unknown>)['toSchemaView'] === 'function'
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Capability declaring that a family can infer a PSL contract AST from its
|
|
45
|
+
* opaque introspected schema IR. Consumed by `prisma-next contract infer`.
|
|
46
|
+
*/
|
|
47
|
+
export interface PslContractInferCapable<TSchemaIR = unknown> {
|
|
48
|
+
inferPslContract(schemaIR: TSchemaIR): PslDocumentAst;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function hasPslContractInfer<TFamilyId extends string, TSchemaIR>(
|
|
52
|
+
instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,
|
|
53
|
+
): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & PslContractInferCapable<TSchemaIR> {
|
|
54
|
+
return (
|
|
55
|
+
'inferPslContract' in instance &&
|
|
56
|
+
typeof (instance as Record<string, unknown>)['inferPslContract'] === 'function'
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Capability declaring that a family can render a textual preview of migration
|
|
62
|
+
* operations for the CLI's "DDL preview" output. SQL families emit
|
|
63
|
+
* `language: 'sql'` statements; Mongo families emit `language: 'mongodb-shell'`.
|
|
64
|
+
*/
|
|
65
|
+
export interface OperationPreviewCapable {
|
|
66
|
+
toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function hasOperationPreview<TFamilyId extends string, TSchemaIR>(
|
|
70
|
+
instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,
|
|
71
|
+
): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & OperationPreviewCapable {
|
|
72
|
+
return (
|
|
73
|
+
'toOperationPreview' in instance &&
|
|
74
|
+
typeof (instance as Record<string, unknown>)['toOperationPreview'] === 'function'
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Capability declaring that a runner can apply per-space plans inside a
|
|
80
|
+
* single outer transaction. The SQL family (`SqlMigrationRunner`) implements
|
|
81
|
+
* this with a true outer transaction. The Mongo family implements a
|
|
82
|
+
* degenerate single-space shim (Mongo per-space is a non-goal per the
|
|
83
|
+
* extension-contract-spaces project spec — TML-2397).
|
|
84
|
+
*
|
|
85
|
+
* The CLI's shared `applyAggregate` primitive uses this guard so that
|
|
86
|
+
* `db init` / `db update` / `migration apply` route uniformly through one
|
|
87
|
+
* dispatch path regardless of family.
|
|
88
|
+
*/
|
|
89
|
+
export function hasMultiSpaceRunner<TFamilyId extends string, TTargetId extends string>(
|
|
90
|
+
runner: MigrationRunner<TFamilyId, TTargetId>,
|
|
91
|
+
): runner is MigrationRunner<TFamilyId, TTargetId> & MultiSpaceCapableRunner<TFamilyId, TTargetId> {
|
|
92
|
+
return (
|
|
93
|
+
'executeAcrossSpaces' in runner &&
|
|
94
|
+
typeof (runner as Record<string, unknown>)['executeAcrossSpaces'] === 'function'
|
|
95
|
+
);
|
|
96
|
+
}
|
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AdapterDescriptor,
|
|
3
|
+
DriverDescriptor,
|
|
4
|
+
ExtensionDescriptor,
|
|
5
|
+
FamilyDescriptor,
|
|
6
|
+
TargetDescriptor,
|
|
7
|
+
} from '../shared/framework-components';
|
|
1
8
|
import type {
|
|
2
9
|
ControlAdapterInstance,
|
|
3
10
|
ControlDriverInstance,
|
|
@@ -7,13 +14,6 @@ import type {
|
|
|
7
14
|
} from './control-instances';
|
|
8
15
|
import type { ControlStack } from './control-stack';
|
|
9
16
|
import type { EmissionSpi } from './emission-types';
|
|
10
|
-
import type {
|
|
11
|
-
AdapterDescriptor,
|
|
12
|
-
DriverDescriptor,
|
|
13
|
-
ExtensionDescriptor,
|
|
14
|
-
FamilyDescriptor,
|
|
15
|
-
TargetDescriptor,
|
|
16
|
-
} from './framework-components';
|
|
17
17
|
|
|
18
18
|
export interface ControlFamilyDescriptor<
|
|
19
19
|
TFamilyId extends string,
|
|
@@ -1,9 +1,4 @@
|
|
|
1
1
|
import type { Contract, ContractMarkerRecord } from '@prisma-next/contract/types';
|
|
2
|
-
import type {
|
|
3
|
-
SignDatabaseResult,
|
|
4
|
-
VerifyDatabaseResult,
|
|
5
|
-
VerifyDatabaseSchemaResult,
|
|
6
|
-
} from './control-result-types';
|
|
7
2
|
import type {
|
|
8
3
|
AdapterInstance,
|
|
9
4
|
DriverInstance,
|
|
@@ -11,7 +6,12 @@ import type {
|
|
|
11
6
|
FamilyInstance,
|
|
12
7
|
TargetBoundComponentDescriptor,
|
|
13
8
|
TargetInstance,
|
|
14
|
-
} from '
|
|
9
|
+
} from '../shared/framework-components';
|
|
10
|
+
import type {
|
|
11
|
+
SignDatabaseResult,
|
|
12
|
+
VerifyDatabaseResult,
|
|
13
|
+
VerifyDatabaseSchemaResult,
|
|
14
|
+
} from './control-result-types';
|
|
15
15
|
|
|
16
16
|
export interface ControlFamilyInstance<TFamilyId extends string, TSchemaIR>
|
|
17
17
|
extends FamilyInstance<TFamilyId> {
|
|
@@ -34,6 +34,24 @@ export interface ControlFamilyInstance<TFamilyId extends string, TSchemaIR>
|
|
|
34
34
|
readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, string>>;
|
|
35
35
|
}): Promise<VerifyDatabaseSchemaResult>;
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Verify a contract against an already-introspected schema slice.
|
|
39
|
+
*
|
|
40
|
+
* Difference from {@link schemaVerify}: no `driver`, no introspection
|
|
41
|
+
* — the caller hands over the schema directly. Used by the aggregate
|
|
42
|
+
* verifier to invoke the family's verification logic per member,
|
|
43
|
+
* with the schema **pre-projected** to that member's claimed slice
|
|
44
|
+
* via {@link import('@prisma-next/migration-tools/aggregate').projectSchemaToSpace}.
|
|
45
|
+
*
|
|
46
|
+
* Synchronous — no I/O. Idempotent.
|
|
47
|
+
*/
|
|
48
|
+
schemaVerifyAgainstSchema(options: {
|
|
49
|
+
readonly contract: unknown;
|
|
50
|
+
readonly schema: TSchemaIR;
|
|
51
|
+
readonly strict: boolean;
|
|
52
|
+
readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, string>>;
|
|
53
|
+
}): VerifyDatabaseSchemaResult;
|
|
54
|
+
|
|
37
55
|
sign(options: {
|
|
38
56
|
readonly driver: ControlDriverInstance<TFamilyId, string>;
|
|
39
57
|
readonly contract: unknown;
|
|
@@ -41,10 +59,38 @@ export interface ControlFamilyInstance<TFamilyId extends string, TSchemaIR>
|
|
|
41
59
|
readonly configPath?: string;
|
|
42
60
|
}): Promise<SignDatabaseResult>;
|
|
43
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Reads the contract marker for `space` from the database, returning
|
|
64
|
+
* `null` if no marker row exists for that space (or if the marker
|
|
65
|
+
* table itself is missing).
|
|
66
|
+
*
|
|
67
|
+
* `space` is required at every call site so the type system surfaces
|
|
68
|
+
* every place that needs to thread the value: callers in single-app
|
|
69
|
+
* paths pass {@link import('./control-spaces').APP_SPACE_ID}
|
|
70
|
+
* (`'app'`); per-extension callers pass the extension's space id.
|
|
71
|
+
* Defaulting at the family-interface level was a silent bug door —
|
|
72
|
+
* it let multi-space-aware callers forget to pass `space` and
|
|
73
|
+
* collapse onto the app's marker row.
|
|
74
|
+
*
|
|
75
|
+
* Families whose underlying storage doesn't yet support per-space
|
|
76
|
+
* markers (Mongo, today) accept `space` for interface conformance and
|
|
77
|
+
* reject any non-`APP_SPACE_ID` value rather than silently ignoring
|
|
78
|
+
* it; see the family-specific implementation for details.
|
|
79
|
+
*/
|
|
44
80
|
readMarker(options: {
|
|
45
81
|
readonly driver: ControlDriverInstance<TFamilyId, string>;
|
|
82
|
+
readonly space: string;
|
|
46
83
|
}): Promise<ContractMarkerRecord | null>;
|
|
47
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Reads every marker row keyed by `space`. Used by the per-space
|
|
87
|
+
* verifier to detect orphan marker rows and marker-vs-on-disk drift.
|
|
88
|
+
* Returns an empty map when the marker table does not yet exist.
|
|
89
|
+
*/
|
|
90
|
+
readAllMarkers(options: {
|
|
91
|
+
readonly driver: ControlDriverInstance<TFamilyId, string>;
|
|
92
|
+
}): Promise<ReadonlyMap<string, ContractMarkerRecord>>;
|
|
93
|
+
|
|
48
94
|
introspect(options: {
|
|
49
95
|
readonly driver: ControlDriverInstance<TFamilyId, string>;
|
|
50
96
|
readonly contract?: unknown;
|