@prisma-next/framework-components 0.5.0-dev.7 → 0.5.0-dev.70
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 +63 -3
- 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 +370 -72
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +82 -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-BwWNqTlD.mjs +205 -0
- package/dist/framework-authoring-BwWNqTlD.mjs.map +1 -0
- package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-Cm5f9U64.d.mts} +41 -12
- package/dist/framework-authoring-Cm5f9U64.d.mts.map +1 -0
- package/dist/{framework-components-EJXe-pum.d.mts → framework-components-DgIEy9eJ.d.mts} +45 -55
- package/dist/framework-components-DgIEy9eJ.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 +346 -19
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +254 -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 +11 -8
- package/src/control/control-capabilities.ts +95 -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} +202 -61
- 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 +85 -0
- package/src/execution/run-with-middleware.ts +132 -0
- package/src/execution/runtime-core.ts +133 -0
- package/src/execution/runtime-error.ts +83 -0
- package/src/execution/runtime-middleware.ts +182 -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 +40 -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 +17 -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} +202 -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-B58nCJiu.d.mts +0 -40
- package/dist/codec-types-B58nCJiu.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-EJXe-pum.d.mts.map +0 -1
- package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
- package/src/codec-types.ts +0 -46
- package/src/control-capabilities.ts +0 -34
- package/src/emission-types.ts +0 -28
- package/src/runtime-error.ts +0 -39
- 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.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/async-iterable-result.ts","../src/runtime-error.ts","../src/runtime-middleware.ts"
|
|
1
|
+
{"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/execution/async-iterable-result.ts","../src/execution/query-plan.ts","../src/execution/runtime-error.ts","../src/execution/race-against-abort.ts","../src/execution/runtime-middleware.ts","../src/execution/run-with-middleware.ts","../src/execution/runtime-core.ts"],"mappings":";;;;cAEa,mBAAA,iBAAoC,aAAA,CAAc,GAAA,GAAM,WAAA,CAAY,GAAA;EAAA,iBAC9D,SAAA;EAAA,QACT,QAAA;EAAA,QACA,UAAA;EAAA,QACA,oBAAA;cAEI,SAAA,EAAW,cAAA,CAAe,GAAA;EAAA,CAIrC,MAAA,CAAO,aAAA,KAAkB,aAAA,CAAc,GAAA;EAmBxC,OAAA,CAAA,GAAW,OAAA,CAAQ,GAAA;EA+Bb,KAAA,CAAA,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+1,25 @@
|
|
|
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
|
+
*/
|
|
13
|
+
const RUNTIME_ABORTED = "RUNTIME.ABORTED";
|
|
14
|
+
/**
|
|
15
|
+
* Type guard for the runtime-error envelope produced by `runtimeError`.
|
|
16
|
+
*
|
|
17
|
+
* Prefer this over duck-typing on `error.code` directly so consumers stay
|
|
18
|
+
* insulated from the envelope's internal shape.
|
|
19
|
+
*/
|
|
20
|
+
function isRuntimeError(error) {
|
|
21
|
+
return error instanceof Error && "code" in error && typeof error.code === "string" && "category" in error && "severity" in error;
|
|
22
|
+
}
|
|
2
23
|
function runtimeError(code, message, details) {
|
|
3
24
|
const error = new Error(message);
|
|
4
25
|
Object.defineProperty(error, "name", {
|
|
@@ -23,9 +44,19 @@ function resolveCategory(code) {
|
|
|
23
44
|
default: return "RUNTIME";
|
|
24
45
|
}
|
|
25
46
|
}
|
|
26
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the
|
|
49
|
+
* abort was observed (encode / decode / stream); cause carries `signal.reason`
|
|
50
|
+
* verbatim from the platform — native abort produces a `DOMException`,
|
|
51
|
+
* explicit `controller.abort(reason)` produces whatever the caller passed.
|
|
52
|
+
* No synthesis happens here.
|
|
53
|
+
*/
|
|
54
|
+
function runtimeAborted(phase, cause) {
|
|
55
|
+
const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });
|
|
56
|
+
return Object.assign(envelope, { cause });
|
|
57
|
+
}
|
|
27
58
|
//#endregion
|
|
28
|
-
//#region src/async-iterable-result.ts
|
|
59
|
+
//#region src/execution/async-iterable-result.ts
|
|
29
60
|
var AsyncIterableResult = class {
|
|
30
61
|
generator;
|
|
31
62
|
consumed = false;
|
|
@@ -70,9 +101,225 @@ var AsyncIterableResult = class {
|
|
|
70
101
|
return this.toArray().then(onfulfilled, onrejected);
|
|
71
102
|
}
|
|
72
103
|
};
|
|
73
|
-
|
|
74
104
|
//#endregion
|
|
75
|
-
//#region src/
|
|
105
|
+
//#region src/execution/race-against-abort.ts
|
|
106
|
+
/**
|
|
107
|
+
* Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied
|
|
108
|
+
* codec-call context is already aborted at the precheck site. Centralises
|
|
109
|
+
* the `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that
|
|
110
|
+
* every codec dispatch site repeats.
|
|
111
|
+
*/
|
|
112
|
+
function checkAborted(ctx, phase) {
|
|
113
|
+
if (ctx.signal?.aborted) throw runtimeAborted(phase, ctx.signal.reason);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Race a per-cell `Promise.all` (or any other in-flight work promise) against
|
|
117
|
+
* the supplied abort signal so the runtime returns `RUNTIME.ABORTED` promptly
|
|
118
|
+
* even when codec bodies ignore the signal. In-flight bodies that ignore the
|
|
119
|
+
* signal are abandoned and run to completion in the background — the
|
|
120
|
+
* cooperative-cancellation contract documented in ADR 204.
|
|
121
|
+
*
|
|
122
|
+
* Call sites still SHOULD pre-check `signal.aborted` and short-circuit with
|
|
123
|
+
* a phase-tagged `RUNTIME.ABORTED` envelope before invoking this helper —
|
|
124
|
+
* that path is the canonical "aborted at entry" surface and avoids
|
|
125
|
+
* scheduling the work promise. As a defensive belt-and-braces, this helper
|
|
126
|
+
* also handles the already-aborted case internally: `AbortSignal` does not
|
|
127
|
+
* replay past abort events to listeners registered after the abort, so we
|
|
128
|
+
* inspect `signal.aborted` synchronously and reject with the sentinel
|
|
129
|
+
* before installing the listener. The rejection is still attributed to the
|
|
130
|
+
* abort path via the sentinel-identity check.
|
|
131
|
+
*
|
|
132
|
+
* Distinguishing the rejection source is load-bearing for AC-ERR4
|
|
133
|
+
* (`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` pass through unchanged).
|
|
134
|
+
* The semantically equivalent `abortable(signal)` helper in
|
|
135
|
+
* `@prisma-next/utils` rejects with `signal.reason ?? new DOMException(...)`,
|
|
136
|
+
* which is not stably distinguishable from a codec-thrown error by identity
|
|
137
|
+
* alone (a fresh fallback DOMException is allocated per call). We instead
|
|
138
|
+
* track abort attribution with a unique sentinel: only the `onAbort` listener
|
|
139
|
+
* installed here ever rejects with the sentinel, so an `error === sentinel`
|
|
140
|
+
* identity check after the race is unambiguous.
|
|
141
|
+
*
|
|
142
|
+
* Lives in `framework-components` (rather than the SQL family, where it
|
|
143
|
+
* originated in m2) so every family runtime that needs cooperative
|
|
144
|
+
* cancellation around a codec-dispatch `Promise.all` (SQL encode + decode
|
|
145
|
+
* today, Mongo encode in m3) shares the same attribution logic.
|
|
146
|
+
*/
|
|
147
|
+
async function raceAgainstAbort(work, signal, phase) {
|
|
148
|
+
if (signal === void 0) return await work;
|
|
149
|
+
const sentinel = { reason: void 0 };
|
|
150
|
+
let onAbort;
|
|
151
|
+
const abortPromise = new Promise((_, reject) => {
|
|
152
|
+
if (signal.aborted) {
|
|
153
|
+
sentinel.reason = signal.reason;
|
|
154
|
+
reject(sentinel);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
onAbort = () => {
|
|
158
|
+
sentinel.reason = signal.reason;
|
|
159
|
+
reject(sentinel);
|
|
160
|
+
};
|
|
161
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
162
|
+
});
|
|
163
|
+
try {
|
|
164
|
+
return await Promise.race([work, abortPromise]);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error === sentinel) throw runtimeAborted(phase, sentinel.reason);
|
|
167
|
+
throw error;
|
|
168
|
+
} finally {
|
|
169
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/execution/run-with-middleware.ts
|
|
174
|
+
/**
|
|
175
|
+
* Drives a single execution of `runDriver()` through the middleware lifecycle.
|
|
176
|
+
*
|
|
177
|
+
* Lifecycle, in order:
|
|
178
|
+
* 1. For each middleware in registration order: `intercept(exec, ctx)`. The
|
|
179
|
+
* first non-`undefined` result wins; subsequent middleware's `intercept`
|
|
180
|
+
* does not fire. On a hit, the runtime emits a `middleware.intercept`
|
|
181
|
+
* debug event naming the winning middleware, switches the row source to
|
|
182
|
+
* the intercepted rows, and proceeds with `source: 'middleware'`. On
|
|
183
|
+
* all-passthrough (every `intercept` returns `undefined` or is omitted),
|
|
184
|
+
* `source: 'driver'` is used and the row source is `runDriver()`.
|
|
185
|
+
* 2. If `source === 'driver'`: for each middleware in registration order,
|
|
186
|
+
* `beforeExecute(exec, ctx)`. Skipped on the intercepted hit path —
|
|
187
|
+
* `beforeExecute` semantically means "about to hit the driver".
|
|
188
|
+
* 3. Iterate the row source. On the driver path, for each row, for each
|
|
189
|
+
* middleware in registration order: `onRow(row, exec, ctx)`; then yield
|
|
190
|
+
* the row. On the intercepted hit path, `onRow` is skipped — intercepted
|
|
191
|
+
* rows did not originate from a driver row stream — but rows are still
|
|
192
|
+
* yielded to the consumer in order.
|
|
193
|
+
* 4. On successful completion: for each middleware in registration order:
|
|
194
|
+
* `afterExecute(exec, { rowCount, latencyMs, completed: true, source },
|
|
195
|
+
* ctx)`.
|
|
196
|
+
* 5. On any error thrown during steps 1–3: for each middleware in
|
|
197
|
+
* registration order: `afterExecute(exec, { rowCount, latencyMs,
|
|
198
|
+
* completed: false, source }, ctx)`. Errors thrown by `afterExecute`
|
|
199
|
+
* during the error path are swallowed so they do not mask the original
|
|
200
|
+
* error. The original error is then rethrown.
|
|
201
|
+
*
|
|
202
|
+
* The `source` field on `AfterExecuteResult` lets observers (telemetry,
|
|
203
|
+
* lints, budgets) distinguish driver-served from middleware-served
|
|
204
|
+
* executions without needing their own out-of-band signal.
|
|
205
|
+
*
|
|
206
|
+
* This helper is the single canonical implementation of the middleware
|
|
207
|
+
* orchestration loop; family runtimes should not reimplement it.
|
|
208
|
+
*/
|
|
209
|
+
function runWithMiddleware(exec, middleware, ctx, runDriver) {
|
|
210
|
+
const iterator = async function* () {
|
|
211
|
+
const startedAt = Date.now();
|
|
212
|
+
let rowCount = 0;
|
|
213
|
+
let completed = false;
|
|
214
|
+
let source = "driver";
|
|
215
|
+
let rowSource;
|
|
216
|
+
try {
|
|
217
|
+
for (const mw of middleware) {
|
|
218
|
+
if (!mw.intercept) continue;
|
|
219
|
+
source = "middleware";
|
|
220
|
+
const result = await mw.intercept(exec, ctx);
|
|
221
|
+
if (result === void 0) {
|
|
222
|
+
source = "driver";
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
ctx.log.debug?.({
|
|
226
|
+
event: "middleware.intercept",
|
|
227
|
+
middleware: mw.name
|
|
228
|
+
});
|
|
229
|
+
rowSource = result.rows;
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
if (source === "driver") {
|
|
233
|
+
for (const mw of middleware) if (mw.beforeExecute) await mw.beforeExecute(exec, ctx);
|
|
234
|
+
rowSource = runDriver();
|
|
235
|
+
}
|
|
236
|
+
for await (const row of rowSource) {
|
|
237
|
+
if (source === "driver") {
|
|
238
|
+
for (const mw of middleware) if (mw.onRow) await mw.onRow(row, exec, ctx);
|
|
239
|
+
}
|
|
240
|
+
rowCount++;
|
|
241
|
+
yield row;
|
|
242
|
+
}
|
|
243
|
+
completed = true;
|
|
244
|
+
} catch (error) {
|
|
245
|
+
const latencyMs = Date.now() - startedAt;
|
|
246
|
+
for (const mw of middleware) if (mw.afterExecute) try {
|
|
247
|
+
await mw.afterExecute(exec, {
|
|
248
|
+
rowCount,
|
|
249
|
+
latencyMs,
|
|
250
|
+
completed,
|
|
251
|
+
source
|
|
252
|
+
}, ctx);
|
|
253
|
+
} catch {}
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
const latencyMs = Date.now() - startedAt;
|
|
257
|
+
for (const mw of middleware) if (mw.afterExecute) await mw.afterExecute(exec, {
|
|
258
|
+
rowCount,
|
|
259
|
+
latencyMs,
|
|
260
|
+
completed,
|
|
261
|
+
source
|
|
262
|
+
}, ctx);
|
|
263
|
+
};
|
|
264
|
+
return new AsyncIterableResult(iterator());
|
|
265
|
+
}
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/execution/runtime-core.ts
|
|
268
|
+
/**
|
|
269
|
+
* Family-agnostic abstract runtime base.
|
|
270
|
+
*
|
|
271
|
+
* Defines the entire `execute(plan)` template in one place:
|
|
272
|
+
*
|
|
273
|
+
* 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides
|
|
274
|
+
* this to run its `beforeCompile` middleware-hook chain.
|
|
275
|
+
* 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`
|
|
276
|
+
* (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).
|
|
277
|
+
* 3. `runWithMiddleware(exec, this.middleware, this.ctx,
|
|
278
|
+
* () => runDriver(exec))` — concrete; lifts the middleware lifecycle
|
|
279
|
+
* out of the family runtimes into the canonical helper.
|
|
280
|
+
*
|
|
281
|
+
* Concrete subclasses must implement `lower`, `runDriver`, and `close`.
|
|
282
|
+
*
|
|
283
|
+
* The class is generic over:
|
|
284
|
+
* - `TPlan` — the family's pre-lowering plan type.
|
|
285
|
+
* - `TExec` — the family's post-lowering (executable) plan type.
|
|
286
|
+
* - `TMiddleware` — the family's middleware type. Constrained to
|
|
287
|
+
* `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the
|
|
288
|
+
* `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered
|
|
289
|
+
* `TExec`. (The spec/plan wording "RuntimeMiddleware<TPlan>" is
|
|
290
|
+
* tightened to `<TExec>` here so the helper call typechecks; the
|
|
291
|
+
* intent is unchanged — middleware sees the post-lowering plan.)
|
|
292
|
+
*/
|
|
293
|
+
var RuntimeCore = class {
|
|
294
|
+
middleware;
|
|
295
|
+
ctx;
|
|
296
|
+
constructor(options) {
|
|
297
|
+
this.middleware = options.middleware;
|
|
298
|
+
this.ctx = options.ctx;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses
|
|
302
|
+
* may override to run a `beforeCompile` middleware chain (SQL does this
|
|
303
|
+
* to support typed AST rewrites — see `before-compile-chain.ts`).
|
|
304
|
+
*/
|
|
305
|
+
runBeforeCompile(plan) {
|
|
306
|
+
return plan;
|
|
307
|
+
}
|
|
308
|
+
execute(plan, options) {
|
|
309
|
+
const self = this;
|
|
310
|
+
const signal = options?.signal;
|
|
311
|
+
const codecCtx = signal === void 0 ? {} : { signal };
|
|
312
|
+
async function* generator() {
|
|
313
|
+
checkAborted(codecCtx, "stream");
|
|
314
|
+
const compiled = await self.runBeforeCompile(plan);
|
|
315
|
+
const exec = await self.lower(compiled, codecCtx);
|
|
316
|
+
yield* runWithMiddleware(exec, self.middleware, self.ctx, () => self.runDriver(exec));
|
|
317
|
+
}
|
|
318
|
+
return new AsyncIterableResult(generator());
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
//#endregion
|
|
322
|
+
//#region src/execution/runtime-middleware.ts
|
|
76
323
|
function checkMiddlewareCompatibility(middleware, runtimeFamilyId, runtimeTargetId) {
|
|
77
324
|
if (middleware.targetId !== void 0 && middleware.familyId === void 0) throw runtimeError("RUNTIME.MIDDLEWARE_INCOMPATIBLE", `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`, {
|
|
78
325
|
middleware: middleware.name,
|
|
@@ -89,7 +336,7 @@ function checkMiddlewareCompatibility(middleware, runtimeFamilyId, runtimeTarget
|
|
|
89
336
|
runtimeTargetId
|
|
90
337
|
});
|
|
91
338
|
}
|
|
92
|
-
|
|
93
339
|
//#endregion
|
|
94
|
-
export { AsyncIterableResult, checkMiddlewareCompatibility, runtimeError };
|
|
340
|
+
export { AsyncIterableResult, RUNTIME_ABORTED, RuntimeCore, checkAborted, checkMiddlewareCompatibility, isRuntimeError, raceAgainstAbort, runWithMiddleware, runtimeAborted, runtimeError };
|
|
341
|
+
|
|
95
342
|
//# 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\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":";AAOA,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;;;;;;AClCb,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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,CAC1F"}
|
|
1
|
+
{"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 */\nexport const RUNTIME_ABORTED = 'RUNTIME.ABORTED' as const;\n\n/** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */\nexport type RuntimeAbortedPhase = 'encode' | 'decode' | 'stream';\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 (encode / decode / stream); cause carries `signal.reason`\n * verbatim from the platform — native abort produces a `DOMException`,\n * explicit `controller.abort(reason)` produces whatever the caller passed.\n * 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 { CodecCallContext } from '../shared/codec-types';\nimport type { RuntimeAbortedPhase } from './runtime-error';\nimport { runtimeAborted } from './runtime-error';\n\n/**\n * Throw a phase-tagged `RUNTIME.ABORTED` envelope if the supplied\n * codec-call context is already aborted at the precheck site. Centralises\n * the `if (ctx.signal?.aborted) throw runtimeAborted(...)` pattern that\n * every codec dispatch site repeats.\n */\nexport function checkAborted(ctx: CodecCallContext, phase: RuntimeAbortedPhase): 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 type { RuntimeMiddleware, RuntimeMiddlewareContext } 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<TExec extends ExecutionPlan, Row>(\n exec: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec>>,\n ctx: RuntimeMiddlewareContext,\n runDriver: () => AsyncIterable<Row>,\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 await mw.beforeExecute(exec, ctx);\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\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\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 * 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 */\nexport interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan> {\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?(plan: TPlan, ctx: RuntimeMiddlewareContext): 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, runtimeTargetId },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAa,kBAAkB;;;;;;;AAW/B,SAAgB,eAAe,OAA+C;CAC5E,OACE,iBAAiB,SACjB,UAAU,SACV,OAAQ,MAA6B,SAAS,YAC9C,cAAc,SACd,cAAc;;AAIlB,SAAgB,aACd,MACA,SACA,SACsB;CACtB,MAAM,QAAQ,IAAI,MAAM,QAAQ;CAChC,OAAO,eAAe,OAAO,QAAQ;EACnC,OAAO;EACP,cAAc;EACf,CAAC;CAEF,OAAO,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;CACrC,QAAQ,QAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,UACH,OAAO;EACT,SACE,OAAO;;;;;;;;;;AAW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AAE,YAAY,WAAW;EAAM,UAAU,WAAW;EAAU,CAC/D;CAGH,IAAI,WAAW,aAAa,KAAA,KAAa,WAAW,aAAa,iBAC/D,MAAM,aACJ,sCACA,eAAe,WAAW,KAAK,qBAAqB,WAAW,SAAS,8CAA8C,gBAAgB,IACtI;EAAE,YAAY,WAAW;EAAM,oBAAoB,WAAW;EAAU;EAAiB,CAC1F;CAGH,IAAI,WAAW,aAAa,KAAA,KAAa,WAAW,aAAa,iBAC/D,MAAM,aACJ,sCACA,eAAe,WAAW,KAAK,qBAAqB,WAAW,SAAS,8CAA8C,gBAAgB,IACtI;EAAE,YAAY,WAAW;EAAM,oBAAoB,WAAW;EAAU;EAAiB,CAC1F"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#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,20 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/framework-components",
|
|
3
|
-
"version": "0.5.0-dev.
|
|
3
|
+
"version": "0.5.0-dev.70",
|
|
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/utils": "0.5.0-dev.
|
|
9
|
+
"@standard-schema/spec": "^1.1.0",
|
|
10
|
+
"@prisma-next/contract": "0.5.0-dev.70",
|
|
11
|
+
"@prisma-next/utils": "0.5.0-dev.70",
|
|
12
|
+
"@prisma-next/operations": "0.5.0-dev.70"
|
|
11
13
|
},
|
|
12
14
|
"devDependencies": {
|
|
13
|
-
"tsdown": "0.
|
|
15
|
+
"tsdown": "0.22.0",
|
|
14
16
|
"typescript": "5.9.3",
|
|
15
|
-
"vitest": "4.
|
|
16
|
-
"@prisma-next/
|
|
17
|
-
"@prisma-next/
|
|
17
|
+
"vitest": "4.1.5",
|
|
18
|
+
"@prisma-next/tsconfig": "0.0.0",
|
|
19
|
+
"@prisma-next/tsdown": "0.0.0"
|
|
18
20
|
},
|
|
19
21
|
"files": [
|
|
20
22
|
"dist",
|
|
@@ -27,6 +29,7 @@
|
|
|
27
29
|
"./control": "./dist/control.mjs",
|
|
28
30
|
"./emission": "./dist/emission.mjs",
|
|
29
31
|
"./execution": "./dist/execution.mjs",
|
|
32
|
+
"./psl-ast": "./dist/psl-ast.mjs",
|
|
30
33
|
"./runtime": "./dist/runtime.mjs",
|
|
31
34
|
"./package.json": "./package.json"
|
|
32
35
|
},
|
|
@@ -0,0 +1,95 @@
|
|
|
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. Today's only implementer is the SQL family
|
|
81
|
+
* (`SqlMigrationRunner`); Mongo per-space is a non-goal per the project
|
|
82
|
+
* spec for extension contract spaces (TML-2397).
|
|
83
|
+
*
|
|
84
|
+
* The CLI uses this guard to route `db init` / `db update` through a
|
|
85
|
+
* per-space wiring when extensions expose a `contractSpace`, falling back
|
|
86
|
+
* to the single-space path when no multi-space capability is present.
|
|
87
|
+
*/
|
|
88
|
+
export function hasMultiSpaceRunner<TFamilyId extends string, TTargetId extends string>(
|
|
89
|
+
runner: MigrationRunner<TFamilyId, TTargetId>,
|
|
90
|
+
): runner is MigrationRunner<TFamilyId, TTargetId> & MultiSpaceCapableRunner<TFamilyId, TTargetId> {
|
|
91
|
+
return (
|
|
92
|
+
'executeAcrossSpaces' in runner &&
|
|
93
|
+
typeof (runner as Record<string, unknown>)['executeAcrossSpaces'] === 'function'
|
|
94
|
+
);
|
|
95
|
+
}
|
|
@@ -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,
|