@prisma-next/framework-components 0.5.0-dev.4 → 0.5.0-dev.41
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 +61 -0
- package/dist/authoring.d.mts +1 -1
- package/dist/authoring.mjs +1 -1
- package/dist/authoring.mjs.map +1 -1
- package/dist/codec-types-CB0jWeHU.d.mts +207 -0
- package/dist/codec-types-CB0jWeHU.d.mts.map +1 -0
- package/dist/codec.d.mts +2 -2
- package/dist/codec.mjs +38 -2
- package/dist/codec.mjs.map +1 -1
- package/dist/components.d.mts +1 -1
- package/dist/components.mjs +1 -1
- package/dist/control.d.mts +101 -35
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +11 -5
- package/dist/control.mjs.map +1 -1
- package/dist/emission-types-D6t3_a0x.d.mts +39 -0
- package/dist/emission-types-D6t3_a0x.d.mts.map +1 -0
- package/dist/emission.d.mts +2 -2
- package/dist/execution.d.mts +5 -5
- package/dist/execution.d.mts.map +1 -1
- package/dist/execution.mjs +3 -3
- package/dist/execution.mjs.map +1 -1
- package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-BdrFDx4x.d.mts} +2 -2
- package/dist/framework-authoring-BdrFDx4x.d.mts.map +1 -0
- package/dist/{framework-components-EJXe-pum.d.mts → framework-components-AHI6V96G.d.mts} +6 -6
- package/dist/framework-components-AHI6V96G.d.mts.map +1 -0
- package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-BsWST1Rn.mjs} +2 -2
- package/dist/framework-components-BsWST1Rn.mjs.map +1 -0
- package/dist/psl-ast-9X5rwo98.d.mts +159 -0
- package/dist/psl-ast-9X5rwo98.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 +251 -19
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +215 -4
- package/dist/runtime.mjs.map +1 -1
- package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-D-O6GotH.d.mts} +2 -2
- package/dist/types-import-spec-D-O6GotH.d.mts.map +1 -0
- package/package.json +8 -6
- package/src/control/control-capabilities.ts +71 -0
- package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
- package/src/{control-instances.ts → control/control-instances.ts} +6 -6
- package/src/{control-migration-types.ts → control/control-migration-types.ts} +48 -23
- package/src/control/control-operation-preview.ts +23 -0
- package/src/{control-stack.ts → control/control-stack.ts} +13 -13
- 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 +77 -0
- package/src/execution/runtime-core.ts +133 -0
- package/src/execution/runtime-error.ts +83 -0
- package/src/{runtime-middleware.ts → execution/runtime-middleware.ts} +32 -12
- package/src/exports/authoring.ts +2 -2
- package/src/exports/codec.ts +14 -2
- package/src/exports/components.ts +2 -2
- package/src/exports/control.ts +26 -12
- 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 +16 -5
- package/src/shared/codec-types.ts +261 -0
- 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/{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/{framework-authoring.ts → shared/framework-authoring.ts} +0 -0
- /package/src/{framework-components.ts → shared/framework-components.ts} +0 -0
- /package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +0 -0
- /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
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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AU;EAAiB,CAC1F"}
|
|
1
|
+
{"version":3,"file":"runtime.mjs","names":["out: Row[]","sentinel: { reason: unknown }","onAbort: (() => void) | undefined","latencyMs","codecCtx: CodecCallContext"],"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: `beforeExecute(exec, ctx)`.\n * 2. For each row yielded by `runDriver()`: for each middleware in registration\n * order: `onRow(row, exec, ctx)`; then yield the row to the consumer.\n * 3. On successful completion: for each middleware in registration order:\n * `afterExecute(exec, { rowCount, latencyMs, completed: true }, ctx)`.\n * 4. On any error thrown by the driver loop: for each middleware in\n * registration order: `afterExecute(exec, { rowCount, latencyMs,\n * completed: false }, ctx)`. Errors thrown by `afterExecute` during the\n * error path are swallowed so they do not mask the original driver error.\n * The original error is then rethrown.\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\n try {\n for (const mw of middleware) {\n if (mw.beforeExecute) {\n await mw.beforeExecute(exec, ctx);\n }\n }\n\n for await (const row of runDriver()) {\n for (const mw of middleware) {\n if (mw.onRow) {\n await mw.onRow(row as Record<string, unknown>, exec, ctx);\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 }, ctx);\n } catch {\n // Swallow afterExecute errors during the error path so they do not\n // mask the original driver 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 }, 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 { 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\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\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 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;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;;;;;;;;;;AAWb,SAAgB,eAAe,OAA4B,OAAuC;CAChG,MAAM,WAAW,aAAa,iBAAiB,4BAA4B,SAAS,EAAE,OAAO,CAAC;AAC9F,QAAO,OAAO,OAAO,UAAU,EAAE,OAAO,CAAC;;;;;AC/E3C,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,WAAW;AAChB,OAAK,aAAa;AAClB,SAAO,KAAK;;CAGd,UAA0B;AACxB,MAAI,KAAK,eAAe,WACtB,QAAO,QAAQ,OAC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AAM,OAAO,MAAM,KAAK,MAAM,UAAU,SAAS;AAGjD,UAAO,kBACL,MACA,KAAK,YACL,KAAK,WACC,KAAK,UAAU,KAAK,CAC3B;;AAGH,SAAO,IAAI,oBAAoB,WAAW,CAAC;;;;;;ACxD/C,SAAgB,6BACd,YACA,iBACA,iBACM;AACN,KAAI,WAAW,aAAa,UAAa,WAAW,aAAa,OAC/D,OAAM,aACJ,mCACA,eAAe,WAAW,KAAK,wBAAwB,WAAW,SAAS,qBAC3E;EAAE,YAAY,WAAW;EAAM,UAAU,WAAW;EAAU,CAC/D;AAGH,KAAI,WAAW,aAAa,UAAa,WAAW,aAAa,gBAC/D,OAAM,aACJ,sCACA,eAAe,WAAW,KAAK,qBAAqB,WAAW,SAAS,8CAA8C,gBAAgB,IACtI;EAAE,YAAY,WAAW;EAAM,oBAAoB,WAAW;EAAU;EAAiB,CAC1F;AAGH,KAAI,WAAW,aAAa,UAAa,WAAW,aAAa,gBAC/D,OAAM,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-D-O6GotH.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-import-spec-D-O6GotH.d.mts","names":[],"sources":["../src/shared/types-import-spec.ts"],"sourcesContent":[],"mappings":";;AAIA;;;UAAiB,eAAA"}
|
package/package.json
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/framework-components",
|
|
3
|
-
"version": "0.5.0-dev.
|
|
3
|
+
"version": "0.5.0-dev.41",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "Framework component types, assembly logic, and stack creation for Prisma Next",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@
|
|
9
|
-
"@prisma-next/
|
|
10
|
-
"@prisma-next/utils": "0.5.0-dev.
|
|
8
|
+
"@standard-schema/spec": "^1.1.0",
|
|
9
|
+
"@prisma-next/contract": "0.5.0-dev.41",
|
|
10
|
+
"@prisma-next/utils": "0.5.0-dev.41",
|
|
11
|
+
"@prisma-next/operations": "0.5.0-dev.41"
|
|
11
12
|
},
|
|
12
13
|
"devDependencies": {
|
|
13
14
|
"tsdown": "0.18.4",
|
|
14
15
|
"typescript": "5.9.3",
|
|
15
16
|
"vitest": "4.0.17",
|
|
16
|
-
"@prisma-next/
|
|
17
|
-
"@prisma-next/
|
|
17
|
+
"@prisma-next/tsdown": "0.0.0",
|
|
18
|
+
"@prisma-next/tsconfig": "0.0.0"
|
|
18
19
|
},
|
|
19
20
|
"files": [
|
|
20
21
|
"dist",
|
|
@@ -27,6 +28,7 @@
|
|
|
27
28
|
"./control": "./dist/control.mjs",
|
|
28
29
|
"./emission": "./dist/emission.mjs",
|
|
29
30
|
"./execution": "./dist/execution.mjs",
|
|
31
|
+
"./psl-ast": "./dist/psl-ast.mjs",
|
|
30
32
|
"./runtime": "./dist/runtime.mjs",
|
|
31
33
|
"./package.json": "./package.json"
|
|
32
34
|
},
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { ControlTargetDescriptor } from './control-descriptors';
|
|
2
|
+
import type { ControlFamilyInstance } from './control-instances';
|
|
3
|
+
import type { MigrationPlanOperation, TargetMigrationsCapability } from './control-migration-types';
|
|
4
|
+
import type { OperationPreview } from './control-operation-preview';
|
|
5
|
+
import type { CoreSchemaView } from './control-schema-view';
|
|
6
|
+
import type { PslDocumentAst } from './psl-ast';
|
|
7
|
+
|
|
8
|
+
export interface MigratableTargetDescriptor<
|
|
9
|
+
TFamilyId extends string,
|
|
10
|
+
TTargetId extends string,
|
|
11
|
+
TFamilyInstance extends ControlFamilyInstance<TFamilyId, unknown> = ControlFamilyInstance<
|
|
12
|
+
TFamilyId,
|
|
13
|
+
unknown
|
|
14
|
+
>,
|
|
15
|
+
> extends ControlTargetDescriptor<TFamilyId, TTargetId> {
|
|
16
|
+
readonly migrations: TargetMigrationsCapability<TFamilyId, TTargetId, TFamilyInstance>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function hasMigrations<TFamilyId extends string, TTargetId extends string>(
|
|
20
|
+
target: ControlTargetDescriptor<TFamilyId, TTargetId>,
|
|
21
|
+
): target is MigratableTargetDescriptor<TFamilyId, TTargetId> {
|
|
22
|
+
return 'migrations' in target && !!(target as Record<string, unknown>)['migrations'];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface SchemaViewCapable<TSchemaIR = unknown> {
|
|
26
|
+
toSchemaView(schema: TSchemaIR): CoreSchemaView;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function hasSchemaView<TFamilyId extends string, TSchemaIR>(
|
|
30
|
+
instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,
|
|
31
|
+
): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & SchemaViewCapable<TSchemaIR> {
|
|
32
|
+
return (
|
|
33
|
+
'toSchemaView' in instance &&
|
|
34
|
+
typeof (instance as Record<string, unknown>)['toSchemaView'] === 'function'
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Capability declaring that a family can infer a PSL contract AST from its
|
|
40
|
+
* opaque introspected schema IR. Consumed by `prisma-next contract infer`.
|
|
41
|
+
*/
|
|
42
|
+
export interface PslContractInferCapable<TSchemaIR = unknown> {
|
|
43
|
+
inferPslContract(schemaIR: TSchemaIR): PslDocumentAst;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function hasPslContractInfer<TFamilyId extends string, TSchemaIR>(
|
|
47
|
+
instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,
|
|
48
|
+
): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & PslContractInferCapable<TSchemaIR> {
|
|
49
|
+
return (
|
|
50
|
+
'inferPslContract' in instance &&
|
|
51
|
+
typeof (instance as Record<string, unknown>)['inferPslContract'] === 'function'
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Capability declaring that a family can render a textual preview of migration
|
|
57
|
+
* operations for the CLI's "DDL preview" output. SQL families emit
|
|
58
|
+
* `language: 'sql'` statements; Mongo families emit `language: 'mongodb-shell'`.
|
|
59
|
+
*/
|
|
60
|
+
export interface OperationPreviewCapable {
|
|
61
|
+
toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function hasOperationPreview<TFamilyId extends string, TSchemaIR>(
|
|
65
|
+
instance: ControlFamilyInstance<TFamilyId, TSchemaIR>,
|
|
66
|
+
): instance is ControlFamilyInstance<TFamilyId, TSchemaIR> & OperationPreviewCapable {
|
|
67
|
+
return (
|
|
68
|
+
'toOperationPreview' in instance &&
|
|
69
|
+
typeof (instance as Record<string, unknown>)['toOperationPreview'] === 'function'
|
|
70
|
+
);
|
|
71
|
+
}
|
|
@@ -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> {
|
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
import type { Contract } from '@prisma-next/contract/types';
|
|
13
13
|
import type { Result } from '@prisma-next/utils/result';
|
|
14
|
+
import type { TargetBoundComponentDescriptor } from '../shared/framework-components';
|
|
14
15
|
import type { ControlDriverInstance, ControlFamilyInstance } from './control-instances';
|
|
15
|
-
import type { TargetBoundComponentDescriptor } from './framework-components';
|
|
16
16
|
|
|
17
17
|
// ============================================================================
|
|
18
18
|
// Operation Classes and Policy
|
|
@@ -48,20 +48,21 @@ export interface SerializedQueryPlan {
|
|
|
48
48
|
* serialized to JSON ASTs at verification time, and rendered to SQL
|
|
49
49
|
* by the target adapter at apply time.
|
|
50
50
|
*
|
|
51
|
-
* The `name` serves as the invariant identity — it's recorded in the
|
|
52
|
-
* ledger and used for invariant-aware routing via environment refs.
|
|
53
|
-
*
|
|
54
51
|
* In draft state (before verification), `check` and `run` are null.
|
|
55
52
|
* After verification, they contain the serialized query ASTs.
|
|
56
53
|
*/
|
|
57
54
|
export interface DataTransformOperation extends MigrationPlanOperation {
|
|
58
55
|
readonly operationClass: 'data';
|
|
59
56
|
/**
|
|
60
|
-
*
|
|
61
|
-
* Recorded in the ledger on successful edge completion.
|
|
62
|
-
* Used by environment refs to declare required invariants.
|
|
57
|
+
* Human-readable label for this data transform.
|
|
63
58
|
*/
|
|
64
59
|
readonly name: string;
|
|
60
|
+
/**
|
|
61
|
+
* Optional opt-in routing identity. Presence opts the transform into
|
|
62
|
+
* invariant-aware routing; absence means it is path-dependent and
|
|
63
|
+
* not referenceable from refs.
|
|
64
|
+
*/
|
|
65
|
+
readonly invariantId?: string;
|
|
65
66
|
/**
|
|
66
67
|
* Path to the TypeScript source file that produced this operation.
|
|
67
68
|
* Not part of edgeId computation — for traceability only.
|
|
@@ -151,6 +152,17 @@ export interface MigrationPlan {
|
|
|
151
152
|
};
|
|
152
153
|
/** Ordered list of operations to execute. */
|
|
153
154
|
readonly operations: readonly MigrationPlanOperation[];
|
|
155
|
+
/**
|
|
156
|
+
* Sorted, deduplicated invariant ids declared by this plan's data-transform
|
|
157
|
+
* ops. Authored migrations carry the canonical value from
|
|
158
|
+
* `migration.json.providedInvariants`; planner-built plans (`db init`,
|
|
159
|
+
* `db update`) omit it (the runner treats it as `[]`). Runners read this
|
|
160
|
+
* field for marker writes and self-edge no-op detection rather than
|
|
161
|
+
* re-deriving from `operations`, since the manifest is the canonical
|
|
162
|
+
* source for the invariant set across all runners (postgres, sqlite,
|
|
163
|
+
* mongo).
|
|
164
|
+
*/
|
|
165
|
+
readonly providedInvariants?: readonly string[];
|
|
154
166
|
}
|
|
155
167
|
|
|
156
168
|
/**
|
|
@@ -289,21 +301,23 @@ export interface MigrationPlanner<
|
|
|
289
301
|
readonly contract: unknown;
|
|
290
302
|
readonly schema: unknown;
|
|
291
303
|
readonly policy: MigrationOperationPolicy;
|
|
292
|
-
/**
|
|
293
|
-
* Storage hash of the "from" contract (the state the planner assumes the
|
|
294
|
-
* database starts at). Planners use this to populate `describe()` on the
|
|
295
|
-
* produced plan so the rendered `migration.ts` has correct `from`/`to`
|
|
296
|
-
* metadata.
|
|
297
|
-
*/
|
|
298
|
-
readonly fromHash: string;
|
|
299
304
|
/**
|
|
300
305
|
* The "from" contract (the state the planner assumes the database starts
|
|
301
|
-
* at)
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
306
|
+
* at), or `null` for a baseline plan with no prior state.
|
|
307
|
+
*
|
|
308
|
+
* Planners derive any "from" identity they need to stamp onto the
|
|
309
|
+
* produced plan's `describe()` from `fromContract?.storage.storageHash
|
|
310
|
+
* ?? null`. They also pass this to data-safety strategies so they can
|
|
311
|
+
* compare `from` and `to` column shapes (e.g. to detect unsafe type
|
|
312
|
+
* changes).
|
|
313
|
+
*
|
|
314
|
+
* Required at every call site to make the structural fact "I have a
|
|
315
|
+
* prior contract / I don't" visible in the type. Reconciliation
|
|
316
|
+
* commands (`db init`, `db update`) introspect a live schema and pass
|
|
317
|
+
* `null`; authoring commands (`migration plan`) pass the previous
|
|
318
|
+
* bundle's `metadata.toContract`.
|
|
305
319
|
*/
|
|
306
|
-
readonly fromContract
|
|
320
|
+
readonly fromContract: Contract | null;
|
|
307
321
|
/**
|
|
308
322
|
* Active framework components participating in this composition.
|
|
309
323
|
* Families/targets can interpret this list to derive family-specific metadata.
|
|
@@ -335,6 +349,16 @@ export interface MigrationRunner<
|
|
|
335
349
|
TFamilyId extends string = string,
|
|
336
350
|
TTargetId extends string = string,
|
|
337
351
|
> {
|
|
352
|
+
/**
|
|
353
|
+
* Execute a migration plan against the configured driver.
|
|
354
|
+
*
|
|
355
|
+
* The `plan` parameter is trusted input. Callers are responsible for
|
|
356
|
+
* upstream verification of the originating migration package — typically
|
|
357
|
+
* by obtaining the package via `readMigrationPackage` from
|
|
358
|
+
* `@prisma-next/migration-tools/io`, which performs hash-integrity checks
|
|
359
|
+
* at the load boundary. Runners do not re-verify the plan and assume the
|
|
360
|
+
* `(metadata, ops)` pair on disk has not been tampered with since emit.
|
|
361
|
+
*/
|
|
338
362
|
execute(options: {
|
|
339
363
|
readonly plan: MigrationPlan;
|
|
340
364
|
readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;
|
|
@@ -414,11 +438,12 @@ export interface MigrationScaffoldContext {
|
|
|
414
438
|
/** Absolute path to the contract.json file, if one exists. Used by targets that emit typed-contract imports. */
|
|
415
439
|
readonly contractJsonPath?: string;
|
|
416
440
|
/**
|
|
417
|
-
* Storage hash of the "from" contract
|
|
418
|
-
* `describe()` on the
|
|
419
|
-
* is correctly
|
|
441
|
+
* Storage hash of the "from" contract, or `null` for a baseline scaffold
|
|
442
|
+
* with no prior state. Targets use this to populate `describe()` on the
|
|
443
|
+
* rendered empty migration so that identity metadata is correctly
|
|
444
|
+
* populated.
|
|
420
445
|
*/
|
|
421
|
-
readonly fromHash: string;
|
|
446
|
+
readonly fromHash: string | null;
|
|
422
447
|
/**
|
|
423
448
|
* Storage hash of the "to" contract. Same purpose as `fromHash` — threaded
|
|
424
449
|
* through so the rendered class's `describe()` declares the correct
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Family-agnostic textual preview of a migration plan, used by the CLI to
|
|
3
|
+
* render a "DDL preview" section for `db init` / `db update` / `migration plan`
|
|
4
|
+
* / `migration show`. Each statement carries a free-form `language` tag so
|
|
5
|
+
* formatters can suffix `;` for SQL but render Mongo shell lines verbatim.
|
|
6
|
+
*
|
|
7
|
+
* Producers are family-specific: SQL emits `language: 'sql'` (existing DDL
|
|
8
|
+
* extraction); Mongo emits `language: 'mongodb-shell'` via the
|
|
9
|
+
* `MongoDdlCommandFormatter` visitor.
|
|
10
|
+
*
|
|
11
|
+
* The capability `OperationPreviewCapable` (declared in
|
|
12
|
+
* `./control-capabilities`) is how a family announces it can produce these.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export interface OperationPreviewStatement {
|
|
16
|
+
readonly text: string;
|
|
17
|
+
/** Dialect identifier, e.g. `'sql'`, `'mongodb-shell'`. Free-form by design (OQ-3). */
|
|
18
|
+
readonly language: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface OperationPreview {
|
|
22
|
+
readonly statements: readonly OperationPreviewStatement[];
|
|
23
|
+
}
|
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import type { CodecLookup } from '
|
|
2
|
-
import type {
|
|
3
|
-
ControlAdapterDescriptor,
|
|
4
|
-
ControlDriverDescriptor,
|
|
5
|
-
ControlExtensionDescriptor,
|
|
6
|
-
ControlFamilyDescriptor,
|
|
7
|
-
ControlTargetDescriptor,
|
|
8
|
-
} from './control-descriptors';
|
|
1
|
+
import type { CodecLookup } from '../shared/codec-types';
|
|
9
2
|
import type {
|
|
10
3
|
AuthoringContributions,
|
|
11
4
|
AuthoringFieldNamespace,
|
|
12
5
|
AuthoringFieldPresetDescriptor,
|
|
13
6
|
AuthoringTypeConstructorDescriptor,
|
|
14
7
|
AuthoringTypeNamespace,
|
|
15
|
-
} from '
|
|
16
|
-
import type { ComponentMetadata } from '
|
|
8
|
+
} from '../shared/framework-authoring';
|
|
9
|
+
import type { ComponentMetadata } from '../shared/framework-components';
|
|
17
10
|
import type {
|
|
18
11
|
ControlMutationDefaultEntry,
|
|
19
12
|
ControlMutationDefaults,
|
|
20
13
|
MutationDefaultGeneratorDescriptor,
|
|
21
|
-
} from '
|
|
22
|
-
import type { TypesImportSpec } from '
|
|
14
|
+
} from '../shared/mutation-default-types';
|
|
15
|
+
import type { TypesImportSpec } from '../shared/types-import-spec';
|
|
16
|
+
import type {
|
|
17
|
+
ControlAdapterDescriptor,
|
|
18
|
+
ControlDriverDescriptor,
|
|
19
|
+
ControlExtensionDescriptor,
|
|
20
|
+
ControlFamilyDescriptor,
|
|
21
|
+
ControlTargetDescriptor,
|
|
22
|
+
} from './control-descriptors';
|
|
23
23
|
|
|
24
24
|
export interface AssembledAuthoringContributions {
|
|
25
25
|
readonly field: AuthoringFieldNamespace;
|
|
@@ -328,7 +328,7 @@ export function assembleControlMutationDefaults(
|
|
|
328
328
|
export function extractCodecLookup(
|
|
329
329
|
descriptors: ReadonlyArray<Pick<ComponentMetadata & { id?: string }, 'types' | 'id'>>,
|
|
330
330
|
): CodecLookup {
|
|
331
|
-
const byId = new Map<string, import('
|
|
331
|
+
const byId = new Map<string, import('../shared/codec-types').Codec>();
|
|
332
332
|
const owners = new Map<string, string>();
|
|
333
333
|
for (const descriptor of descriptors) {
|
|
334
334
|
const codecInstances = descriptor.types?.codecTypes?.codecInstances;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Contract, ContractModel } from '@prisma-next/contract/types';
|
|
2
|
+
import type { TypesImportSpec } from '../shared/types-import-spec';
|
|
3
|
+
|
|
4
|
+
export interface GenerateContractTypesOptions {
|
|
5
|
+
readonly queryOperationTypeImports?: ReadonlyArray<TypesImportSpec>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface ValidationContext {
|
|
9
|
+
readonly codecTypeImports?: ReadonlyArray<TypesImportSpec>;
|
|
10
|
+
readonly operationTypeImports?: ReadonlyArray<TypesImportSpec>;
|
|
11
|
+
readonly extensionIds?: ReadonlyArray<string>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface EmissionSpi {
|
|
15
|
+
readonly id: string;
|
|
16
|
+
|
|
17
|
+
generateStorageType(contract: Contract, storageHashTypeName: string): string;
|
|
18
|
+
|
|
19
|
+
generateModelStorageType(modelName: string, model: ContractModel): string;
|
|
20
|
+
|
|
21
|
+
getFamilyImports(): string[];
|
|
22
|
+
|
|
23
|
+
getFamilyTypeAliases(options?: GenerateContractTypesOptions): string;
|
|
24
|
+
|
|
25
|
+
getTypeMapsExpression(): string;
|
|
26
|
+
|
|
27
|
+
getContractWrapper(contractBaseName: string, typeMapsName: string): string;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Per-family resolver for typeParams that don't live inline on the
|
|
31
|
+
* framework-domain `ContractField`. Some families (notably SQL) let columns
|
|
32
|
+
* reference a named entry in `storage.types` via `typeRef`; the typeParams
|
|
33
|
+
* live on that named entry rather than on the domain field. The framework
|
|
34
|
+
* emit path consults this hook so the codec's `renderOutputType` can run
|
|
35
|
+
* for typeRef-shaped columns.
|
|
36
|
+
*
|
|
37
|
+
* Inline `field.type.typeParams` always takes precedence; the hook is only
|
|
38
|
+
* consulted when the domain field has no typeParams. Families without
|
|
39
|
+
* named storage types (e.g. mongo) don't implement this hook.
|
|
40
|
+
*
|
|
41
|
+
* Returns `undefined` when the field has no resolvable typeParams.
|
|
42
|
+
*/
|
|
43
|
+
resolveFieldTypeParams?(
|
|
44
|
+
modelName: string,
|
|
45
|
+
fieldName: string,
|
|
46
|
+
model: ContractModel,
|
|
47
|
+
contract: Contract,
|
|
48
|
+
): Record<string, unknown> | undefined;
|
|
49
|
+
}
|