@prisma-next/sql-runtime 0.11.0-dev.3 → 0.11.0-dev.30

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.
@@ -138,7 +138,7 @@ declare function lints(options?: LintsOptions): SqlMiddleware;
138
138
  //#endregion
139
139
  //#region src/runtime-spi.d.ts
140
140
  /**
141
- * Reader of the SQL contract marker. SQL runtimes call `readMarker` before executing user queries (when `verify` is enabled). The adapter owns the full marker-read flow — probing for storage, issuing the read, decoding the row — and returns a tagged result so callers can distinguish "marker storage missing", "no row for this space", and "present".
141
+ * Reader of the SQL contract marker. SQL runtimes call `readMarker` before executing user queries (unless `verifyMarker` is false). The adapter owns the full marker-read flow — probing for storage, issuing the read, decoding the row — and returns a tagged result so callers can distinguish "marker storage missing", "no row for this space", and "present".
142
142
  */
143
143
  interface MarkerReader {
144
144
  readMarker(queryable: SqlQueryable): Promise<MarkerReadResult>;
@@ -156,10 +156,24 @@ interface RuntimeFamilyAdapter<TContract = unknown> {
156
156
  readonly markerReader: MarkerReader;
157
157
  validatePlan(plan: ExecutionPlan, contract: TContract): void;
158
158
  }
159
- interface RuntimeVerifyOptions {
160
- readonly mode: 'onFirstUse' | 'startup' | 'always';
161
- readonly requireMarker: boolean;
162
- }
159
+ /**
160
+ * Controls whether the runtime reads and checks the contract marker row on first execute.
161
+ *
162
+ * - `'onFirstUse'` (default when omitted): the marker is read once per runtime lifetime, on the
163
+ * first `execute()` call. Any hash mismatch or absent marker emits a structured `warn`-level log
164
+ * through the runtime's {@link RuntimeLog} and the query proceeds. Subsequent queries skip the
165
+ * marker reader entirely.
166
+ * - `false`: the marker reader is never invoked. No log line is emitted. Use this to opt out of
167
+ * the diagnostic entirely (e.g. during a known deploy-skew window).
168
+ *
169
+ * The string-or-false shape is forward-compatible: future modes such as `'startup'` (eager check
170
+ * inside the wrapper `connect()` step) can be added as additive union members without an API break.
171
+ * `true` is intentionally not permitted — modes are always named.
172
+ *
173
+ * Default-on so contract drift surfaces by default — teams who never thought to enable the diagnostic
174
+ * still see the warning when something goes wrong.
175
+ */
176
+ type VerifyMarkerOption = 'onFirstUse' | false;
163
177
  type TelemetryOutcome = 'success' | 'runtime-error';
164
178
  interface RuntimeTelemetryEvent {
165
179
  readonly lane: string;
@@ -233,6 +247,10 @@ declare function createSqlExecutionStack<TTargetId extends string>(options: {
233
247
  declare function createExecutionContext<TContract extends Contract<SqlStorage> = Contract<SqlStorage>, TTargetId extends string = string>(options: {
234
248
  readonly contract: TContract;
235
249
  readonly stack: SqlExecutionStack<TTargetId>;
250
+ /**
251
+ * Optional driver descriptor. When provided, its `capabilities` are folded into the contract's capability matrix alongside the target, adapter, and extension packs — matching the merge `enrichContract` performs at CLI emit time. The driver is *only* consulted as a capability source here; runtime driver lifecycle is wired separately via {@link instantiateExecutionStack} + `runtime.connect`.
252
+ */
253
+ readonly driver?: RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>;
236
254
  }): ExecutionContext<TContract>;
237
255
  //#endregion
238
256
  //#region src/sql-runtime.d.ts
@@ -241,7 +259,7 @@ interface CreateRuntimeOptions<TContract extends Contract<SqlStorage> = Contract
241
259
  readonly stackInstance: ExecutionStackInstance<'sql', TTargetId, SqlRuntimeAdapterInstance<TTargetId>, RuntimeDriverInstance<'sql', TTargetId>, SqlRuntimeExtensionInstance<TTargetId>>;
242
260
  readonly context: ExecutionContext<TContract>;
243
261
  readonly driver: SqlDriver<unknown>;
244
- readonly verify: RuntimeVerifyOptions;
262
+ readonly verifyMarker?: VerifyMarkerOption;
245
263
  readonly middleware?: readonly SqlMiddleware[];
246
264
  readonly mode?: 'strict' | 'permissive';
247
265
  readonly log?: Log$1;
@@ -375,5 +393,5 @@ interface WriteContractMarkerStatements {
375
393
  }
376
394
  declare function writeContractMarker(input: WriteMarkerInput): WriteContractMarkerStatements;
377
395
  //#endregion
378
- export { SqlMiddlewareContext as $, RuntimeParameterizedCodecDescriptor as A, TypeHelperRegistry as B, RuntimeTransaction as C, ExecutionContext as D, withTransaction as E, SqlRuntimeDriverInstance as F, RuntimeTelemetryEvent as G, createSqlExecutionStack as H, SqlRuntimeExtensionDescriptor as I, LintsOptions as J, RuntimeVerifyOptions as K, SqlRuntimeExtensionInstance as L, SqlExecutionStackWithDriver as M, SqlRuntimeAdapterDescriptor as N, GeneratorStability as O, SqlRuntimeAdapterInstance as P, SqlMiddleware as Q, SqlRuntimeTargetDescriptor as R, RuntimeQueryable as S, createRuntime as T, MarkerReader as U, createExecutionContext as V, RuntimeFamilyAdapter as W, BudgetsOptions as X, lints as Y, budgets as Z, PrepareCallback as _, APP_SPACE_ID as a, Runtime as b, ensureTableStatement as c, BindSiteParams as d, parseContractMarkerRow as et, Declaration as f, ParamsFromDeclaration as g, ParamSpec as h, MarkerStatement$1 as i, validateContractCodecMappings as it, SqlExecutionStack as j, RuntimeMutationDefaultGenerator as k, readContractMarker as l, DeclaredNullable as m, Log as n, extractCodecIds as nt, SqlStatement as o, DeclaredCodecId as p, TelemetryOutcome as q, MarkerReadResult$1 as r, validateCodecRegistryCompleteness as rt, ensureSchemaStatement as s, AfterExecuteResult$1 as t, lowerSqlPlan as tt, writeContractMarker as u, PreparedStatement as v, TransactionContext as w, RuntimeConnection as x, CreateRuntimeOptions as y, SqlStaticContributions as z };
379
- //# sourceMappingURL=index-B2sP_QGE.d.mts.map
396
+ export { SqlMiddlewareContext as $, RuntimeParameterizedCodecDescriptor as A, TypeHelperRegistry as B, RuntimeTransaction as C, ExecutionContext as D, withTransaction as E, SqlRuntimeDriverInstance as F, RuntimeTelemetryEvent as G, createSqlExecutionStack as H, SqlRuntimeExtensionDescriptor as I, LintsOptions as J, TelemetryOutcome as K, SqlRuntimeExtensionInstance as L, SqlExecutionStackWithDriver as M, SqlRuntimeAdapterDescriptor as N, GeneratorStability as O, SqlRuntimeAdapterInstance as P, SqlMiddleware as Q, SqlRuntimeTargetDescriptor as R, RuntimeQueryable as S, createRuntime as T, MarkerReader as U, createExecutionContext as V, RuntimeFamilyAdapter as W, BudgetsOptions as X, lints as Y, budgets as Z, PrepareCallback as _, APP_SPACE_ID as a, Runtime as b, ensureTableStatement as c, BindSiteParams as d, parseContractMarkerRow as et, Declaration as f, ParamsFromDeclaration as g, ParamSpec as h, MarkerStatement$1 as i, validateContractCodecMappings as it, SqlExecutionStack as j, RuntimeMutationDefaultGenerator as k, readContractMarker as l, DeclaredNullable as m, Log as n, extractCodecIds as nt, SqlStatement as o, DeclaredCodecId as p, VerifyMarkerOption as q, MarkerReadResult$1 as r, validateCodecRegistryCompleteness as rt, ensureSchemaStatement as s, AfterExecuteResult$1 as t, lowerSqlPlan as tt, writeContractMarker as u, PreparedStatement as v, TransactionContext as w, RuntimeConnection as x, CreateRuntimeOptions as y, SqlStaticContributions as z };
397
+ //# sourceMappingURL=index-OaoYba4_.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-OaoYba4_.d.mts","names":[],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/sql-middleware.ts","../src/middleware/budgets.ts","../src/middleware/lints.ts","../src/runtime-spi.ts","../src/sql-context.ts","../src/sql-runtime.ts","../src/prepared/types.ts","../src/sql-marker.ts"],"mappings":";;;;;;;;;;;;;;;iBAagB,eAAA,CAAgB,QAAA,EAAU,QAAA,CAAS,UAAA,IAAc,GAAA;AAAA,iBA+BjD,6BAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;AAAA,iBA4BL,iCAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;;;;;;;;;;;;iBC7DL,YAAA,KAAA,CACd,OAAA,EAAS,OAAA,CAAQ,WAAA,EAAa,QAAA,CAAS,UAAA,GAAa,gBAAA,GACpD,QAAA,EAAU,QAAA,CAAS,UAAA,GACnB,SAAA,EAAW,YAAA,CAAa,GAAA,IACvB,gBAAA,CAAiB,GAAA;;;iB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SACN,GAAA;EAAA,SACA,GAAA,EAAK,WAAA;EAAA,SACL,IAAA,EAAM,QAAA;EAAA,SACN,KAAA,WAAgB,YAAA;ETLN;;;;;;ESanB,OAAA,CACE,MAAA,EAAQ,gBAAA,EACR,MAAA,EAAQ,MAAA,EACR,OAAA,GAAU,qBAAA,GACT,mBAAA,CAAoB,GAAA;AAAA;;;UC1DR,YAAA;EAAA,SACN,GAAA;EAAA,SACA,MAAM;AAAA;AAAA,UAGA,gBAAA;;;;;;;;AVGjB;WUMW,KAAA;EAAA,SACA,WAAA;EAAA,SACA,WAAA;EAAA,SACA,YAAA;EAAA,SACA,gBAAA;EAAA,SACA,MAAA;EAAA,SACA,IAAA,GAAO,MAAM;EVZkB;;;;;AAA0B;AA+BpE;;EA/B0C,SUqB/B,UAAA;AAAA;AAAA,cAGE,qBAAA,EAAuB,YAGnC;;;;;;;;;;AVM+B;AA4BhC;cUrBa,oBAAA,EAAsB,YAalC;AAAA,iBAEe,kBAAA,CAAmB,KAAA,WAAgB,eAAe;AAAA,UAiBjD,6BAAA;EAAA,SACN,MAAA,EAAQ,YAAA;EAAA,SACR,MAAA,EAAQ,YAAY;AAAA;AAAA,iBA2Bf,mBAAA,CAAoB,KAAA,EAAO,gBAAA,GAAmB,6BAA6B"}
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as SqlMiddlewareContext, A as RuntimeParameterizedCodecDescriptor, B as TypeHelperRegistry, C as RuntimeTransaction, D as ExecutionContext, E as withTransaction, F as SqlRuntimeDriverInstance, G as RuntimeTelemetryEvent, H as createSqlExecutionStack, I as SqlRuntimeExtensionDescriptor, J as LintsOptions, K as RuntimeVerifyOptions, L as SqlRuntimeExtensionInstance, M as SqlExecutionStackWithDriver, N as SqlRuntimeAdapterDescriptor, O as GeneratorStability, P as SqlRuntimeAdapterInstance, Q as SqlMiddleware, R as SqlRuntimeTargetDescriptor, S as RuntimeQueryable, T as createRuntime, U as MarkerReader, V as createExecutionContext, W as RuntimeFamilyAdapter, X as BudgetsOptions, Y as lints, Z as budgets, _ as PrepareCallback, a as APP_SPACE_ID, b as Runtime, c as ensureTableStatement, d as BindSiteParams, et as parseContractMarkerRow, f as Declaration, g as ParamsFromDeclaration, h as ParamSpec, i as MarkerStatement, it as validateContractCodecMappings, j as SqlExecutionStack, k as RuntimeMutationDefaultGenerator, l as readContractMarker, m as DeclaredNullable, n as Log, nt as extractCodecIds, o as SqlStatement, p as DeclaredCodecId, q as TelemetryOutcome, r as MarkerReadResult, rt as validateCodecRegistryCompleteness, s as ensureSchemaStatement, t as AfterExecuteResult, tt as lowerSqlPlan, u as writeContractMarker, v as PreparedStatement, w as TransactionContext, x as RuntimeConnection, y as CreateRuntimeOptions, z as SqlStaticContributions } from "./index-B2sP_QGE.mjs";
2
- export { APP_SPACE_ID, AfterExecuteResult, BindSiteParams, BudgetsOptions, CreateRuntimeOptions, Declaration, DeclaredCodecId, DeclaredNullable, ExecutionContext, GeneratorStability, LintsOptions, Log, MarkerReadResult, MarkerReader, MarkerStatement, ParamSpec, ParamsFromDeclaration, PrepareCallback, PreparedStatement, Runtime, RuntimeConnection, RuntimeFamilyAdapter, RuntimeMutationDefaultGenerator, RuntimeParameterizedCodecDescriptor, RuntimeQueryable, RuntimeTelemetryEvent, RuntimeTransaction, RuntimeVerifyOptions, SqlExecutionStack, SqlExecutionStackWithDriver, SqlMiddleware, SqlMiddlewareContext, SqlRuntimeAdapterDescriptor, SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance, SqlRuntimeExtensionDescriptor, SqlRuntimeExtensionInstance, SqlRuntimeTargetDescriptor, SqlStatement, SqlStaticContributions, TelemetryOutcome, TransactionContext, TypeHelperRegistry, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
1
+ import { $ as SqlMiddlewareContext, A as RuntimeParameterizedCodecDescriptor, B as TypeHelperRegistry, C as RuntimeTransaction, D as ExecutionContext, E as withTransaction, F as SqlRuntimeDriverInstance, G as RuntimeTelemetryEvent, H as createSqlExecutionStack, I as SqlRuntimeExtensionDescriptor, J as LintsOptions, K as TelemetryOutcome, L as SqlRuntimeExtensionInstance, M as SqlExecutionStackWithDriver, N as SqlRuntimeAdapterDescriptor, O as GeneratorStability, P as SqlRuntimeAdapterInstance, Q as SqlMiddleware, R as SqlRuntimeTargetDescriptor, S as RuntimeQueryable, T as createRuntime, U as MarkerReader, V as createExecutionContext, W as RuntimeFamilyAdapter, X as BudgetsOptions, Y as lints, Z as budgets, _ as PrepareCallback, a as APP_SPACE_ID, b as Runtime, c as ensureTableStatement, d as BindSiteParams, et as parseContractMarkerRow, f as Declaration, g as ParamsFromDeclaration, h as ParamSpec, i as MarkerStatement, it as validateContractCodecMappings, j as SqlExecutionStack, k as RuntimeMutationDefaultGenerator, l as readContractMarker, m as DeclaredNullable, n as Log, nt as extractCodecIds, o as SqlStatement, p as DeclaredCodecId, q as VerifyMarkerOption, r as MarkerReadResult, rt as validateCodecRegistryCompleteness, s as ensureSchemaStatement, t as AfterExecuteResult, tt as lowerSqlPlan, u as writeContractMarker, v as PreparedStatement, w as TransactionContext, x as RuntimeConnection, y as CreateRuntimeOptions, z as SqlStaticContributions } from "./index-OaoYba4_.mjs";
2
+ export { APP_SPACE_ID, AfterExecuteResult, BindSiteParams, BudgetsOptions, CreateRuntimeOptions, Declaration, DeclaredCodecId, DeclaredNullable, ExecutionContext, GeneratorStability, LintsOptions, Log, MarkerReadResult, MarkerReader, MarkerStatement, ParamSpec, ParamsFromDeclaration, PrepareCallback, PreparedStatement, Runtime, RuntimeConnection, RuntimeFamilyAdapter, RuntimeMutationDefaultGenerator, RuntimeParameterizedCodecDescriptor, RuntimeQueryable, RuntimeTelemetryEvent, RuntimeTransaction, SqlExecutionStack, SqlExecutionStackWithDriver, SqlMiddleware, SqlMiddlewareContext, SqlRuntimeAdapterDescriptor, SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance, SqlRuntimeExtensionDescriptor, SqlRuntimeExtensionInstance, SqlRuntimeTargetDescriptor, SqlStatement, SqlStaticContributions, TelemetryOutcome, TransactionContext, TypeHelperRegistry, VerifyMarkerOption, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as ensureTableStatement, c as createExecutionContext, d as budgets, f as parseContractMarkerRow, g as validateContractCodecMappings, h as validateCodecRegistryCompleteness, i as ensureSchemaStatement, l as createSqlExecutionStack, m as extractCodecIds, n as withTransaction, o as readContractMarker, p as lowerSqlPlan, r as APP_SPACE_ID, s as writeContractMarker, t as createRuntime, u as lints } from "./exports-BsRNNJxU.mjs";
1
+ import { a as ensureTableStatement, c as createExecutionContext, d as budgets, f as parseContractMarkerRow, g as validateContractCodecMappings, h as validateCodecRegistryCompleteness, i as ensureSchemaStatement, l as createSqlExecutionStack, m as extractCodecIds, n as withTransaction, o as readContractMarker, p as lowerSqlPlan, r as APP_SPACE_ID, s as writeContractMarker, t as createRuntime, u as lints } from "./exports-n51JO9iG.mjs";
2
2
  export { APP_SPACE_ID, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
@@ -1,4 +1,4 @@
1
- import { D as ExecutionContext, F as SqlRuntimeDriverInstance, I as SqlRuntimeExtensionDescriptor, L as SqlRuntimeExtensionInstance, N as SqlRuntimeAdapterDescriptor, P as SqlRuntimeAdapterInstance, R as SqlRuntimeTargetDescriptor, T as createRuntime, o as SqlStatement } from "../index-B2sP_QGE.mjs";
1
+ import { D as ExecutionContext, F as SqlRuntimeDriverInstance, I as SqlRuntimeExtensionDescriptor, L as SqlRuntimeExtensionInstance, N as SqlRuntimeAdapterDescriptor, P as SqlRuntimeAdapterInstance, R as SqlRuntimeTargetDescriptor, T as createRuntime, o as SqlStatement } from "../index-OaoYba4_.mjs";
2
2
  import { ResultType } from "@prisma-next/framework-components/runtime";
3
3
  import { Adapter, AnyQueryAst, Codec, ContractCodecRegistry, LoweredStatement, SelectAst } from "@prisma-next/sql-relational-core/ast";
4
4
  import * as _$_prisma_next_framework_components_execution0 from "@prisma-next/framework-components/execution";
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../../test/utils.ts"],"mappings":";;;;;;;;;;;;;;;AA4DA;iBAAsB,qBAAA,WACV,gBAAA,CAAiB,UAAA,CAAW,CAAA,KAAM,YAAA,CAAa,UAAA,CAAW,CAAA,GAAA,CACpE,OAAA,EAAS,UAAA,QAAkB,aAAA,GAAgB,IAAA,EAAM,CAAA,GAAI,OAAA,CAAQ,UAAA,CAAW,CAAA;;;;iBAQpD,kBAAA,CACpB,OAAA,EAAS,UAAA,QAAkB,aAAA,GAC3B,IAAA,EAAM,gBAAA,GAAmB,YAAA,YACxB,OAAA;;;;iBAOmB,gBAAA,CAAiB,MAAA,EAAQ,MAAA,EAAQ,SAAA,EAAW,YAAA,GAAe,OAAA;;;;iBAY3D,iBAAA,CACpB,MAAA,EAAQ,MAAA,EACR,QAAA,EAAU,QAAA,CAAS,UAAA,GACnB,OAAA,GAAU,MAAA,EAAQ,MAAA,KAAW,OAAA,SAC5B,OAAA;;;;iBAqBmB,uBAAA,CACpB,MAAA,EAAQ,MAAA,EACR,QAAA,EAAU,QAAA,CAAS,UAAA,IAClB,OAAA;;;;;;;iBAiBa,uBAAA,CACd,MAAA,EAAQ,aAAA,CAAc,KAAA,YACrB,qBAAA;;;;;iBAqCa,qBAAA,CACd,MAAA,EAAQ,aAAA,CAAc,KAAA,YACrB,aA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AAA,CAAS,UAAA;EAC9B,WAAA;EACA,WAAA;EACA,OAAA,GAAU,IAAA,CAAK,eAAA;AAAA,IAEhB,QAAA,CAAS,UAAA;AAAA,iBAoBI,OAAA,CAAA,GAAW,WAAW"}
@@ -1,4 +1,4 @@
1
- import { a as ensureTableStatement, c as createExecutionContext, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-BsRNNJxU.mjs";
1
+ import { a as ensureTableStatement, c as createExecutionContext, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-n51JO9iG.mjs";
2
2
  import { runtimeError } from "@prisma-next/framework-components/runtime";
3
3
  import { SelectAst, TableSource } from "@prisma-next/sql-relational-core/ast";
4
4
  import { instantiateExecutionStack } from "@prisma-next/framework-components/execution";
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":["collectAsync","SelectAstCtor"],"sources":["../../test/test-codec.ts","../../test/utils.ts"],"sourcesContent":["/**\n * Test-only helper that constructs a SQL-family `Codec` instance from author-side encode/decode functions. Replaces the legacy public `mkCodec()` factory (deleted under TML-2357); tests that need a stub codec for behavioural assertions instantiate one through this helper rather than going through `descriptor.factory(...)`.\n *\n * The body is identical in spirit to the retired `mkCodec`: promise-lift sync author functions onto the framework-required `Promise<…>` boundary, default `encodeJson`/`decodeJson` to identity when `TInput` is JSON-safe, fail loudly otherwise.\n */\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { Codec, SqlCodecCallContext } from '@prisma-next/sql-relational-core/ast';\n\ntype JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]\n ? {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n }\n : {\n encodeJson: (value: TInput) => JsonValue;\n decodeJson: (json: JsonValue) => TInput;\n };\n\nexport function defineTestCodec<\n Id extends string,\n const TTraits extends readonly CodecTrait[] = readonly [],\n TWire = unknown,\n TInput = unknown,\n>(\n config: {\n typeId: Id;\n targetTypes?: readonly string[];\n encode: (value: TInput, ctx: SqlCodecCallContext) => TWire | Promise<TWire>;\n decode: (wire: TWire, ctx: SqlCodecCallContext) => TInput | Promise<TInput>;\n traits?: TTraits;\n } & JsonRoundTripConfig<TInput>,\n): Codec<Id, TTraits, TWire, TInput> {\n const identity = (v: unknown) => v;\n const userEncode = config.encode;\n const userDecode = config.decode;\n const widenedConfig = config as {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n };\n return {\n id: config.typeId,\n encode: (value, ctx) => {\n try {\n return Promise.resolve(userEncode(value, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n decode: (wire, ctx) => {\n try {\n return Promise.resolve(userDecode(wire, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,\n decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,\n } as Codec<Id, TTraits, TWire, TInput>;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport type {\n CodecDescriptor,\n CodecMeta,\n CodecTrait,\n} from '@prisma-next/framework-components/codec';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport { SqlStorage, type SqlStorageInput } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n AnyQueryAst,\n Codec,\n ContractCodecRegistry,\n LoweredStatement,\n SelectAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport { SelectAst as SelectAstCtor, TableSource } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n APP_SPACE_ID,\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\nimport { defineTestCodec } from './test-codec';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n stability: 'field' as const,\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.\n */\n/**\n * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.\n */\nexport function buildTestContractCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ContractCodecRegistry {\n const byId = new Map<string, Codec<string>>();\n for (const codec of codecs) {\n byId.set(codec.id, codec);\n }\n // Canonical-key cache: production `forCodecRef` memoizes per `(codecId, canonicalize(typeParams))`. Tests resolve by codecId, but key the cache on the canonical pair so callers passing distinct typeParams get distinct (still codec-id-templated) entries — and so this helper cannot silently coalesce them.\n const byCanonicalKey = new Map<string, Codec<string>>();\n return {\n forColumn: () => undefined,\n forCodecRef: (ref) => {\n const canonicalKey = canonicalizeJson({\n codecId: ref.codecId,\n ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n });\n const cached = byCanonicalKey.get(canonicalKey);\n if (cached) return cached;\n const template = byId.get(ref.codecId);\n if (!template) {\n throw runtimeError(\n 'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n `Test ContractCodecRegistry has no codec for codecId '${ref.codecId}'.`,\n {\n codecId: ref.codecId,\n ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n },\n );\n }\n byCanonicalKey.set(canonicalKey, template);\n return template;\n },\n };\n}\n\n/**\n * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry\n * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.\n */\nexport function descriptorsFromCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ReadonlyArray<CodecDescriptor> {\n // Permissive paramsSchema for synthesized test descriptors: accepts any\n // shape (incl. undefined) and passes it through. Stubs do not encode\n // parameterization, so marking them `isParameterized: true` with this\n // schema lets the runtime integrity check tolerate columns that legitimately\n // carry typeParams (e.g. `sql/char@1` length=36) without re-introducing\n // the legacy \"non-parameterized + typeParams\" silent skip.\n // Permissive schema for synthesized test descriptors. `validate()` always\n // succeeds and discards input, narrowed to `void` to match the\n // `paramsSchema: StandardSchemaV1<void, void>` slot on the descriptor.\n // The factory ignores typeParams, so typing the validated output as `void`\n // is honest about what the stub does with the value.\n const acceptAnyParamsSchema = {\n '~standard': {\n version: 1 as const,\n vendor: 'sql-runtime/test-utils',\n validate: (_value: unknown) => ({ value: undefined }),\n },\n };\n const descriptors: CodecDescriptor[] = [];\n for (const instance of codecs) {\n const legacy = instance as {\n readonly traits?: readonly CodecTrait[];\n readonly targetTypes?: readonly string[];\n readonly meta?: CodecMeta;\n };\n descriptors.push({\n codecId: instance.id,\n traits: legacy.traits ?? [],\n targetTypes: legacy.targetTypes ?? [],\n paramsSchema: acceptAnyParamsSchema,\n isParameterized: true,\n factory: () => () => instance,\n ...(legacy.meta !== undefined ? { meta: legacy.meta } : {}),\n });\n }\n return descriptors;\n}\n\nexport function createTestAdapterDescriptor(\n adapter: StubAdapter,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const descriptors = descriptorsFromCodecs(adapter.__codecs);\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => descriptors,\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: StubAdapter,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.\n */\nexport type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {\n readonly __codecs: ReadonlyArray<Codec<string>>;\n};\n\n/**\n * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): StubAdapter {\n // Stub codecs for codec IDs that test contracts may reference. The set must\n // be complete enough to satisfy `assertColumnCodecIntegrity` against any\n // emitted test contract; the encode/decode bodies are passthrough since\n // the stub adapter never executes against a real driver.\n // The encode/decode bodies pass through; widen TInput to a JSON-safe type\n // so `defineTestCodec` does not require explicit JSON round-trip helpers.\n const passthroughCodec = (typeId: string, targetType: string): Codec<string> =>\n defineTestCodec({\n typeId,\n targetTypes: [targetType],\n encode: (value: string | number | boolean | null) => value,\n decode: (wire: string | number | boolean | null) => wire,\n });\n const codecs: ReadonlyArray<Codec<string>> = [\n passthroughCodec('pg/bit@1', 'bit'),\n passthroughCodec('pg/bool@1', 'bool'),\n passthroughCodec('pg/bytea@1', 'bytea'),\n passthroughCodec('pg/float4@1', 'float4'),\n passthroughCodec('pg/float8@1', 'float8'),\n passthroughCodec('pg/int2@1', 'int2'),\n defineTestCodec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n passthroughCodec('pg/int8@1', 'int8'),\n passthroughCodec('pg/interval@1', 'interval'),\n passthroughCodec('pg/json@1', 'json'),\n passthroughCodec('pg/jsonb@1', 'jsonb'),\n passthroughCodec('pg/numeric@1', 'numeric'),\n defineTestCodec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n passthroughCodec('pg/time@1', 'time'),\n defineTestCodec({\n typeId: 'pg/timestamp@1',\n targetTypes: ['timestamp'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n defineTestCodec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n // Date is not assignable to JsonValue, so the JSON round-trip pair must be supplied explicitly.\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n passthroughCodec('pg/timetz@1', 'timetz'),\n passthroughCodec('pg/varbit@1', 'varbit'),\n passthroughCodec('pg/uuid@1', 'uuid'),\n passthroughCodec('sql/char@1', 'char'),\n passthroughCodec('sql/varchar@1', 'varchar'),\n ];\n\n return {\n __codecs: codecs,\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n readMarker: async () => ({ kind: 'absent' as const }),\n },\n lower(ast: SelectAst, _ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n const refs = ast.collectParamRefs();\n const params = refs.map((ref) =>\n ref.kind === 'prepared-param-ref'\n ? ({ kind: 'bind' as const, name: ref.name } as const)\n : ({ kind: 'literal' as const, value: ref.value } as const),\n );\n return Object.freeze({ sql: sqlText, params });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorageInput, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? new SqlStorage({ ...rest['storage'], storageHash: storageHashValue })\n : new SqlStorage({ storageHash: storageHashValue }),\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\nexport function stubAst(): AnyQueryAst {\n return SelectAstCtor.from(TableSource.named('stub'));\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;;;;AAmBA,SAAgB,gBAMd,QAOmC;CACnC,MAAM,YAAY,MAAe;CACjC,MAAM,aAAa,OAAO;CAC1B,MAAM,aAAa,OAAO;CAC1B,MAAM,gBAAgB;CAItB,OAAO;EACL,IAAI,OAAO;EACX,SAAS,OAAO,QAAQ;GACtB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,OAAO,IAAI,CAAC;YACvC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,SAAS,MAAM,QAAQ;GACrB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,MAAM,IAAI,CAAC;YACtC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,YAAa,cAAc,cAAc;EACzC,YAAa,cAAc,cAAc;EAC1C;;;;ACTH,SAAS,sCAAsC;CAC7C,OAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC,WAAW,SAAS;GAAE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B,cAAc,KAAK,mBAAmB,EAAE;EACxC,gBAAgB,KAAK,qBAAqB,EAAE;EAC5C,MAAM,KAAK,WAAW,EAAE;EACxB,GAAI,YAAY,EAAE,WAAW,GAAG,EAAE;EAClC,aAAa,YAAY,KAAK,kBAAkB,qBAAqB;EACtE;;AAGH,SAAgB,UAAuB;CACrC,OAAOC,UAAc,KAAK,YAAY,MAAM,OAAO,CAAC"}
1
+ {"version":3,"file":"utils.mjs","names":["collectAsync","SelectAstCtor"],"sources":["../../test/test-codec.ts","../../test/utils.ts"],"sourcesContent":["/**\n * Test-only helper that constructs a SQL-family `Codec` instance from author-side encode/decode functions. Replaces the legacy public `mkCodec()` factory (deleted under TML-2357); tests that need a stub codec for behavioural assertions instantiate one through this helper rather than going through `descriptor.factory(...)`.\n *\n * The body is identical in spirit to the retired `mkCodec`: promise-lift sync author functions onto the framework-required `Promise<…>` boundary, default `encodeJson`/`decodeJson` to identity when `TInput` is JSON-safe, fail loudly otherwise.\n */\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { Codec, SqlCodecCallContext } from '@prisma-next/sql-relational-core/ast';\n\ntype JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]\n ? {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n }\n : {\n encodeJson: (value: TInput) => JsonValue;\n decodeJson: (json: JsonValue) => TInput;\n };\n\nexport function defineTestCodec<\n Id extends string,\n const TTraits extends readonly CodecTrait[] = readonly [],\n TWire = unknown,\n TInput = unknown,\n>(\n config: {\n typeId: Id;\n targetTypes?: readonly string[];\n encode: (value: TInput, ctx: SqlCodecCallContext) => TWire | Promise<TWire>;\n decode: (wire: TWire, ctx: SqlCodecCallContext) => TInput | Promise<TInput>;\n traits?: TTraits;\n } & JsonRoundTripConfig<TInput>,\n): Codec<Id, TTraits, TWire, TInput> {\n const identity = (v: unknown) => v;\n const userEncode = config.encode;\n const userDecode = config.decode;\n const widenedConfig = config as {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n };\n return {\n id: config.typeId,\n encode: (value, ctx) => {\n try {\n return Promise.resolve(userEncode(value, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n decode: (wire, ctx) => {\n try {\n return Promise.resolve(userDecode(wire, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,\n decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,\n } as Codec<Id, TTraits, TWire, TInput>;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport type {\n CodecDescriptor,\n CodecMeta,\n CodecTrait,\n} from '@prisma-next/framework-components/codec';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport { SqlStorage, type SqlStorageInput } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n AnyQueryAst,\n Codec,\n ContractCodecRegistry,\n LoweredStatement,\n SelectAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport { SelectAst as SelectAstCtor, TableSource } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n APP_SPACE_ID,\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\nimport { defineTestCodec } from './test-codec';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n stability: 'field' as const,\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.\n */\n/**\n * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.\n */\nexport function buildTestContractCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ContractCodecRegistry {\n const byId = new Map<string, Codec<string>>();\n for (const codec of codecs) {\n byId.set(codec.id, codec);\n }\n // Canonical-key cache: production `forCodecRef` memoizes per `(codecId, canonicalize(typeParams))`. Tests resolve by codecId, but key the cache on the canonical pair so callers passing distinct typeParams get distinct (still codec-id-templated) entries — and so this helper cannot silently coalesce them.\n const byCanonicalKey = new Map<string, Codec<string>>();\n return {\n forColumn: () => undefined,\n forCodecRef: (ref) => {\n const canonicalKey = canonicalizeJson({\n codecId: ref.codecId,\n ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n });\n const cached = byCanonicalKey.get(canonicalKey);\n if (cached) return cached;\n const template = byId.get(ref.codecId);\n if (!template) {\n throw runtimeError(\n 'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n `Test ContractCodecRegistry has no codec for codecId '${ref.codecId}'.`,\n {\n codecId: ref.codecId,\n ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n },\n );\n }\n byCanonicalKey.set(canonicalKey, template);\n return template;\n },\n };\n}\n\n/**\n * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry\n * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.\n */\nexport function descriptorsFromCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ReadonlyArray<CodecDescriptor> {\n // Permissive paramsSchema for synthesized test descriptors: accepts any\n // shape (incl. undefined) and passes it through. Stubs do not encode\n // parameterization, so marking them `isParameterized: true` with this\n // schema lets the runtime integrity check tolerate columns that legitimately\n // carry typeParams (e.g. `sql/char@1` length=36) without re-introducing\n // the legacy \"non-parameterized + typeParams\" silent skip.\n // Permissive schema for synthesized test descriptors. `validate()` always\n // succeeds and discards input, narrowed to `void` to match the\n // `paramsSchema: StandardSchemaV1<void, void>` slot on the descriptor.\n // The factory ignores typeParams, so typing the validated output as `void`\n // is honest about what the stub does with the value.\n const acceptAnyParamsSchema = {\n '~standard': {\n version: 1 as const,\n vendor: 'sql-runtime/test-utils',\n validate: (_value: unknown) => ({ value: undefined }),\n },\n };\n const descriptors: CodecDescriptor[] = [];\n for (const instance of codecs) {\n const legacy = instance as {\n readonly traits?: readonly CodecTrait[];\n readonly targetTypes?: readonly string[];\n readonly meta?: CodecMeta;\n };\n descriptors.push({\n codecId: instance.id,\n traits: legacy.traits ?? [],\n targetTypes: legacy.targetTypes ?? [],\n paramsSchema: acceptAnyParamsSchema,\n isParameterized: true,\n factory: () => () => instance,\n ...(legacy.meta !== undefined ? { meta: legacy.meta } : {}),\n });\n }\n return descriptors;\n}\n\nexport function createTestAdapterDescriptor(\n adapter: StubAdapter,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const descriptors = descriptorsFromCodecs(adapter.__codecs);\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => descriptors,\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: StubAdapter,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.\n */\nexport type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {\n readonly __codecs: ReadonlyArray<Codec<string>>;\n};\n\n/**\n * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): StubAdapter {\n // Stub codecs for codec IDs that test contracts may reference. The set must\n // be complete enough to satisfy `assertColumnCodecIntegrity` against any\n // emitted test contract; the encode/decode bodies are passthrough since\n // the stub adapter never executes against a real driver.\n // The encode/decode bodies pass through; widen TInput to a JSON-safe type\n // so `defineTestCodec` does not require explicit JSON round-trip helpers.\n const passthroughCodec = (typeId: string, targetType: string): Codec<string> =>\n defineTestCodec({\n typeId,\n targetTypes: [targetType],\n encode: (value: string | number | boolean | null) => value,\n decode: (wire: string | number | boolean | null) => wire,\n });\n const codecs: ReadonlyArray<Codec<string>> = [\n passthroughCodec('pg/bit@1', 'bit'),\n passthroughCodec('pg/bool@1', 'bool'),\n passthroughCodec('pg/bytea@1', 'bytea'),\n passthroughCodec('pg/float4@1', 'float4'),\n passthroughCodec('pg/float8@1', 'float8'),\n passthroughCodec('pg/int2@1', 'int2'),\n defineTestCodec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n passthroughCodec('pg/int8@1', 'int8'),\n passthroughCodec('pg/interval@1', 'interval'),\n passthroughCodec('pg/json@1', 'json'),\n passthroughCodec('pg/jsonb@1', 'jsonb'),\n passthroughCodec('pg/numeric@1', 'numeric'),\n defineTestCodec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n passthroughCodec('pg/time@1', 'time'),\n defineTestCodec({\n typeId: 'pg/timestamp@1',\n targetTypes: ['timestamp'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n defineTestCodec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n // Date is not assignable to JsonValue, so the JSON round-trip pair must be supplied explicitly.\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n passthroughCodec('pg/timetz@1', 'timetz'),\n passthroughCodec('pg/varbit@1', 'varbit'),\n passthroughCodec('pg/uuid@1', 'uuid'),\n passthroughCodec('sql/char@1', 'char'),\n passthroughCodec('sql/varchar@1', 'varchar'),\n ];\n\n return {\n __codecs: codecs,\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n readMarker: async () => ({ kind: 'absent' as const }),\n },\n lower(ast: SelectAst, _ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n const refs = ast.collectParamRefs();\n const params = refs.map((ref) =>\n ref.kind === 'prepared-param-ref'\n ? ({ kind: 'bind' as const, name: ref.name } as const)\n : ({ kind: 'literal' as const, value: ref.value } as const),\n );\n return Object.freeze({ sql: sqlText, params });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorageInput, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? new SqlStorage({ ...rest['storage'], storageHash: storageHashValue })\n : new SqlStorage({ storageHash: storageHashValue }),\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\nexport function stubAst(): AnyQueryAst {\n return SelectAstCtor.from(TableSource.named('stub'));\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;;;;AAmBA,SAAgB,gBAMd,QAOmC;CACnC,MAAM,YAAY,MAAe;CACjC,MAAM,aAAa,OAAO;CAC1B,MAAM,aAAa,OAAO;CAC1B,MAAM,gBAAgB;CAItB,OAAO;EACL,IAAI,OAAO;EACX,SAAS,OAAO,QAAQ;GACtB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,OAAO,GAAG,CAAC;GAC/C,SAAS,OAAO;IACd,OAAO,QAAQ,OAAO,KAAK;GAC7B;EACF;EACA,SAAS,MAAM,QAAQ;GACrB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,MAAM,GAAG,CAAC;GAC9C,SAAS,OAAO;IACd,OAAO,QAAQ,OAAO,KAAK;GAC7B;EACF;EACA,YAAa,cAAc,cAAc;EACzC,YAAa,cAAc,cAAc;CAC3C;AACF;;;ACVA,SAAS,sCAAsC;CAC7C,OAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC,WAAW,SAAS;GAAE;GAAI;EAAO,IAAI,EAAE,GAAG,CAAC;EAC3F,WAAW;CACb,EAAE;AACJ;;;;AAKA,eAAsB,sBAEpB,SAA2C,MAAmC;CAE9E,OAAOA,eAAkB,QAAQ,QAAa,IAAI,CAAC;AACrD;;;;AAKA,eAAsB,mBACpB,SACA,MACe;CACf,OAAO,mBAAmB,QAAQ,QAAQ,IAAI,CAAC;AACjD;;;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CACtE;AACF;AAEA,SAAgB,UAAuB;CACrC,OAAOC,UAAc,KAAK,YAAY,MAAM,MAAM,CAAC;AACrD"}
package/package.json CHANGED
@@ -1,27 +1,27 @@
1
1
  {
2
2
  "name": "@prisma-next/sql-runtime",
3
- "version": "0.11.0-dev.3",
3
+ "version": "0.11.0-dev.30",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "SQL runtime implementation for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/contract": "0.11.0-dev.3",
10
- "@prisma-next/utils": "0.11.0-dev.3",
11
- "@prisma-next/framework-components": "0.11.0-dev.3",
12
- "@prisma-next/ids": "0.11.0-dev.3",
13
- "@prisma-next/operations": "0.11.0-dev.3",
14
- "@prisma-next/sql-contract": "0.11.0-dev.3",
15
- "@prisma-next/sql-operations": "0.11.0-dev.3",
16
- "@prisma-next/sql-relational-core": "0.11.0-dev.3",
9
+ "@prisma-next/contract": "0.11.0-dev.30",
10
+ "@prisma-next/utils": "0.11.0-dev.30",
11
+ "@prisma-next/framework-components": "0.11.0-dev.30",
12
+ "@prisma-next/ids": "0.11.0-dev.30",
13
+ "@prisma-next/operations": "0.11.0-dev.30",
14
+ "@prisma-next/sql-contract": "0.11.0-dev.30",
15
+ "@prisma-next/sql-operations": "0.11.0-dev.30",
16
+ "@prisma-next/sql-relational-core": "0.11.0-dev.30",
17
17
  "arktype": "^2.2.0"
18
18
  },
19
19
  "devDependencies": {
20
- "@prisma-next/test-utils": "0.11.0-dev.3",
21
- "@prisma-next/tsconfig": "0.11.0-dev.3",
20
+ "@prisma-next/test-utils": "0.11.0-dev.30",
21
+ "@prisma-next/tsconfig": "0.11.0-dev.30",
22
22
  "@types/pg": "8.20.0",
23
23
  "pg": "8.20.0",
24
- "@prisma-next/tsdown": "0.11.0-dev.3",
24
+ "@prisma-next/tsdown": "0.11.0-dev.30",
25
25
  "tsdown": "0.22.0",
26
26
  "typescript": "5.9.3",
27
27
  "vitest": "4.1.6"
@@ -135,20 +135,18 @@ function decodeIncludeAggregate(alias: string, wireValue: unknown): unknown {
135
135
  }
136
136
 
137
137
  try {
138
- let parsed: unknown;
139
138
  if (typeof wireValue === 'string') {
140
- parsed = JSON.parse(wireValue);
141
- } else if (Array.isArray(wireValue)) {
142
- parsed = wireValue;
143
- } else {
144
- parsed = JSON.parse(String(wireValue));
139
+ return JSON.parse(wireValue);
145
140
  }
146
-
147
- if (!Array.isArray(parsed)) {
148
- throw new Error(`Expected array for include alias '${alias}', got ${typeof parsed}`);
141
+ if (typeof wireValue === 'object') {
142
+ // Driver layer has already parsed the JSON wire value (pg returns
143
+ // json / jsonb columns as JS values). Pass through unchanged —
144
+ // both row include arrays (`json_agg`) and scalar / combine
145
+ // include envelopes (`json_build_object`) flow through this path,
146
+ // each with their own downstream shape decoder.
147
+ return wireValue;
149
148
  }
150
-
151
- return parsed;
149
+ return JSON.parse(String(wireValue));
152
150
  } catch (error) {
153
151
  wrapIncludeAggregateFailure(error, alias, wireValue);
154
152
  }
@@ -29,8 +29,8 @@ export type {
29
29
  MarkerReader,
30
30
  RuntimeFamilyAdapter,
31
31
  RuntimeTelemetryEvent,
32
- RuntimeVerifyOptions,
33
32
  TelemetryOutcome,
33
+ VerifyMarkerOption,
34
34
  } from '../runtime-spi';
35
35
  export type {
36
36
  ExecutionContext,
@@ -2,7 +2,7 @@ import type { ExecutionPlan } from '@prisma-next/framework-components/runtime';
2
2
  import type { MarkerReadResult, SqlQueryable } from '@prisma-next/sql-relational-core/ast';
3
3
 
4
4
  /**
5
- * Reader of the SQL contract marker. SQL runtimes call `readMarker` before executing user queries (when `verify` is enabled). The adapter owns the full marker-read flow — probing for storage, issuing the read, decoding the row — and returns a tagged result so callers can distinguish "marker storage missing", "no row for this space", and "present".
5
+ * Reader of the SQL contract marker. SQL runtimes call `readMarker` before executing user queries (unless `verifyMarker` is false). The adapter owns the full marker-read flow — probing for storage, issuing the read, decoding the row — and returns a tagged result so callers can distinguish "marker storage missing", "no row for this space", and "present".
6
6
  */
7
7
  export interface MarkerReader {
8
8
  readMarker(queryable: SqlQueryable): Promise<MarkerReadResult>;
@@ -22,10 +22,24 @@ export interface RuntimeFamilyAdapter<TContract = unknown> {
22
22
  validatePlan(plan: ExecutionPlan, contract: TContract): void;
23
23
  }
24
24
 
25
- export interface RuntimeVerifyOptions {
26
- readonly mode: 'onFirstUse' | 'startup' | 'always';
27
- readonly requireMarker: boolean;
28
- }
25
+ /**
26
+ * Controls whether the runtime reads and checks the contract marker row on first execute.
27
+ *
28
+ * - `'onFirstUse'` (default when omitted): the marker is read once per runtime lifetime, on the
29
+ * first `execute()` call. Any hash mismatch or absent marker emits a structured `warn`-level log
30
+ * through the runtime's {@link RuntimeLog} and the query proceeds. Subsequent queries skip the
31
+ * marker reader entirely.
32
+ * - `false`: the marker reader is never invoked. No log line is emitted. Use this to opt out of
33
+ * the diagnostic entirely (e.g. during a known deploy-skew window).
34
+ *
35
+ * The string-or-false shape is forward-compatible: future modes such as `'startup'` (eager check
36
+ * inside the wrapper `connect()` step) can be added as additive union members without an API break.
37
+ * `true` is intentionally not permitted — modes are always named.
38
+ *
39
+ * Default-on so contract drift surfaces by default — teams who never thought to enable the diagnostic
40
+ * still see the warning when something goes wrong.
41
+ */
42
+ export type VerifyMarkerOption = 'onFirstUse' | false;
29
43
 
30
44
  export type TelemetryOutcome = 'success' | 'runtime-error';
31
45
 
@@ -9,7 +9,10 @@ import type {
9
9
  CodecRef,
10
10
  } from '@prisma-next/framework-components/codec';
11
11
  import type { ComponentDescriptor } from '@prisma-next/framework-components/components';
12
- import { checkContractComponentRequirements } from '@prisma-next/framework-components/components';
12
+ import {
13
+ checkContractComponentRequirements,
14
+ mergeCapabilityMatrices,
15
+ } from '@prisma-next/framework-components/components';
13
16
  import {
14
17
  createExecutionStack,
15
18
  type ExecutionStack,
@@ -758,10 +761,34 @@ export function createExecutionContext<
758
761
  >(options: {
759
762
  readonly contract: TContract;
760
763
  readonly stack: SqlExecutionStack<TTargetId>;
764
+ /**
765
+ * Optional driver descriptor. When provided, its `capabilities` are folded into the contract's capability matrix alongside the target, adapter, and extension packs — matching the merge `enrichContract` performs at CLI emit time. The driver is *only* consulted as a capability source here; runtime driver lifecycle is wired separately via {@link instantiateExecutionStack} + `runtime.connect`.
766
+ */
767
+ readonly driver?: RuntimeDriverDescriptor<
768
+ 'sql',
769
+ TTargetId,
770
+ unknown,
771
+ SqlRuntimeDriverInstance<TTargetId>
772
+ >;
761
773
  }): ExecutionContext<TContract> {
762
- const { contract, stack } = options;
774
+ const { stack, driver } = options;
775
+
776
+ assertExecutionStackContractRequirements(options.contract, stack);
763
777
 
764
- assertExecutionStackContractRequirements(contract, stack);
778
+ const capabilityContributors: ReadonlyArray<{ readonly capabilities?: unknown }> = [
779
+ stack.target,
780
+ stack.adapter,
781
+ ...(driver ? [driver] : []),
782
+ ...stack.extensionPacks,
783
+ ];
784
+ const mergedCapabilities = mergeCapabilityMatrices(
785
+ options.contract.capabilities,
786
+ capabilityContributors,
787
+ );
788
+ const contract: TContract = {
789
+ ...options.contract,
790
+ capabilities: mergedCapabilities,
791
+ };
765
792
 
766
793
  const contributors: Array<SqlStaticContributions & ComponentDescriptor<string>> = [
767
794
  stack.target,
@@ -61,8 +61,8 @@ import type {
61
61
  import type {
62
62
  RuntimeFamilyAdapter,
63
63
  RuntimeTelemetryEvent,
64
- RuntimeVerifyOptions,
65
64
  TelemetryOutcome,
65
+ VerifyMarkerOption,
66
66
  } from './runtime-spi';
67
67
  import type {
68
68
  ExecutionContext,
@@ -77,7 +77,7 @@ export interface RuntimeOptions<TContract extends Contract<SqlStorage> = Contrac
77
77
  readonly context: ExecutionContext<TContract>;
78
78
  readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;
79
79
  readonly driver: SqlDriver<unknown>;
80
- readonly verify: RuntimeVerifyOptions;
80
+ readonly verifyMarker?: VerifyMarkerOption;
81
81
  readonly middleware?: readonly SqlMiddleware[];
82
82
  readonly mode?: 'strict' | 'permissive';
83
83
  readonly log?: Log;
@@ -96,7 +96,7 @@ export interface CreateRuntimeOptions<
96
96
  >;
97
97
  readonly context: ExecutionContext<TContract>;
98
98
  readonly driver: SqlDriver<unknown>;
99
- readonly verify: RuntimeVerifyOptions;
99
+ readonly verifyMarker?: VerifyMarkerOption;
100
100
  readonly middleware?: readonly SqlMiddleware[];
101
101
  readonly mode?: 'strict' | 'permissive';
102
102
  readonly log?: Log;
@@ -157,7 +157,7 @@ export interface TransactionContext extends RuntimeQueryable {
157
157
  readonly invalidated: boolean;
158
158
  }
159
159
 
160
- export type { RuntimeTelemetryEvent, RuntimeVerifyOptions, TelemetryOutcome };
160
+ export type { RuntimeTelemetryEvent, TelemetryOutcome, VerifyMarkerOption };
161
161
 
162
162
  function isExecutionPlan(plan: SqlExecutionPlan | SqlQueryPlan): plan is SqlExecutionPlan {
163
163
  return 'sql' in plan;
@@ -178,15 +178,15 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
178
178
  private readonly contractCodecs: ContractCodecRegistry;
179
179
  private readonly codecDescriptors: CodecDescriptorRegistry;
180
180
  private readonly sqlCtx: SqlMiddlewareContext;
181
- private readonly verify: RuntimeVerifyOptions;
181
+ private readonly verifyMarkerOption: VerifyMarkerOption;
182
+ // Single-flight gate. Memoises the first verifyMarker() call so concurrent first-queries share one read + one log line. `null` until the first gate hit; pre-resolved when `verifyMarkerOption === false` so the gate becomes a no-op await.
183
+ private verifyMarkerPromise: Promise<void> | null;
182
184
  readonly #preparedStatementHandles = new WeakMap<object, unknown>();
183
185
  private codecRegistryValidated: boolean;
184
- private verified: boolean;
185
- private startupVerified: boolean;
186
186
  private _telemetry: RuntimeTelemetryEvent | null;
187
187
 
188
188
  constructor(options: RuntimeOptions<TContract>) {
189
- const { context, adapter, driver, verify, middleware, mode, log } = options;
189
+ const { context, adapter, driver, verifyMarker, middleware, mode, log } = options;
190
190
 
191
191
  if (middleware) {
192
192
  for (const mw of middleware) {
@@ -213,16 +213,10 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
213
213
  this.contractCodecs = context.contractCodecs;
214
214
  this.codecDescriptors = context.codecDescriptors;
215
215
  this.sqlCtx = sqlCtx;
216
- this.verify = verify;
216
+ this.verifyMarkerOption = verifyMarker ?? 'onFirstUse';
217
217
  this.codecRegistryValidated = false;
218
- this.verified = verify.mode === 'startup' ? false : verify.mode === 'always';
219
- this.startupVerified = false;
218
+ this.verifyMarkerPromise = this.verifyMarkerOption === false ? Promise.resolve() : null;
220
219
  this._telemetry = null;
221
-
222
- if (verify.mode === 'startup') {
223
- validateCodecRegistryCompleteness(this.codecDescriptors, context.contract);
224
- this.codecRegistryValidated = true;
225
- }
226
220
  }
227
221
 
228
222
  /**
@@ -336,22 +330,15 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
336
330
  this.familyAdapter.validatePlan(exec, this.contract);
337
331
  this._telemetry = null;
338
332
 
339
- if (!this.startupVerified && this.verify.mode === 'startup') {
340
- await this.verifyMarker();
341
- }
342
-
343
- if (!this.verified && this.verify.mode === 'onFirstUse') {
344
- await this.verifyMarker();
333
+ if (this.verifyMarkerPromise === null) {
334
+ this.verifyMarkerPromise = this.verifyMarker();
345
335
  }
336
+ await this.verifyMarkerPromise;
346
337
 
347
338
  const startedAt = Date.now();
348
339
  let outcome: TelemetryOutcome | null = null;
349
340
 
350
341
  try {
351
- if (this.verify.mode === 'always') {
352
- await this.verifyMarker();
353
- }
354
-
355
342
  const stream = runWithMiddleware<SqlExecutionPlan, Record<string, unknown>>(
356
343
  exec,
357
344
  this.middleware,
@@ -697,48 +684,35 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
697
684
  private async verifyMarker(): Promise<void> {
698
685
  const readResult = await this.familyAdapter.markerReader.readMarker(this.driver);
699
686
 
700
- if (readResult.kind !== 'present') {
701
- if (this.verify.requireMarker) {
702
- throw runtimeError('CONTRACT.MARKER_MISSING', 'Contract marker not found in database');
703
- }
687
+ const expectedStorageHash = this.contract.storage.storageHash;
688
+ const expectedProfileHash = this.contract.profileHash ?? null;
689
+ const expected = { storageHash: expectedStorageHash, profileHash: expectedProfileHash };
704
690
 
705
- this.verified = true;
691
+ if (readResult.kind !== 'present') {
692
+ this.sqlCtx.log.warn({
693
+ code: 'CONTRACT.MARKER_MISSING',
694
+ scope: 'marker-verification',
695
+ expected,
696
+ actual: null,
697
+ message: 'Contract marker not found in database',
698
+ });
706
699
  return;
707
700
  }
708
701
 
709
702
  const marker = readResult.record;
710
-
711
- const contract = this.contract as {
712
- storage: { storageHash: string };
713
- execution?: { executionHash?: string | null };
714
- profileHash?: string | null;
715
- };
716
-
717
- if (marker.storageHash !== contract.storage.storageHash) {
718
- throw runtimeError(
719
- 'CONTRACT.MARKER_MISMATCH',
720
- 'Database storage hash does not match contract',
721
- {
722
- expected: contract.storage.storageHash,
723
- actual: marker.storageHash,
724
- },
725
- );
703
+ const storageHashMatch = marker.storageHash === expectedStorageHash;
704
+ const profileHashMatch =
705
+ expectedProfileHash === null || marker.profileHash === expectedProfileHash;
706
+
707
+ if (!storageHashMatch || !profileHashMatch) {
708
+ this.sqlCtx.log.warn({
709
+ code: 'CONTRACT.MARKER_MISMATCH',
710
+ scope: 'marker-verification',
711
+ expected,
712
+ actual: { storageHash: marker.storageHash, profileHash: marker.profileHash ?? null },
713
+ message: 'Contract marker hash does not match runtime contract',
714
+ });
726
715
  }
727
-
728
- const expectedProfile = contract.profileHash ?? null;
729
- if (expectedProfile !== null && marker.profileHash !== expectedProfile) {
730
- throw runtimeError(
731
- 'CONTRACT.MARKER_MISMATCH',
732
- 'Database profile hash does not match contract',
733
- {
734
- expectedProfile,
735
- actualProfile: marker.profileHash,
736
- },
737
- );
738
- }
739
-
740
- this.verified = true;
741
- this.startupVerified = true;
742
716
  }
743
717
 
744
718
  private recordTelemetry(
@@ -876,13 +850,13 @@ export async function withTransaction<R>(
876
850
  export function createRuntime<TContract extends Contract<SqlStorage>, TTargetId extends string>(
877
851
  options: CreateRuntimeOptions<TContract, TTargetId>,
878
852
  ): Runtime {
879
- const { stackInstance, context, driver, verify, middleware, mode, log } = options;
853
+ const { stackInstance, context, driver, verifyMarker, middleware, mode, log } = options;
880
854
 
881
855
  return new SqlRuntimeImpl({
882
856
  context,
883
857
  adapter: stackInstance.adapter,
884
858
  driver,
885
- verify,
859
+ ...ifDefined('verifyMarker', verifyMarker),
886
860
  ...ifDefined('middleware', middleware),
887
861
  ...ifDefined('mode', mode),
888
862
  ...ifDefined('log', log),