@prisma-next/sql-runtime 0.6.0-dev.5 → 0.6.0-dev.6

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.
@@ -1079,6 +1079,7 @@ async function encodeParamValue(value, metadata, paramIndex, ctx, contractCodecs
1079
1079
  try {
1080
1080
  return await codec.encode(value, ctx);
1081
1081
  } catch (error) {
1082
+ if (isRuntimeError(error)) throw error;
1082
1083
  wrapEncodeFailure(error, metadata, paramIndex, codec.id);
1083
1084
  }
1084
1085
  }
@@ -1513,4 +1514,4 @@ function createRuntime(options) {
1513
1514
  //#endregion
1514
1515
  export { ensureTableStatement as a, createExecutionContext as c, budgets as d, parseContractMarkerRow as f, validateContractCodecMappings as g, validateCodecRegistryCompleteness as h, ensureSchemaStatement as i, createSqlExecutionStack as l, extractCodecIds as m, withTransaction as n, readContractMarker as o, lowerSqlPlan as p, APP_SPACE_ID as r, writeContractMarker as s, createRuntime as t, lints as u };
1515
1516
 
1516
- //# sourceMappingURL=exports-BSTHn_rH.mjs.map
1517
+ //# sourceMappingURL=exports-B_kfmMPM.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"exports-BSTHn_rH.mjs","names":[],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/budgets.ts","../src/guardrails/raw.ts","../src/middleware/lints.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/codecs/alias-resolver.ts","../src/codecs/decoding.ts","../src/codecs/encoding.ts","../src/content-hash.ts","../src/fingerprint.ts","../src/middleware/before-compile-chain.ts","../src/sql-family-adapter.ts","../src/sql-runtime.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\n\nexport function extractCodecIds(contract: Contract<SqlStorage>): Set<string> {\n const codecIds = new Set<string>();\n\n for (const table of Object.values(contract.storage.tables)) {\n for (const column of Object.values(table.columns)) {\n const codecId = column.codecId;\n codecIds.add(codecId);\n }\n }\n\n return codecIds;\n}\n\nfunction extractCodecIdsFromColumns(contract: Contract<SqlStorage>): Map<string, string> {\n const codecIds = new Map<string, string>();\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n const codecId = column.codecId;\n const key = `${tableName}.${columnName}`;\n codecIds.set(key, codecId);\n }\n }\n\n return codecIds;\n}\n\nexport function validateContractCodecMappings(\n registry: CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\n const codecIds = extractCodecIdsFromColumns(contract);\n const invalidCodecs: Array<{ table: string; column: string; codecId: string }> = [];\n\n for (const [key, codecId] of codecIds.entries()) {\n if (registry.descriptorFor(codecId) === undefined) {\n const parts = key.split('.');\n const table = parts[0] ?? '';\n const column = parts[1] ?? '';\n invalidCodecs.push({ table, column, codecId });\n }\n }\n\n if (invalidCodecs.length > 0) {\n const details: Record<string, unknown> = {\n contractTarget: contract.target,\n invalidCodecs,\n };\n\n throw runtimeError(\n 'RUNTIME.CODEC_MISSING',\n `Missing codec implementations for column codecIds: ${invalidCodecs.map((c) => `${c.table}.${c.column} (${c.codecId})`).join(', ')}`,\n details,\n );\n }\n}\n\nexport function validateCodecRegistryCompleteness(\n registry: CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\n validateContractCodecMappings(registry, contract);\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Adapter, AnyQueryAst, LoweredStatement } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\n\n/**\n * Lowers a SQL query plan to an executable Plan by calling the adapter's lower method.\n *\n * @param adapter - Adapter to lower AST to SQL\n * @param contract - Contract for lowering context\n * @param queryPlan - SQL query plan from a lane (contains AST, params, meta, but no SQL)\n * @returns Fully executable Plan with SQL string\n */\nexport function lowerSqlPlan<Row>(\n adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>,\n contract: Contract<SqlStorage>,\n queryPlan: SqlQueryPlan<Row>,\n): SqlExecutionPlan<Row> {\n const lowered = adapter.lower(queryPlan.ast, {\n contract,\n params: queryPlan.params,\n });\n\n return Object.freeze({\n sql: lowered.sql,\n params: lowered.params ?? queryPlan.params,\n ast: queryPlan.ast,\n meta: queryPlan.meta,\n });\n}\n","import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { type } from 'arktype';\n\nexport interface ContractMarkerRow {\n core_hash: string;\n profile_hash: string;\n contract_json: unknown | null;\n canonical_version: number | null;\n updated_at: Date;\n app_tag: string | null;\n meta: unknown | null;\n invariants: readonly string[];\n}\n\nconst MetaSchema = type({ '[string]': 'unknown' });\n\nfunction parseMeta(meta: unknown): Record<string, unknown> {\n if (meta === null || meta === undefined) {\n return {};\n }\n\n let parsed: unknown;\n if (typeof meta === 'string') {\n try {\n parsed = JSON.parse(meta);\n } catch {\n return {};\n }\n } else {\n parsed = meta;\n }\n\n const result = MetaSchema(parsed);\n if (result instanceof type.errors) {\n return {};\n }\n\n return result as Record<string, unknown>;\n}\n\nconst ContractMarkerRowSchema = type({\n core_hash: 'string',\n profile_hash: 'string',\n 'contract_json?': 'unknown | null',\n 'canonical_version?': 'number | null',\n 'updated_at?': 'Date | string',\n 'app_tag?': 'string | null',\n 'meta?': 'unknown | null',\n invariants: type('string').array(),\n});\n\nexport function parseContractMarkerRow(row: unknown): ContractMarkerRecord {\n const result = ContractMarkerRowSchema(row);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Invalid contract marker row: ${messages}`);\n }\n\n const updatedAt = result.updated_at\n ? result.updated_at instanceof Date\n ? result.updated_at\n : new Date(result.updated_at)\n : new Date();\n\n return {\n storageHash: result.core_hash,\n profileHash: result.profile_hash,\n contractJson: result.contract_json ?? null,\n canonicalVersion: result.canonical_version ?? null,\n updatedAt,\n appTag: result.app_tag ?? null,\n meta: parseMeta(result.meta),\n invariants: result.invariants,\n };\n}\n","import {\n type AfterExecuteResult,\n type RuntimeErrorEnvelope,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport { isQueryAst, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport interface BudgetsOptions {\n readonly maxRows?: number;\n readonly defaultTableRows?: number;\n readonly tableRows?: Record<string, number>;\n readonly maxLatencyMs?: number;\n readonly severities?: {\n readonly rowCount?: 'warn' | 'error';\n readonly latency?: 'warn' | 'error';\n };\n}\n\nfunction hasAggregateWithoutGroupBy(ast: SelectAst): boolean {\n if (ast.groupBy !== undefined) {\n return false;\n }\n return ast.projection.some((item) => item.expr.kind === 'aggregate');\n}\n\nfunction primaryTableFromAst(ast: SelectAst): string {\n switch (ast.from.kind) {\n case 'table-source':\n return ast.from.name;\n case 'derived-table-source':\n return ast.from.alias;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source kind: ${(ast.from satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction estimateRowsFromAst(\n ast: SelectAst,\n tableRows: Record<string, number>,\n defaultTableRows: number,\n hasAggregateWithoutGroup: boolean,\n): number {\n if (hasAggregateWithoutGroup) {\n return 1;\n }\n\n const tableEstimate = tableRows[primaryTableFromAst(ast)] ?? defaultTableRows;\n\n if (ast.limit !== undefined) {\n return Math.min(ast.limit, tableEstimate);\n }\n\n return tableEstimate;\n}\n\nfunction emitBudgetViolation(\n error: RuntimeErrorEnvelope,\n shouldBlock: boolean,\n ctx: SqlMiddlewareContext,\n): void {\n if (shouldBlock) {\n throw error;\n }\n ctx.log.warn({\n code: error.code,\n message: error.message,\n details: error.details,\n });\n}\n\nexport function budgets(options?: BudgetsOptions): SqlMiddleware {\n const maxRows = options?.maxRows ?? 10_000;\n const defaultTableRows = options?.defaultTableRows ?? 10_000;\n const tableRows = options?.tableRows ?? {};\n const maxLatencyMs = options?.maxLatencyMs ?? 1_000;\n const rowSeverity = options?.severities?.rowCount ?? 'error';\n\n const observedRowsByPlan = new WeakMap<SqlExecutionPlan, { count: number }>();\n\n return Object.freeze({\n name: 'budgets',\n familyId: 'sql' as const,\n\n async beforeExecute(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n observedRowsByPlan.set(plan, { count: 0 });\n\n if (isQueryAst(plan.ast) && plan.ast.kind === 'select') {\n return evaluateSelectAst(plan.ast, ctx);\n }\n },\n\n async onRow(_row: Record<string, unknown>, plan: SqlExecutionPlan, _ctx: SqlMiddlewareContext) {\n const state = observedRowsByPlan.get(plan);\n if (!state) return;\n state.count += 1;\n if (state.count > maxRows) {\n throw runtimeError('BUDGET.ROWS_EXCEEDED', 'Observed row count exceeds budget', {\n source: 'observed',\n observedRows: state.count,\n maxRows,\n });\n }\n },\n\n async afterExecute(\n _plan: SqlExecutionPlan,\n result: AfterExecuteResult,\n ctx: SqlMiddlewareContext,\n ) {\n const latencyMs = result.latencyMs;\n if (latencyMs > maxLatencyMs) {\n const shouldBlock = ctx.mode === 'strict';\n emitBudgetViolation(\n runtimeError('BUDGET.TIME_EXCEEDED', 'Query latency exceeds budget', {\n latencyMs,\n maxLatencyMs,\n }),\n shouldBlock,\n ctx,\n );\n }\n },\n });\n\n function evaluateSelectAst(ast: SelectAst, ctx: SqlMiddlewareContext) {\n const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);\n const estimated = estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggNoGroup);\n const isUnbounded = ast.limit === undefined && !hasAggNoGroup;\n const shouldBlock = rowSeverity === 'error' || ctx.mode === 'strict';\n\n if (isUnbounded) {\n const details =\n estimated >= maxRows\n ? { source: 'ast', estimatedRows: estimated, maxRows }\n : { source: 'ast', maxRows };\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', details),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n if (estimated > maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Estimated row count exceeds budget', {\n source: 'ast',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n }\n }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\n\nexport type LintSeverity = 'error' | 'warn';\nexport type BudgetSeverity = 'error' | 'warn';\n\nexport interface LintFinding {\n readonly code: `LINT.${string}`;\n readonly severity: LintSeverity;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface BudgetFinding {\n readonly code: `BUDGET.${string}`;\n readonly severity: BudgetSeverity;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface RawGuardrailConfig {\n readonly budgets?: {\n readonly unboundedSelectSeverity?: BudgetSeverity;\n readonly estimatedRows?: number;\n };\n}\n\nexport interface RawGuardrailResult {\n readonly lints: LintFinding[];\n readonly budgets: BudgetFinding[];\n readonly statement: 'select' | 'mutation' | 'other';\n}\n\n/**\n * Minimal plan view consumed by raw-SQL guardrails. Structurally satisfied\n * by `SqlExecutionPlan`; declared inline so this module stays decoupled\n * from a specific plan type at the call site.\n */\ninterface RawGuardrailPlan {\n readonly sql: string;\n readonly meta: PlanMeta;\n}\n\nconst SELECT_STAR_REGEX = /select\\s+\\*/i;\nconst LIMIT_REGEX = /\\blimit\\b/i;\nconst MUTATION_PREFIX_REGEX = /^(insert|update|delete|create|alter|drop|truncate)\\b/i;\n\nconst READ_ONLY_INTENTS = new Set(['read', 'report', 'readonly']);\n\nexport function evaluateRawGuardrails(\n plan: RawGuardrailPlan,\n config?: RawGuardrailConfig,\n): RawGuardrailResult {\n const lints: LintFinding[] = [];\n const budgets: BudgetFinding[] = [];\n\n const normalized = normalizeWhitespace(plan.sql);\n const statementType = classifyStatement(normalized);\n\n if (statementType === 'select') {\n if (SELECT_STAR_REGEX.test(normalized)) {\n lints.push(\n createLint('LINT.SELECT_STAR', 'error', 'Raw SQL plan selects all columns via *', {\n sql: snippet(plan.sql),\n }),\n );\n }\n\n if (!LIMIT_REGEX.test(normalized)) {\n const severity = config?.budgets?.unboundedSelectSeverity ?? 'error';\n lints.push(\n createLint('LINT.NO_LIMIT', 'warn', 'Raw SQL plan omits LIMIT clause', {\n sql: snippet(plan.sql),\n }),\n );\n\n budgets.push(\n createBudget(\n 'BUDGET.ROWS_EXCEEDED',\n severity,\n 'Raw SQL plan is unbounded and may exceed row budget',\n {\n sql: snippet(plan.sql),\n ...(config?.budgets?.estimatedRows !== undefined\n ? { estimatedRows: config.budgets.estimatedRows }\n : {}),\n },\n ),\n );\n }\n }\n\n if (isMutationStatement(statementType) && isReadOnlyIntent(plan.meta)) {\n lints.push(\n createLint(\n 'LINT.READ_ONLY_MUTATION',\n 'error',\n 'Raw SQL plan mutates data despite read-only intent',\n {\n sql: snippet(plan.sql),\n intent: plan.meta.annotations?.['intent'],\n },\n ),\n );\n }\n\n return { lints, budgets, statement: statementType };\n}\n\nfunction classifyStatement(sql: string): 'select' | 'mutation' | 'other' {\n const trimmed = sql.trim();\n const lower = trimmed.toLowerCase();\n\n if (lower.startsWith('with')) {\n if (lower.includes('select')) {\n return 'select';\n }\n }\n\n if (lower.startsWith('select')) {\n return 'select';\n }\n\n if (MUTATION_PREFIX_REGEX.test(trimmed)) {\n return 'mutation';\n }\n\n return 'other';\n}\n\nfunction isMutationStatement(statement: 'select' | 'mutation' | 'other'): boolean {\n return statement === 'mutation';\n}\n\nfunction isReadOnlyIntent(meta: PlanMeta): boolean {\n const annotations = meta.annotations as { intent?: string } | undefined;\n const intent =\n typeof annotations?.intent === 'string' ? annotations.intent.toLowerCase() : undefined;\n return intent !== undefined && READ_ONLY_INTENTS.has(intent);\n}\n\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction snippet(sql: string): string {\n return normalizeWhitespace(sql).slice(0, 200);\n}\n\nfunction createLint(\n code: LintFinding['code'],\n severity: LintFinding['severity'],\n message: string,\n details?: Record<string, unknown>,\n): LintFinding {\n return { code, severity, message, ...(details ? { details } : {}) };\n}\n\nfunction createBudget(\n code: BudgetFinding['code'],\n severity: BudgetFinding['severity'],\n message: string,\n details?: Record<string, unknown>,\n): BudgetFinding {\n return { code, severity, message, ...(details ? { details } : {}) };\n}\n","import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport {\n type AnyFromSource,\n type AnyQueryAst,\n isQueryAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { evaluateRawGuardrails } from '../guardrails/raw';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport interface LintsOptions {\n readonly severities?: {\n readonly selectStar?: 'warn' | 'error';\n readonly noLimit?: 'warn' | 'error';\n readonly deleteWithoutWhere?: 'warn' | 'error';\n readonly updateWithoutWhere?: 'warn' | 'error';\n readonly readOnlyMutation?: 'warn' | 'error';\n readonly unindexedPredicate?: 'warn' | 'error';\n };\n readonly fallbackWhenAstMissing?: 'raw' | 'skip';\n}\n\nexport interface LintFinding {\n readonly code: `LINT.${string}`;\n readonly severity: 'error' | 'warn';\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nfunction getFromSourceTableDetail(source: AnyFromSource): string | undefined {\n switch (source.kind) {\n case 'table-source':\n return source.name;\n case 'derived-table-source':\n return source.alias;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source kind: ${(source satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction evaluateAstLints(ast: AnyQueryAst): LintFinding[] {\n const findings: LintFinding[] = [];\n\n switch (ast.kind) {\n case 'delete':\n if (ast.where === undefined) {\n findings.push({\n code: 'LINT.DELETE_WITHOUT_WHERE',\n severity: 'error',\n message:\n 'DELETE without WHERE clause blocks execution to prevent accidental full-table deletion',\n details: { table: ast.table.name },\n });\n }\n break;\n\n case 'update':\n if (ast.where === undefined) {\n findings.push({\n code: 'LINT.UPDATE_WITHOUT_WHERE',\n severity: 'error',\n message:\n 'UPDATE without WHERE clause blocks execution to prevent accidental full-table update',\n details: { table: ast.table.name },\n });\n }\n break;\n\n case 'select':\n if (ast.limit === undefined) {\n const table = getFromSourceTableDetail(ast.from);\n findings.push({\n code: 'LINT.NO_LIMIT',\n severity: 'warn',\n message: 'Unbounded SELECT may return large result sets',\n ...ifDefined('details', table !== undefined ? { table } : undefined),\n });\n }\n if (ast.selectAllIntent !== undefined) {\n const table = ast.selectAllIntent.table;\n findings.push({\n code: 'LINT.SELECT_STAR',\n severity: 'warn',\n message: 'Query selects all columns via selectAll intent',\n ...ifDefined('details', table !== undefined ? { table } : undefined),\n });\n }\n break;\n\n case 'insert':\n break;\n\n case 'raw-sql':\n // Raw-SQL ASTs opt out of structural lints (LIMIT / WHERE etc.) —\n // the embedded SQL fragments are caller-authored and the lint's\n // shape-based heuristics don't apply.\n break;\n\n // v8 ignore next 2\n default:\n throw new Error(`Unsupported AST kind: ${(ast satisfies never as { kind: string }).kind}`);\n }\n\n return findings;\n}\n\nfunction getConfiguredSeverity(code: string, options?: LintsOptions): 'warn' | 'error' | undefined {\n const severities = options?.severities;\n if (!severities) return undefined;\n\n switch (code) {\n case 'LINT.SELECT_STAR':\n return severities.selectStar;\n case 'LINT.NO_LIMIT':\n return severities.noLimit;\n case 'LINT.DELETE_WITHOUT_WHERE':\n return severities.deleteWithoutWhere;\n case 'LINT.UPDATE_WITHOUT_WHERE':\n return severities.updateWithoutWhere;\n case 'LINT.READ_ONLY_MUTATION':\n return severities.readOnlyMutation;\n case 'LINT.UNINDEXED_PREDICATE':\n return severities.unindexedPredicate;\n default:\n return undefined;\n }\n}\n\n/**\n * AST-first lint middleware for SQL plans. When `plan.ast` is a SQL QueryAst, inspects\n * the AST structurally. When `plan.ast` is missing, falls back to raw heuristic\n * guardrails or skips linting depending on `fallbackWhenAstMissing`.\n *\n * Rules (AST-based):\n * - DELETE without WHERE: blocks execution (configurable severity, default error)\n * - UPDATE without WHERE: blocks execution (configurable severity, default error)\n * - Unbounded SELECT: warn/error (severity from noLimit)\n * - SELECT * intent: warn/error (severity from selectStar)\n *\n * Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic\n * SQL parsing; `'skip'` skips all lints. Default is `'raw'`.\n */\nexport function lints(options?: LintsOptions): SqlMiddleware {\n const fallback = options?.fallbackWhenAstMissing ?? 'raw';\n\n return Object.freeze({\n name: 'lints',\n familyId: 'sql' as const,\n\n async beforeExecute(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n const findings: LintFinding[] = [];\n if (isQueryAst(plan.ast)) {\n findings.push(...evaluateAstLints(plan.ast));\n // Raw-SQL ASTs opt out of structural AST lints (no LIMIT /\n // WHERE shape to inspect) but the embedded SQL text still\n // wants the raw-heuristic guardrails. Without this the lint\n // middleware would silently disable both for raw plans.\n if (plan.ast.kind === 'raw-sql') {\n findings.push(...evaluateRawGuardrails(plan).lints);\n }\n } else if (fallback !== 'skip') {\n findings.push(...evaluateRawGuardrails(plan).lints);\n }\n\n for (const lint of findings) {\n const configuredSeverity = getConfiguredSeverity(lint.code, options);\n const effectiveSeverity = configuredSeverity ?? lint.severity;\n\n if (effectiveSeverity === 'error') {\n throw runtimeError(lint.code, lint.message, lint.details);\n }\n if (effectiveSeverity === 'warn') {\n ctx.log.warn({\n code: lint.code,\n message: lint.message,\n details: lint.details,\n });\n }\n }\n },\n });\n}\n","import type { Contract, ExecutionMutationDefaultValue } from '@prisma-next/contract/types';\nimport type { AnyCodecDescriptor, CodecDescriptor } from '@prisma-next/framework-components/codec';\nimport type { ComponentDescriptor } from '@prisma-next/framework-components/components';\nimport { checkContractComponentRequirements } from '@prisma-next/framework-components/components';\nimport {\n createExecutionStack,\n type ExecutionStack,\n type RuntimeAdapterDescriptor,\n type RuntimeAdapterInstance,\n type RuntimeDriverDescriptor,\n type RuntimeDriverInstance,\n type RuntimeExtensionDescriptor,\n type RuntimeExtensionInstance,\n type RuntimeTargetDescriptor,\n type RuntimeTargetInstance,\n} from '@prisma-next/framework-components/execution';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport {\n createSqlOperationRegistry,\n type SqlOperationDescriptors,\n} from '@prisma-next/sql-operations';\nimport type {\n Adapter,\n AnyQueryAst,\n Codec,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecInstanceContext,\n SqlDriver,\n} from '@prisma-next/sql-relational-core/ast';\nimport { buildCodecDescriptorRegistry } from '@prisma-next/sql-relational-core/codec-descriptor-registry';\nimport type {\n AppliedMutationDefault,\n CodecDescriptorRegistry,\n ExecutionContext,\n MutationDefaultsOptions,\n TypeHelperRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Runtime parameterized codec descriptor.\n *\n * The unified `CodecDescriptor<P>` shape applied to parameterized codecs — `paramsSchema: StandardSchemaV1<P>` for JSON-boundary validation, `factory: (P) => (CodecInstanceContext) => Codec` for the curried higher-order codec. The factory is called once per `storage.types` instance (or once per inline-`typeParams` column); per-instance state lives in the closure.\n *\n * Codec-registry-unification spec § Decision.\n */\nexport type RuntimeParameterizedCodecDescriptor<P = Record<string, unknown>> = CodecDescriptor<P>;\n\n/**\n * Contributor protocol for SQL components (target, adapter, extension pack). The unified `codecs:` slot returns the full {@link CodecDescriptor} list — non-parameterized and parameterized descriptors live side-by-side in the same array. The framework dispatches every codec id through the unified descriptor map without branching on parameterization.\n */\nexport interface SqlStaticContributions {\n readonly codecs: () => ReadonlyArray<AnyCodecDescriptor>;\n readonly queryOperations?: () => SqlOperationDescriptors;\n readonly mutationDefaultGenerators?: () => ReadonlyArray<RuntimeMutationDefaultGenerator>;\n}\n\n/**\n * Scope across which a generator's value is constant.\n *\n * - `'field'` — one value per defaulting site (one column, one row). Cache strategy: no cache; call per defaulting site. Right for per-row identifiers (UUIDs, CUIDs, ULIDs, nanoid, ksuid).\n * - `'row'` — one value across all defaulting sites of one row of one operation. Cache strategy: per-call cache keyed by `generatorId`. Right for correlation ids stamped into multiple columns of one row.\n * - `'query'` — one value across all rows and columns of one ORM operation. Cache strategy: caller-provided cache keyed by `generatorId`. Right for `timestampNow` (a single timestamp per bulk insert/update).\n */\nexport type GeneratorStability = 'field' | 'row' | 'query';\n\nexport interface RuntimeMutationDefaultGenerator {\n readonly id: string;\n readonly generate: (params?: Record<string, unknown>) => unknown;\n /**\n * Scope across which the generator's value is constant. The framework derives the cache strategy from this declaration; generator authors never need to know about cache keys. See `GeneratorStability` for the per-value semantics.\n */\n readonly stability: GeneratorStability;\n}\n\nexport interface SqlRuntimeTargetDescriptor<\n TTargetId extends string = string,\n TTargetInstance extends RuntimeTargetInstance<'sql', TTargetId> = RuntimeTargetInstance<\n 'sql',\n TTargetId\n >,\n> extends RuntimeTargetDescriptor<'sql', TTargetId, TTargetInstance>,\n SqlStaticContributions {}\n\nexport interface SqlRuntimeAdapterDescriptor<\n TTargetId extends string = string,\n TAdapterInstance extends RuntimeAdapterInstance<\n 'sql',\n TTargetId\n > = SqlRuntimeAdapterInstance<TTargetId>,\n> extends RuntimeAdapterDescriptor<'sql', TTargetId, TAdapterInstance>,\n SqlStaticContributions {}\n\nexport interface SqlRuntimeExtensionDescriptor<TTargetId extends string = string>\n extends RuntimeExtensionDescriptor<'sql', TTargetId, SqlRuntimeExtensionInstance<TTargetId>>,\n SqlStaticContributions {\n create(): SqlRuntimeExtensionInstance<TTargetId>;\n}\n\nexport interface SqlExecutionStack<TTargetId extends string = string> {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId>;\n readonly extensionPacks: readonly SqlRuntimeExtensionDescriptor<TTargetId>[];\n}\n\nexport type SqlExecutionStackWithDriver<TTargetId extends string = string> = Omit<\n ExecutionStack<\n 'sql',\n TTargetId,\n SqlRuntimeAdapterInstance<TTargetId>,\n SqlRuntimeDriverInstance<TTargetId>,\n SqlRuntimeExtensionInstance<TTargetId>\n >,\n 'target' | 'adapter' | 'driver' | 'extensionPacks'\n> & {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId, SqlRuntimeAdapterInstance<TTargetId>>;\n readonly driver:\n | RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>\n | undefined;\n readonly extensionPacks: readonly SqlRuntimeExtensionDescriptor<TTargetId>[];\n};\n\nexport interface SqlRuntimeExtensionInstance<TTargetId extends string>\n extends RuntimeExtensionInstance<'sql', TTargetId> {}\n\nexport type SqlRuntimeAdapterInstance<TTargetId extends string = string> = RuntimeAdapterInstance<\n 'sql',\n TTargetId\n> &\n Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n\n/**\n * NOTE: Binding type is intentionally erased to unknown at this shared runtime layer. Target clients (for example `postgres()`) validate and construct the concrete binding before calling `driver.connect(binding)`, which keeps runtime behavior safe today. A future follow-up can preserve TBinding through stack/context generics end-to-end.\n */\nexport type SqlRuntimeDriverInstance<TTargetId extends string = string> = RuntimeDriverInstance<\n 'sql',\n TTargetId\n> &\n SqlDriver<unknown>;\n\nexport function createSqlExecutionStack<TTargetId extends string>(options: {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId>;\n readonly driver?:\n | RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>\n | undefined;\n readonly extensionPacks?: readonly SqlRuntimeExtensionDescriptor<TTargetId>[] | undefined;\n}): SqlExecutionStackWithDriver<TTargetId> {\n return createExecutionStack({\n target: options.target,\n adapter: options.adapter,\n driver: options.driver,\n extensionPacks: options.extensionPacks,\n });\n}\n\nexport type { ExecutionContext, TypeHelperRegistry };\n\nexport function assertExecutionStackContractRequirements(\n contract: Contract<SqlStorage>,\n stack: SqlExecutionStack,\n): void {\n const providedComponentIds = new Set<string>([\n stack.target.id,\n stack.adapter.id,\n ...stack.extensionPacks.map((pack) => pack.id),\n ]);\n\n const result = checkContractComponentRequirements({\n contract,\n expectedTargetFamily: 'sql',\n expectedTargetId: stack.target.targetId,\n providedComponentIds,\n });\n\n if (result.familyMismatch) {\n throw runtimeError(\n 'RUNTIME.CONTRACT_FAMILY_MISMATCH',\n `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`,\n {\n actual: result.familyMismatch.actual,\n expected: result.familyMismatch.expected,\n },\n );\n }\n\n if (result.targetMismatch) {\n throw runtimeError(\n 'RUNTIME.CONTRACT_TARGET_MISMATCH',\n `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`,\n {\n actual: result.targetMismatch.actual,\n expected: result.targetMismatch.expected,\n },\n );\n }\n\n if (result.missingExtensionPackIds.length > 0) {\n const packIds = result.missingExtensionPackIds;\n const packList = packIds.map((id) => `'${id}'`).join(', ');\n throw runtimeError(\n 'RUNTIME.MISSING_EXTENSION_PACK',\n `Contract requires extension pack(s) ${packList}, but runtime descriptors do not provide matching component(s).`,\n { packIds },\n );\n }\n}\n\nfunction validateTypeParams(\n typeParams: Record<string, unknown>,\n descriptor: RuntimeParameterizedCodecDescriptor,\n context: { typeName?: string; tableName?: string; columnName?: string },\n): Record<string, unknown> {\n const result = descriptor.paramsSchema['~standard'].validate(typeParams);\n if (result instanceof Promise) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `paramsSchema for codec '${descriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,\n { ...context, codecId: descriptor.codecId, typeParams },\n );\n }\n if (result.issues) {\n const messages = result.issues.map((issue) => issue.message).join('; ');\n const locationInfo = context.typeName\n ? `type '${context.typeName}'`\n : `column '${context.tableName}.${context.columnName}'`;\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Invalid typeParams for ${locationInfo} (codecId: ${descriptor.codecId}): ${messages}`,\n { ...context, codecId: descriptor.codecId, typeParams },\n );\n }\n return result.value as Record<string, unknown>;\n}\n\n/**\n * Collect every {@link CodecDescriptor} contributed by the SQL stack and partition into \"parameterized\" vs \"non-parameterized\" via the descriptor's own {@link CodecDescriptorImpl.isParameterized} getter. The getter is the canonical discriminator — a `paramsSchema` identity check would misroute any descriptor that doesn't reuse the exact `voidParamsSchema` singleton (e.g. a non-parameterized codec authoring its own no-op schema).\n *\n * The unified descriptor list collapses the legacy split (a separate slot used to register parameterized codecs) — every codec id resolves through the same map (codec-registry-unification spec § Decision).\n */\nfunction collectCodecDescriptors(contributors: ReadonlyArray<SqlStaticContributions>): {\n readonly all: ReadonlyArray<AnyCodecDescriptor>;\n readonly parameterized: Map<string, RuntimeParameterizedCodecDescriptor>;\n} {\n const all: AnyCodecDescriptor[] = [];\n const parameterized = new Map<string, RuntimeParameterizedCodecDescriptor>();\n const seen = new Set<string>();\n\n for (const contributor of contributors) {\n for (const descriptor of contributor.codecs()) {\n if (seen.has(descriptor.codecId)) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_CODEC',\n `Duplicate codec descriptor for codecId '${descriptor.codecId}'.`,\n { codecId: descriptor.codecId },\n );\n }\n seen.add(descriptor.codecId);\n all.push(descriptor);\n\n if (descriptor.isParameterized) {\n // Cast widens the descriptor's heterogeneous `P` to the runtime alias surface; consumers narrow per codec id at the dispatch site, where the descriptor's own `paramsSchema` validates JSON-sourced params before the factory ever sees them.\n parameterized.set(\n descriptor.codecId,\n descriptor as unknown as RuntimeParameterizedCodecDescriptor,\n );\n }\n }\n }\n\n return { all, parameterized };\n}\n\nfunction collectTypeRefSites(\n storage: SqlStorage,\n): Map<string, Array<{ readonly table: string; readonly column: string }>> {\n const sites = new Map<string, Array<{ readonly table: string; readonly column: string }>>();\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (typeof column.typeRef !== 'string') continue;\n const list = sites.get(column.typeRef);\n const entry = { table: tableName, column: columnName };\n if (list) {\n list.push(entry);\n } else {\n sites.set(column.typeRef, [entry]);\n }\n }\n }\n return sites;\n}\n\nfunction initializeTypeHelpers(\n storage: SqlStorage,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): TypeHelperRegistry {\n const helpers: TypeHelperRegistry = {};\n const storageTypes = storage.types;\n\n if (!storageTypes) {\n return helpers;\n }\n\n const typeRefSites = collectTypeRefSites(storage);\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes)) {\n const descriptor = codecDescriptors.get(typeInstance.codecId);\n\n if (!descriptor) {\n // No parameterized descriptor for this codec id — store the raw type instance for callers that need typeParams metadata.\n helpers[typeName] = typeInstance;\n continue;\n }\n\n const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, {\n typeName,\n });\n\n const usedAt = typeRefSites.get(typeName) ?? [];\n const ctx: SqlCodecInstanceContext = { name: typeName, usedAt };\n helpers[typeName] = descriptor.factory(validatedParams)(ctx);\n }\n\n return helpers;\n}\n\nfunction validateColumnTypeParams(\n storage: SqlStorage,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): void {\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeParams) {\n const descriptor = codecDescriptors.get(column.codecId);\n if (descriptor) {\n validateTypeParams(column.typeParams, descriptor, { tableName, columnName });\n }\n }\n }\n }\n}\n\nfunction isResolvedCodec(candidate: unknown): candidate is Codec {\n return (\n candidate !== null &&\n typeof candidate === 'object' &&\n 'id' in candidate &&\n 'decode' in candidate\n );\n}\n\n/**\n * Walk the contract's `storage.tables[].columns[]` and resolve each column to a `Codec` through the unified descriptor map. Per-instance behavior:\n *\n * - **typeRef columns**: reuse the resolved codec materialized once by `initializeTypeHelpers` for the `storage.types` entry. Multiple columns sharing one typeRef share one codec instance.\n * - **inline-typeParams columns**: call `descriptor.factory(typeParams) (ctx)` once per column (per-column anonymous instance).\n * - **non-parameterized columns**: call `descriptor.factory()(ctx)` once. The synthesized descriptor's factory is constant — every call returns the same shared codec instance — so columns sharing a non-parameterized codec id share one resolved codec without explicit caching.\n *\n * Codec-registry-unification spec § AC-4: every column resolves through one descriptor map without branching on parameterization. JSON-Schema validation, when required, lives inside the resolved codec's `decode` body (see `arktype-json`'s `ArktypeJsonCodecClass`); the framework no longer maintains a parallel validator registry.\n */\nfunction buildContractCodecRegistry(\n contract: Contract<SqlStorage>,\n codecDescriptors: CodecDescriptorRegistry,\n types: TypeHelperRegistry,\n parameterizedDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): ContractCodecRegistry {\n const byColumn = new Map<string, Codec>();\n const byCodecId = new Map<string, Codec>();\n // Codec ids whose `byCodecId` entry is ambiguous — multiple distinct resolved instances landed under the same parameterized codec id (e.g. `Vector<1024>` and `Vector<1536>` both registering under `pg/vector@1`). The refs-less `forCodecId` fallback rejects these ids so a DSL-param without a column ref cannot silently bind to the wrong instance. The validator pass enforces refs on every parameterized `ParamRef`, so this\n // branch is reachable only as a defensive guard for non-parameterized columns whose `byCodecId` entry is unique by construction.\n const ambiguousCodecIds = new Set<string>();\n\n // Pre-populate `byCodecId` with non-parameterized descriptor instances. Refs-less encode/decode call sites (computed projections without a column ref, transient builder ParamRefs) resolve through `forCodecId(id)` and need a representative instance for codec ids that no contract column declares. Non-parameterized descriptors' factories are constant — every call yields the same shared codec — so a single materialization\n // is correct.\n for (const descriptor of codecDescriptors.values()) {\n if (descriptor.isParameterized) continue;\n const ctx: SqlCodecInstanceContext = {\n name: `<shared:${descriptor.codecId}>`,\n usedAt: [],\n };\n const voidFactory = descriptor.factory as unknown as (\n params: undefined,\n ) => (ctx: SqlCodecInstanceContext) => Codec;\n byCodecId.set(descriptor.codecId, voidFactory(undefined)(ctx));\n }\n\n // Representative instances for parameterized descriptors whose factory tolerates `factory(undefined)` (e.g. pgvector — the factory ignores its params and returns the same shared codec). Used as the last-resort fallback in `forCodecId` for refs-less call sites whose codec id has no contract column the walk could resolve through (e.g. `cosineSimilarity(col, [literal])` builds an inline `ParamRef` without column refs).\n // Stored separately so column-bound walk results don't trip the ambiguity check, and consulted only when `byCodecId` has no column-bound entry. Descriptors whose factory needs real params (arktype-json) raise and are skipped — the per-column dispatch path materializes those lazily when refs are populated.\n const parameterizedRepresentatives = new Map<string, Codec>();\n for (const descriptor of codecDescriptors.values()) {\n if (!descriptor.isParameterized) continue;\n const ctx: SqlCodecInstanceContext = {\n name: `<shared:${descriptor.codecId}>`,\n usedAt: [],\n };\n // Call `factory` *as a method on the descriptor* — `descriptor.factory(undefined)` — rather than detaching it into a local. Several descriptors implement `factory` as a class method whose body returns an arrow that captures `this` (`return () => new SomeCodec(this);`), and detaching loses that binding so the codec ends up with an `undefined` descriptor and `codec.id` throws.\n const factory = descriptor.factory.bind(descriptor) as unknown as (\n params: unknown,\n ) => (ctx: SqlCodecInstanceContext) => Codec;\n try {\n parameterizedRepresentatives.set(descriptor.codecId, factory(undefined)(ctx));\n } catch {\n // Parameterized descriptor whose factory requires real params; refs-less fallback for this codec id is unavailable.\n }\n }\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n const columnKey = `${tableName}.${columnName}`;\n const descriptor = codecDescriptors.descriptorFor(column.codecId);\n\n let resolvedCodec: Codec | undefined;\n\n if (descriptor) {\n const isParameterized = parameterizedDescriptors.has(column.codecId);\n\n if (column.typeRef) {\n // The named instance was already materialized once by `initializeTypeHelpers`; reuse it so multiple columns sharing the same typeRef share one codec instance (and any per-instance helper state on it).\n const helper = types[column.typeRef];\n if (isResolvedCodec(helper)) {\n resolvedCodec = helper;\n }\n } else if (column.typeParams && isParameterized) {\n const parameterizedDescriptor = parameterizedDescriptors.get(column.codecId);\n if (parameterizedDescriptor) {\n const validatedParams = validateTypeParams(column.typeParams, parameterizedDescriptor, {\n tableName,\n columnName,\n });\n const ctx: SqlCodecInstanceContext = {\n name: `<col:${tableName}.${columnName}>`,\n usedAt: [{ table: tableName, column: columnName }],\n };\n resolvedCodec = parameterizedDescriptor.factory(validatedParams)(ctx);\n }\n } else if (!isParameterized) {\n // Non-parameterized column: materialize a fresh codec instance per `forColumn(table, column)` entry with a column-specific `SqlCodecInstanceContext`. The pre-populated `byCodecId` representative (built with the synthetic `<shared:codecId>` context and empty `usedAt`) is reserved for `forCodecId()` refs-less fallbacks; reusing it for column-bound dispatch would erase per-column diagnostics for any descriptor whose factory reads `CodecInstanceContext`.\n const ctx: SqlCodecInstanceContext = {\n name: `<col:${tableName}.${columnName}>`,\n usedAt: [{ table: tableName, column: columnName }],\n };\n // The descriptor's `P` is `void` for non-parameterized codecs; the runtime's `void` value is `undefined`. The cast narrows the descriptor's family-agnostic `CodecInstanceContext` slot to the SQL `SqlCodecInstanceContext` we pass at this call site — function-argument contravariance makes the narrow safe.\n // `bind` preserves the `this`-on-descriptor invariant — several descriptors implement `factory` as a class method whose body returns an arrow that captures `this`; detaching loses the binding and produces a codec whose `descriptor` is `undefined`.\n const voidFactory = descriptor.factory.bind(descriptor) as unknown as (\n params: undefined,\n ) => (ctx: SqlCodecInstanceContext) => Codec;\n resolvedCodec = voidFactory(undefined)(ctx);\n }\n // else: parameterized codec id with no typeRef and no typeParams — this is the legitimate \"undimensioned\" form for codecs that ship a no-params column variant alongside a parameterized one (e.g. pgvector's `vectorColumn` vs. `vector(N)`). Leave `resolvedCodec` undefined; encode/decode for this column flows through `forCodecId`. The fallback works for these cases because their wire format is params-independent (vector\n // formats `[v1,v2,...]` regardless of declared length).\n }\n\n if (resolvedCodec) {\n byColumn.set(columnKey, resolvedCodec);\n const existing = byCodecId.get(column.codecId);\n if (existing === undefined) {\n byCodecId.set(column.codecId, resolvedCodec);\n } else if (existing !== resolvedCodec && parameterizedDescriptors.has(column.codecId)) {\n ambiguousCodecIds.add(column.codecId);\n }\n }\n }\n }\n\n const registry: ContractCodecRegistry = {\n forColumn(table, column) {\n return byColumn.get(`${table}.${column}`);\n },\n forCodecId(codecId) {\n // Codec-id-only fallback for refs-less sites. The validator pass (`validateParamRefRefs`) enforces refs on every parameterized `ParamRef` before encode, so this path is only legitimately reachable for non-parameterized codec ids. The map is pre-populated with every non-parameterized descriptor's canonical instance and overlaid with column-resolved instances from the contract walk; parameterized codec ids without a\n // typeRef/typeParams-bound column never reach this map.\n //\n // Reject ambiguous parameterized fallbacks: if the contract walk resolved more than one distinct codec instance under this id (e.g. multiple vector dimensions, multiple arktype-json schemas), the codec-id-keyed lookup cannot honor the call site — fail fast rather than bind to whichever instance happened to land first.\n if (ambiguousCodecIds.has(codecId)) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Codec '${codecId}' resolves to multiple parameterized instances; column-aware dispatch is required.`,\n { codecId },\n );\n }\n return byCodecId.get(codecId) ?? parameterizedRepresentatives.get(codecId);\n },\n };\n\n return registry;\n}\n\nfunction assertMutationDefaultGeneratorsAvailable(\n contract: Contract<SqlStorage>,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n): void {\n const defaults = contract.execution?.mutations.defaults ?? [];\n if (defaults.length === 0) return;\n\n const missing = new Set<string>();\n for (const mutationDefault of defaults) {\n for (const phase of [mutationDefault.onCreate, mutationDefault.onUpdate]) {\n if (!phase) continue;\n if (phase.kind === 'generator' && !generatorRegistry.has(phase.id)) {\n missing.add(phase.id);\n }\n }\n }\n\n if (missing.size === 0) return;\n\n const ids = Array.from(missing);\n const idList = ids.map((id) => `'${id}'`).join(', ');\n throw runtimeError(\n 'RUNTIME.MISSING_MUTATION_DEFAULT_GENERATOR',\n `Contract requires mutation default generator(s) ${idList}, but no runtime component provides them.`,\n { ids },\n );\n}\n\nfunction collectMutationDefaultGenerators(\n contributors: ReadonlyArray<SqlStaticContributions & { readonly id: string }>,\n): ReadonlyMap<string, RuntimeMutationDefaultGenerator> {\n const generators = new Map<string, RuntimeMutationDefaultGenerator>();\n const owners = new Map<string, string>();\n\n for (const contributor of contributors) {\n const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];\n for (const generator of nextGenerators) {\n const existingOwner = owners.get(generator.id);\n if (existingOwner !== undefined) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR',\n `Duplicate mutation default generator '${generator.id}'.`,\n {\n id: generator.id,\n existingOwner,\n incomingOwner: contributor.id,\n },\n );\n }\n generators.set(generator.id, generator);\n owners.set(generator.id, contributor.id);\n }\n }\n\n return generators;\n}\n\nfunction computeExecutionDefaultValue(\n spec: ExecutionMutationDefaultValue,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n): unknown {\n switch (spec.kind) {\n case 'generator': {\n const generator = generatorRegistry.get(spec.id);\n if (!generator) {\n throw runtimeError(\n 'RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING',\n `Contract references mutation default generator '${spec.id}' but no runtime component provides it.`,\n {\n id: spec.id,\n },\n );\n }\n // nosemgrep: javascript.express.security.express-wkhtml-injection.express-wkhtmltoimage-injection\n return generator.generate(spec.params);\n }\n }\n}\n\nfunction applyMutationDefaults(\n contract: Contract<SqlStorage>,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n options: MutationDefaultsOptions,\n): ReadonlyArray<AppliedMutationDefault> {\n const defaults = contract.execution?.mutations.defaults ?? [];\n if (defaults.length === 0) {\n return [];\n }\n\n const isEmptyUpdate = options.op === 'update' && Object.keys(options.values).length === 0;\n\n const applied: AppliedMutationDefault[] = [];\n const appliedColumns = new Set<string>();\n // Fresh per-call cache for `stability: 'row'` generators — they share across columns of a single row but regenerate on the next call.\n const rowCache = new Map<string, unknown>();\n\n for (const mutationDefault of defaults) {\n if (mutationDefault.ref.table !== options.table) {\n continue;\n }\n\n const defaultSpec =\n options.op === 'create' ? mutationDefault.onCreate : mutationDefault.onUpdate;\n if (!defaultSpec) {\n continue;\n }\n\n // RD2: empty update payloads skip onUpdate defaults — no write means no `@updatedAt` advance.\n if (isEmptyUpdate) {\n continue;\n }\n\n const columnName = mutationDefault.ref.column;\n if (Object.hasOwn(options.values, columnName) || appliedColumns.has(columnName)) {\n continue;\n }\n\n applied.push({\n column: columnName,\n value: resolveScopedValue(\n defaultSpec,\n generatorRegistry,\n rowCache,\n options.defaultValueCache,\n ),\n });\n appliedColumns.add(columnName);\n }\n\n return applied;\n}\n\nfunction resolveScopedValue(\n spec: ExecutionMutationDefaultValue,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n rowCache: Map<string, unknown>,\n queryCache: Map<string, unknown> | undefined,\n): unknown {\n if (spec.kind !== 'generator') {\n return computeExecutionDefaultValue(spec, generatorRegistry);\n }\n const generator = generatorRegistry.get(spec.id);\n const cache = scopedCache(generator?.stability, rowCache, queryCache);\n if (!cache) {\n return computeExecutionDefaultValue(spec, generatorRegistry);\n }\n if (cache.has(spec.id)) {\n return cache.get(spec.id);\n }\n const value = computeExecutionDefaultValue(spec, generatorRegistry);\n cache.set(spec.id, value);\n return value;\n}\n\nfunction scopedCache(\n stability: GeneratorStability | undefined,\n rowCache: Map<string, unknown>,\n queryCache: Map<string, unknown> | undefined,\n): Map<string, unknown> | undefined {\n switch (stability) {\n case 'row':\n return rowCache;\n case 'query':\n return queryCache;\n default:\n return undefined;\n }\n}\n\nexport function createExecutionContext<\n TContract extends Contract<SqlStorage> = Contract<SqlStorage>,\n TTargetId extends string = string,\n>(options: {\n readonly contract: TContract;\n readonly stack: SqlExecutionStack<TTargetId>;\n}): ExecutionContext<TContract> {\n const { contract, stack } = options;\n\n assertExecutionStackContractRequirements(contract, stack);\n\n const contributors: Array<SqlStaticContributions & ComponentDescriptor<string>> = [\n stack.target,\n stack.adapter,\n ...stack.extensionPacks,\n ];\n\n const { all: allCodecDescriptors, parameterized: parameterizedCodecDescriptors } =\n collectCodecDescriptors(contributors);\n\n const queryOperationRegistry = createSqlOperationRegistry();\n for (const contributor of contributors) {\n const ops = contributor.queryOperations?.() ?? {};\n for (const [name, op] of Object.entries(ops)) {\n queryOperationRegistry.register(name, op);\n }\n }\n\n const codecDescriptors = buildCodecDescriptorRegistry(allCodecDescriptors);\n const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);\n assertMutationDefaultGeneratorsAvailable(contract, mutationDefaultGeneratorRegistry);\n\n if (parameterizedCodecDescriptors.size > 0) {\n validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);\n }\n\n const types = initializeTypeHelpers(contract.storage, parameterizedCodecDescriptors);\n\n const contractCodecs = buildContractCodecRegistry(\n contract,\n codecDescriptors,\n types,\n parameterizedCodecDescriptors,\n );\n\n return {\n contract,\n contractCodecs,\n codecDescriptors,\n queryOperations: queryOperationRegistry,\n types,\n applyMutationDefaults: (options) =>\n applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options),\n };\n}\n","import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport type { MarkerStatement } from '@prisma-next/sql-relational-core/ast';\n\nexport { APP_SPACE_ID };\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport interface WriteMarkerInput {\n /**\n * Logical space identifier for this marker row. Required at every\n * call site so the type system surfaces every place that needs to\n * thread the value (rather than letting an `?? APP_SPACE_ID`\n * fall-through silently collapse multi-space markers onto the\n * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}\n * (`'app'`); per-extension callers pass the extension's space id.\n */\n readonly space: string;\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number;\n readonly appTag?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Applied-invariants set on the marker.\n *\n * - `undefined` → existing column left untouched. Sign and\n * verify-database paths use this; they don't accumulate invariants.\n * - explicit value (including `[]`) → column overwritten with\n * exactly that value.\n */\n readonly invariants?: readonly string[];\n}\n\nexport const ensureSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\n/**\n * Schema for `prisma_contract.marker`. The `space text` primary key\n * supports one row per loaded contract space (`'app'`,\n * `'<extension-id>'`, …); brand-new databases create this shape\n * directly. Pre-1.0 single-row markers (no `space` column) are not\n * auto-migrated — the target-specific migration runner detects the\n * legacy shape at boot and surfaces a structured `LEGACY_MARKER_SHAPE`\n * failure pointing the operator at re-running `dbInit`.\n *\n * @see specs/framework-mechanism.spec.md § 2.\n */\nexport const ensureTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n space text not null primary key default '${APP_SPACE_ID}',\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}',\n invariants text[] not null default '{}'\n )`,\n params: [],\n};\n\nexport function readContractMarker(space: string): MarkerStatement {\n return {\n sql: `select\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta,\n invariants\n from prisma_contract.marker\n where space = $1`,\n params: [space],\n };\n}\n\nexport interface WriteContractMarkerStatements {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n}\n\n/**\n * Variable columns that participate in INSERT/UPDATE alongside the\n * always-on `space = $1` and `updated_at = now()`. Each column declares\n * its name, optional cast type, and parameter value; the placeholder\n * (`$N`) is computed positionally below — adding or reordering a\n * column doesn't desync indices. `invariants` only appears when the\n * caller supplies it — see `WriteMarkerInput.invariants`.\n */\nfunction markerColumns(\n input: WriteMarkerInput,\n): ReadonlyArray<{ readonly name: string; readonly type?: string; readonly param: unknown }> {\n return [\n { name: 'core_hash', param: input.storageHash },\n { name: 'profile_hash', param: input.profileHash },\n { name: 'contract_json', type: 'jsonb', param: input.contractJson ?? null },\n { name: 'canonical_version', param: input.canonicalVersion ?? null },\n { name: 'app_tag', param: input.appTag ?? null },\n { name: 'meta', type: 'jsonb', param: JSON.stringify(input.meta ?? {}) },\n ...(input.invariants !== undefined\n ? [{ name: 'invariants' as const, type: 'text[]' as const, param: input.invariants }]\n : []),\n ];\n}\n\nexport function writeContractMarker(input: WriteMarkerInput): WriteContractMarkerStatements {\n const cols = markerColumns(input);\n // $1 is reserved for `space`; subsequent positions follow the order of cols.\n const placed = cols.map((c, i) => ({\n name: c.name,\n expr: c.type ? `$${i + 2}::${c.type}` : `$${i + 2}`,\n param: c.param,\n }));\n const params: readonly unknown[] = [input.space, ...placed.map((c) => c.param)];\n\n // `updated_at = now()` is a SQL literal with no parameter slot, so it\n // sits outside `placed` and is appended directly to each statement.\n const insertColumns = ['space', ...placed.map((c) => c.name), 'updated_at'].join(', ');\n const insertValues = ['$1', ...placed.map((c) => c.expr), 'now()'].join(', ');\n const setClauses = [...placed.map((c) => `${c.name} = ${c.expr}`), 'updated_at = now()'].join(\n ', ',\n );\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (${insertColumns}) values (${insertValues})`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set ${setClauses} where space = $1`,\n params,\n },\n };\n}\n","import type { AnyFromSource, AnyQueryAst } from '@prisma-next/sql-relational-core/ast';\n\n/**\n * Build a map from query-local table aliases to their underlying source table names.\n *\n * Self-joins like `db.sql.post.as('p1').innerJoin(db.sql.post.as('p2'), …)` produce `ColumnRef`s whose `table` is the alias (`p1`, `p2`) — the SQL renderer needs the alias for `SELECT p1.id, …`. Codec dispatch keys `byColumn` by the underlying source table, so aliases must be resolved back to the source name for `forColumn(...)` to hit. Tables that already use their canonical name (no alias) are also entered so a single\n * lookup works for both shapes.\n */\nfunction buildAliasMap(ast: AnyQueryAst): ReadonlyMap<string, string> {\n const aliases = new Map<string, string>();\n const recordSource = (source: AnyFromSource): void => {\n if (source.kind === 'table-source') {\n const key = source.alias ?? source.name;\n aliases.set(key, source.name);\n } else {\n aliases.set(source.alias, source.alias);\n }\n };\n if (ast.kind === 'select') {\n recordSource(ast.from);\n for (const join of ast.joins ?? []) {\n recordSource(join.source);\n }\n } else if (ast.kind === 'raw-sql') {\n // Raw-SQL ASTs do not bind a single primary table — alias resolution\n // is driven by inline `IdentifierRef`s the caller embedded directly.\n } else {\n recordSource(ast.table);\n }\n return aliases;\n}\n\nexport function makeAliasResolver(ast: AnyQueryAst | undefined): (alias: string) => string {\n if (!ast) return (alias) => alias;\n const map = buildAliasMap(ast);\n return (alias) => map.get(alias) ?? alias;\n}\n","import {\n checkAborted,\n isRuntimeError,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport type {\n AnyQueryAst,\n Codec,\n ContractCodecRegistry,\n ProjectionItem,\n SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { makeAliasResolver } from './alias-resolver';\n\ntype ColumnRef = { table: string; column: string };\n\ninterface DecodeContext {\n readonly aliases: ReadonlyArray<string> | undefined;\n readonly codecs: ReadonlyMap<string, Codec>;\n readonly columnRefs: ReadonlyMap<string, ColumnRef>;\n readonly includeAliases: ReadonlySet<string>;\n}\n\nconst WIRE_PREVIEW_LIMIT = 100;\nconst EMPTY_INCLUDE_ALIASES: ReadonlySet<string> = new Set<string>();\n\nfunction isAstBackedPlan(\n plan: SqlExecutionPlan,\n): plan is SqlExecutionPlan & { readonly ast: AnyQueryAst } {\n return plan.ast !== undefined;\n}\n\nfunction projectionListFromAst(ast: AnyQueryAst): ReadonlyArray<ProjectionItem> | undefined {\n if (ast.kind === 'select') {\n return ast.projection;\n }\n if (ast.kind === 'raw-sql') {\n return undefined;\n }\n return ast.returning;\n}\n\n/**\n * Resolve the per-cell codec for a projection item.\n *\n * When a `(table, column)` ref is available — either implicit on a `column-ref` expression or carried explicitly via `item.refs` for column-bound non-`column-ref` projections — prefer `contractCodecs.forColumn(table, column)`: that returns the per-instance codec materialized from the descriptor's factory for that column, encoding any per-instance state (typeParams like vector length, schema validators, etc.).\n *\n * The wrong-instance risk for parameterized codecs is closed off structurally:\n *\n * 1. `buildContractCodecRegistry` pre-populates `byCodecId` with one canonical instance per non-parameterized descriptor; parameterized descriptors are intentionally absent. 2. `forCodecId` rejects ambiguous parameterized fallbacks (`ambiguousCodecIds`). 3. The non-ambiguous parameterized case stores the column-correct per-instance codec under `byCodecId`, so the fall-through still resolves to the right instance.\n *\n * The `forCodecId` fallback otherwise covers projections that are *not* column-bound (computed projections, raw SQL aliases) but still carry a `codecId` (ADR 205 stamps every `ProjectionItem` with the producer's codec id).\n *\n * Codec-registry-unification spec § AC-4 / AC-5.\n */\nfunction resolveProjectionCodec(\n item: ProjectionItem,\n contractCodecs: ContractCodecRegistry | undefined,\n aliasResolver: (alias: string) => string,\n): Codec | undefined {\n if (contractCodecs) {\n if (item.expr.kind === 'column-ref') {\n const byColumn = contractCodecs.forColumn(aliasResolver(item.expr.table), item.expr.column);\n // Only honour `byColumn` when its codec id agrees with `item.codecId`. They can legitimately disagree when an `OperationExpr`-shaped projection carries a single inner column-ref but transforms the value's codec (e.g. `cosineDistance(col, x)` projects `pg/float8@1` while the inner column-ref points at a `pg/vector@1` column).\n if (byColumn && (item.codecId === undefined || byColumn.id === item.codecId)) return byColumn;\n } else if (item.refs) {\n const byColumn = contractCodecs.forColumn(aliasResolver(item.refs.table), item.refs.column);\n if (byColumn && (item.codecId === undefined || byColumn.id === item.codecId)) return byColumn;\n }\n }\n if (item.codecId) {\n return contractCodecs?.forCodecId(item.codecId);\n }\n return undefined;\n}\n\nfunction buildDecodeContext(\n plan: SqlExecutionPlan,\n contractCodecs: ContractCodecRegistry | undefined,\n): DecodeContext {\n if (!isAstBackedPlan(plan)) {\n return {\n aliases: undefined,\n codecs: new Map(),\n columnRefs: new Map(),\n includeAliases: EMPTY_INCLUDE_ALIASES,\n };\n }\n\n const projection = projectionListFromAst(plan.ast);\n if (!projection) {\n return {\n aliases: undefined,\n codecs: new Map(),\n columnRefs: new Map(),\n includeAliases: EMPTY_INCLUDE_ALIASES,\n };\n }\n\n const aliases: string[] = [];\n const codecs = new Map<string, Codec>();\n const columnRefs = new Map<string, ColumnRef>();\n const includeAliases = new Set<string>();\n const aliasResolver = makeAliasResolver(plan.ast);\n\n for (const item of projection) {\n aliases.push(item.alias);\n\n const codec = resolveProjectionCodec(item, contractCodecs, aliasResolver);\n if (codec) {\n codecs.set(item.alias, codec);\n }\n\n if (item.expr.kind === 'column-ref') {\n columnRefs.set(item.alias, {\n table: aliasResolver(item.expr.table),\n column: item.expr.column,\n });\n } else if (item.refs) {\n columnRefs.set(item.alias, {\n table: aliasResolver(item.refs.table),\n column: item.refs.column,\n });\n } else if (item.expr.kind === 'subquery' || item.expr.kind === 'json-array-agg') {\n includeAliases.add(item.alias);\n }\n }\n\n return { aliases, codecs, columnRefs, includeAliases };\n}\n\nfunction previewWireValue(wireValue: unknown): string {\n if (typeof wireValue === 'string') {\n return wireValue.length > WIRE_PREVIEW_LIMIT\n ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...`\n : wireValue;\n }\n return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);\n}\n\nfunction wrapDecodeFailure(\n error: unknown,\n alias: string,\n ref: ColumnRef | undefined,\n codec: Codec,\n wireValue: unknown,\n): never {\n const message = error instanceof Error ? error.message : String(error);\n const target = ref ? `${ref.table}.${ref.column}` : alias;\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to decode column ${target} with codec '${codec.id}': ${message}`,\n {\n ...(ref ? { table: ref.table, column: ref.column } : { alias }),\n codec: codec.id,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nfunction wrapIncludeAggregateFailure(error: unknown, alias: string, wireValue: unknown): never {\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to parse JSON array for include alias '${alias}': ${message}`,\n {\n alias,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nfunction decodeIncludeAggregate(alias: string, wireValue: unknown): unknown {\n if (wireValue === null || wireValue === undefined) {\n return [];\n }\n\n try {\n let parsed: unknown;\n if (typeof wireValue === 'string') {\n parsed = JSON.parse(wireValue);\n } else if (Array.isArray(wireValue)) {\n parsed = wireValue;\n } else {\n parsed = JSON.parse(String(wireValue));\n }\n\n if (!Array.isArray(parsed)) {\n throw new Error(`Expected array for include alias '${alias}', got ${typeof parsed}`);\n }\n\n return parsed;\n } catch (error) {\n wrapIncludeAggregateFailure(error, alias, wireValue);\n }\n}\n\n/**\n * Decodes a single field. Single-armed: every cell takes the same path — `codec.decode → await → return plain value` — so sync- and async-authored codecs are indistinguishable to callers. JSON-Schema validation, when required, lives inside the resolved codec's `decode` body (e.g. `arktype-json` validates against its rehydrated schema and throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` from `decode` directly); there is\n * no separate validator-registry pass.\n *\n * The row-level `rowCtx` is repackaged into a per-cell `SqlCodecCallContext` whose `column = { table, name }` is a structural projection of the per-cell `ColumnRef = { table, column }` resolved from the AST-backed `DecodeContext` (the same resolution `wrapDecodeFailure` uses for envelope construction — one resolution per cell, two consumers). Cells the runtime cannot resolve to a single underlying column (aggregate\n * aliases, computed projections without a simple ref) get `column: undefined`, matching the spec contract that the runtime never silently defaults this field.\n */\nasync function decodeField(\n alias: string,\n wireValue: unknown,\n decodeCtx: DecodeContext,\n rowCtx: SqlCodecCallContext,\n): Promise<unknown> {\n if (wireValue === null) {\n return null;\n }\n\n const codec = decodeCtx.codecs.get(alias);\n if (!codec) {\n return wireValue;\n }\n\n const ref = decodeCtx.columnRefs.get(alias);\n\n // Per-cell ctx: the cell-level `column` is a `SqlColumnRef = { table, name }` projection of the resolved `ColumnRef = { table, column }` (same resolution `wrapDecodeFailure` uses below — no double work). Cells the runtime cannot resolve (aggregate aliases, computed projections without a simple ref) drop the `column` field entirely — explicitly cleared so a previously-populated `rowCtx.column` cannot leak through to\n // unrelated cells. Destructuring (rather than `column: undefined`) is required because `SqlCodecCallContext.column` is declared `column?: SqlColumnRef` under `exactOptionalPropertyTypes`.\n let cellCtx: SqlCodecCallContext;\n if (ref) {\n cellCtx = { ...rowCtx, column: { table: ref.table, name: ref.column } };\n } else {\n const { column: _drop, ...rowCtxWithoutColumn } = rowCtx;\n cellCtx = rowCtxWithoutColumn;\n }\n\n try {\n return await codec.decode(wireValue, cellCtx);\n } catch (error) {\n // Codec-authored runtime envelopes (e.g. `RUNTIME.DECODE_FAILED` thrown from inside the codec body, or `RUNTIME.ABORTED` raised via `CodecCallContext.signal` per ADR 207) carry their own per-codec context — wrapping them again would erase that context and coerce the abort intent into a generic decode failure. Pass them through unchanged; only foreign errors get the `wrapDecodeFailure` envelope.\n if (isRuntimeError(error)) {\n throw error;\n }\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n}\n\n/**\n * Decodes a row by dispatching all per-cell codec calls concurrently via `Promise.all`. Each cell follows the single-armed `decodeField` path. Failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column, codec }` (or `{ alias, codec }` when no column ref is resolvable) and the original error attached on `cause`.\n *\n * When `rowCtx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'decode' }`) before any `codec.decode` call is made.\n * - **Mid-flight aborts** race the per-cell `Promise.all` against the signal so the runtime returns promptly even when codec bodies ignore it. In-flight bodies that ignore the signal complete in the background (cooperative cancellation).\n * - Existing `RUNTIME.DECODE_FAILED` envelopes from codec bodies pass through unchanged (no double wrap).\n */\nexport async function decodeRow(\n row: Record<string, unknown>,\n plan: SqlExecutionPlan,\n rowCtx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<Record<string, unknown>> {\n checkAborted(rowCtx, 'decode');\n const signal = rowCtx.signal;\n\n const decodeCtx = buildDecodeContext(plan, contractCodecs);\n\n const aliases = decodeCtx.aliases ?? Object.keys(row);\n\n if (decodeCtx.aliases !== undefined) {\n for (const alias of decodeCtx.aliases) {\n if (!Object.hasOwn(row, alias)) {\n throw runtimeError('RUNTIME.DECODE_FAILED', `Row missing projection alias \"${alias}\"`, {\n alias,\n expectedAliases: decodeCtx.aliases,\n presentKeys: Object.keys(row),\n });\n }\n }\n }\n\n const tasks: Promise<unknown>[] = [];\n const includeIndices: { index: number; alias: string; value: unknown }[] = [];\n\n for (let i = 0; i < aliases.length; i++) {\n const alias = aliases[i] as string;\n const wireValue = row[alias];\n\n if (decodeCtx.includeAliases.has(alias)) {\n includeIndices.push({ index: i, alias, value: wireValue });\n tasks.push(Promise.resolve(undefined));\n continue;\n }\n\n tasks.push(decodeField(alias, wireValue, decodeCtx, rowCtx));\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'decode');\n\n // Include aggregates are decoded synchronously after concurrent codec dispatch settles, so any decode failures upstream propagate first.\n for (const entry of includeIndices) {\n settled[entry.index] = decodeIncludeAggregate(entry.alias, entry.value);\n }\n\n const decoded: Record<string, unknown> = {};\n for (let i = 0; i < aliases.length; i++) {\n decoded[aliases[i] as string] = settled[i];\n }\n return decoded;\n}\n","import {\n checkAborted,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport {\n type Codec,\n type ContractCodecRegistry,\n collectOrderedParamRefs,\n type ParamRefBindingRefs,\n type SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { makeAliasResolver } from './alias-resolver';\n\ninterface ParamMetadata {\n readonly codecId: string | undefined;\n readonly name: string | undefined;\n readonly refs: ParamRefBindingRefs | undefined;\n}\n\nconst NO_METADATA: ParamMetadata = Object.freeze({\n codecId: undefined,\n name: undefined,\n refs: undefined,\n});\n\n/**\n * Resolve the codec for an outgoing param.\n *\n * Column-aware dispatch: when `metadata.refs` is populated by a column-bound construction site, prefer `contractCodecs.forColumn(refs.table, refs.column)` — that returns the per-instance codec the contract walk materialized for the `(table, column)` pair, encoding the column's typeParams (e.g. `vector(1024)` vs. `vector(1536)`).\n *\n * On a column-lookup miss the resolver falls through to `forCodecId`. The wrong-instance risk for parameterized codecs is closed off structurally:\n *\n * 1. `buildContractCodecRegistry` pre-populates `byCodecId` with one canonical instance per non-parameterized descriptor; parameterized descriptors are intentionally absent from this pre-population. 2. `forCodecId` rejects ambiguous parameterized fallbacks (`ambiguousCodecIds`) — if the contract walk resolved more than one distinct instance under a single parameterized id, the call throws rather than binding to\n * whichever landed first. 3. For the non-ambiguous parameterized case (a single column with that id), `byCodecId` stores the column-correct per-instance codec, so the fall-through still resolves to the right instance.\n *\n * Refs-less fallback: ParamRefs constructed outside a column-bound site (literals, transient builder state) carry a non-parameterized `codecId` whose dispatch is ambiguity-free. The validator pass (`validateParamRefRefs`) already enforced refs on every parameterized ParamRef before encode runs.\n */\nfunction resolveParamCodec(\n metadata: ParamMetadata,\n contractCodecs: ContractCodecRegistry | undefined,\n aliasResolver: (alias: string) => string,\n): Codec | undefined {\n if (!metadata.codecId) return undefined;\n if (metadata.refs && contractCodecs) {\n const byColumn = contractCodecs.forColumn(\n aliasResolver(metadata.refs.table),\n metadata.refs.column,\n );\n // Only honour `byColumn` when its codec id agrees with the `ParamRef`'s declared `codecId`. They can legitimately disagree when a heuristic (e.g. the ORM's `refsFromLeft`) lifts column refs out of an `OperationExpr` that changed the codec id — e.g. `cosineDistance(p.embedding, x).lt(1)` carries `refs={post,embedding}` (a vector column) but the comparison side's codec is `pg/float8@1`. Trusting `byColumn` blindly would dispatch the float\n // literal through the vector codec.\n if (byColumn && byColumn.id === metadata.codecId) return byColumn;\n }\n return contractCodecs?.forCodecId(metadata.codecId);\n}\n\nfunction paramLabel(metadata: ParamMetadata, paramIndex: number): string {\n return metadata.name ?? `param[${paramIndex}]`;\n}\n\nfunction wrapEncodeFailure(\n error: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\n codecId: string,\n): never {\n const label = paramLabel(metadata, paramIndex);\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.ENCODE_FAILED',\n `Failed to encode parameter ${label} with codec '${codecId}': ${message}`,\n { label, codec: codecId, paramIndex },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\n/**\n * Encodes a single parameter through its codec. Always awaits codec.encode so a Promise can never leak into the driver, even if a sync-authored codec is lifted to async by the codec factory. Failures are wrapped in `RUNTIME.ENCODE_FAILED` with `{ label, codec, paramIndex }` and the original error attached on `cause`.\n *\n * `ctx` is forwarded verbatim to `codec.encode` so codec authors who opt into the `(value, ctx)` arity see the same `SqlCodecCallContext` the runtime built for the surrounding `runtime.execute()` call. The ctx is always present; its `signal` field may be `undefined`. Encode call sites do not populate `ctx.column` — encode-time column context is the middleware's domain.\n */\nexport async function encodeParam(\n value: unknown,\n paramRef: {\n readonly codecId?: string;\n readonly name?: string;\n readonly refs?: ParamRefBindingRefs;\n },\n paramIndex: number,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<unknown> {\n return encodeParamValue(\n value,\n { codecId: paramRef.codecId, name: paramRef.name, refs: paramRef.refs },\n paramIndex,\n ctx,\n contractCodecs,\n (alias) => alias,\n );\n}\n\nasync function encodeParamValue(\n value: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\n ctx: SqlCodecCallContext,\n contractCodecs: ContractCodecRegistry | undefined,\n aliasResolver: (alias: string) => string,\n): Promise<unknown> {\n if (value === null || value === undefined) {\n return null;\n }\n\n const codec = resolveParamCodec(metadata, contractCodecs, aliasResolver);\n if (!codec) {\n return value;\n }\n\n try {\n return await codec.encode(value, ctx);\n } catch (error) {\n wrapEncodeFailure(error, metadata, paramIndex, codec.id);\n }\n}\n\n/**\n * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-and async-authored codecs share the same path: `codec.encode → await → return`. Param-level failures are wrapped in `RUNTIME.ENCODE_FAILED`.\n *\n * When `ctx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'encode' }`) before any `codec.encode` call is made — codecs can pin this with a per-call counter that stays at zero.\n * - **Mid-flight abort** races the per-param `Promise.all` against `abortable(ctx.signal)`. The runtime returns `RUNTIME.ABORTED` promptly even if codec bodies ignore the signal; the in-flight bodies are abandoned and run to completion in the background (cooperative cancellation, see ADR 204).\n * - Existing `RUNTIME.ENCODE_FAILED` envelopes that surface from a codec body before the runtime observes the abort pass through unchanged (no double wrap).\n */\nexport async function encodeParams(\n plan: SqlExecutionPlan,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<readonly unknown[]> {\n checkAborted(ctx, 'encode');\n const signal = ctx.signal;\n\n if (plan.params.length === 0) {\n return plan.params;\n }\n\n const paramCount = plan.params.length;\n const metadata: ParamMetadata[] = new Array(paramCount).fill(NO_METADATA);\n\n if (plan.ast) {\n const refs = collectOrderedParamRefs(plan.ast);\n for (let i = 0; i < paramCount && i < refs.length; i++) {\n const ref = refs[i];\n if (ref) {\n metadata[i] = { codecId: ref.codecId, name: ref.name, refs: ref.refs };\n }\n }\n }\n\n const aliasResolver = makeAliasResolver(plan.ast);\n\n const tasks: Promise<unknown>[] = new Array(paramCount);\n for (let i = 0; i < paramCount; i++) {\n tasks[i] = encodeParamValue(\n plan.params[i],\n metadata[i] ?? NO_METADATA,\n i,\n ctx,\n contractCodecs,\n aliasResolver,\n );\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'encode');\n return Object.freeze(settled);\n}\n","import type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { canonicalStringify } from '@prisma-next/utils/canonical-stringify';\nimport { hashContent } from '@prisma-next/utils/hash-content';\n\n/**\n * Computes a stable content hash for a lowered SQL execution plan.\n *\n * Internally builds an unambiguous canonical-stringified preimage from\n * three components:\n *\n * 1. `meta.storageHash` — discriminates by schema. A migration changes the\n * storage hash, which invalidates cached entries automatically.\n * 2. `exec.sql` — the raw lowered SQL text. Two queries with different\n * structure produce different keys. Note that we deliberately do **not**\n * use `computeSqlFingerprint` here: that helper strips literals to group\n * executions by statement shape (used by telemetry), which is the\n * opposite of what a content hash needs — we want per-execution\n * discrimination, not per-statement-shape grouping.\n * 3. `exec.params` — the bound parameters. `canonicalStringify` produces a\n * deterministic serialization that is stable across object key\n * insertion order and that distinguishes types JSON would otherwise\n * conflate (e.g. `BigInt(1)` vs `1`).\n *\n * The components are wrapped in an object and canonicalized as a single\n * unit (rather than concatenated with a delimiter) so component\n * boundaries are unambiguous: any character appearing inside `sql` or\n * `storageHash` cannot bleed across components and produce a collision\n * with a different split of the same characters.\n *\n * The canonical string is then piped through `hashContent` to produce a\n * bounded, opaque digest. See `@prisma-next/utils/hash-content` for the\n * rationale.\n *\n * @internal\n */\nexport function computeSqlContentHash(exec: SqlExecutionPlan): Promise<string> {\n return hashContent(\n canonicalStringify({\n storageHash: exec.meta.storageHash,\n sql: exec.sql,\n params: exec.params,\n }),\n );\n}\n","import { createHash } from 'node:crypto';\n\nconst STRING_LITERAL_REGEX = /'(?:''|[^'])*'/g;\nconst NUMERIC_LITERAL_REGEX = /\\b\\d+(?:\\.\\d+)?\\b/g;\nconst WHITESPACE_REGEX = /\\s+/g;\n\n/**\n * Computes a literal-stripped, normalized fingerprint of a SQL statement.\n *\n * The function strips string and numeric literals, collapses whitespace, and\n * lowercases the result before hashing — so two structurally equivalent\n * statements (with different parameter values) produce the same fingerprint.\n * Used by SQL telemetry to group queries.\n */\nexport function computeSqlFingerprint(sql: string): string {\n const withoutStrings = sql.replace(STRING_LITERAL_REGEX, '?');\n const withoutNumbers = withoutStrings.replace(NUMERIC_LITERAL_REGEX, '?');\n const normalized = withoutNumbers.replace(WHITESPACE_REGEX, ' ').trim().toLowerCase();\n\n const hash = createHash('sha256').update(normalized).digest('hex');\n return `sha256:${hash}`;\n}\n","import type { DraftPlan, SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport async function runBeforeCompileChain(\n middleware: readonly SqlMiddleware[],\n initial: DraftPlan,\n ctx: SqlMiddlewareContext,\n): Promise<DraftPlan> {\n let current = initial;\n for (const mw of middleware) {\n if (!mw.beforeCompile) {\n continue;\n }\n const result = await mw.beforeCompile(current, ctx);\n if (result === undefined) {\n continue;\n }\n if (result.ast === current.ast) {\n continue;\n }\n ctx.log.debug?.({\n event: 'middleware.rewrite',\n middleware: mw.name,\n lane: current.meta.lane,\n });\n current = result;\n }\n\n return current;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { ExecutionPlan } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { AdapterProfile } from '@prisma-next/sql-relational-core/ast';\nimport type { MarkerReader, RuntimeFamilyAdapter } from './runtime-spi';\n\nexport class SqlFamilyAdapter<TContract extends Contract<SqlStorage>>\n implements RuntimeFamilyAdapter<TContract>\n{\n readonly contract: TContract;\n readonly markerReader: MarkerReader;\n\n constructor(contract: TContract, adapterProfile: AdapterProfile) {\n this.contract = contract;\n this.markerReader = adapterProfile;\n }\n\n validatePlan(plan: ExecutionPlan, contract: TContract): void {\n if (plan.meta.target !== contract.target) {\n throw runtimeError('PLAN.TARGET_MISMATCH', 'Plan target does not match runtime target', {\n planTarget: plan.meta.target,\n runtimeTarget: contract.target,\n });\n }\n\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw runtimeError(\n 'PLAN.HASH_MISMATCH',\n 'Plan storage hash does not match runtime contract',\n {\n planStorageHash: plan.meta.storageHash,\n runtimeStorageHash: contract.storage.storageHash,\n },\n );\n }\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n ExecutionStackInstance,\n RuntimeDriverInstance,\n} from '@prisma-next/framework-components/execution';\nimport {\n AsyncIterableResult,\n checkAborted,\n checkMiddlewareCompatibility,\n RuntimeCore,\n type RuntimeExecuteOptions,\n type RuntimeLog,\n runtimeError,\n runWithMiddleware,\n} from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n AnyQueryAst,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecCallContext,\n SqlDriver,\n SqlQueryable,\n SqlTransaction,\n} from '@prisma-next/sql-relational-core/ast';\nimport { validateParamRefRefs } from '@prisma-next/sql-relational-core/ast';\nimport {\n createSqlParamRefMutator,\n type SqlParamRefMutator,\n type SqlParamRefMutatorInternal,\n} from '@prisma-next/sql-relational-core/middleware';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { RuntimeScope } from '@prisma-next/sql-relational-core/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { decodeRow } from './codecs/decoding';\nimport { encodeParams } from './codecs/encoding';\nimport { validateCodecRegistryCompleteness } from './codecs/validation';\nimport { computeSqlContentHash } from './content-hash';\nimport { computeSqlFingerprint } from './fingerprint';\nimport { lowerSqlPlan } from './lower-sql-plan';\nimport { runBeforeCompileChain } from './middleware/before-compile-chain';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './middleware/sql-middleware';\nimport type {\n RuntimeFamilyAdapter,\n RuntimeTelemetryEvent,\n RuntimeVerifyOptions,\n TelemetryOutcome,\n} from './runtime-spi';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterInstance,\n SqlRuntimeExtensionInstance,\n} from './sql-context';\nimport { SqlFamilyAdapter } from './sql-family-adapter';\n\nexport type Log = RuntimeLog;\n\nexport interface RuntimeOptions<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> {\n readonly context: ExecutionContext<TContract>;\n readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n readonly driver: SqlDriver<unknown>;\n readonly verify: RuntimeVerifyOptions;\n readonly middleware?: readonly SqlMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n readonly log?: Log;\n}\n\nexport interface CreateRuntimeOptions<\n TContract extends Contract<SqlStorage> = Contract<SqlStorage>,\n TTargetId extends string = string,\n> {\n readonly stackInstance: ExecutionStackInstance<\n 'sql',\n TTargetId,\n SqlRuntimeAdapterInstance<TTargetId>,\n RuntimeDriverInstance<'sql', TTargetId>,\n SqlRuntimeExtensionInstance<TTargetId>\n >;\n readonly context: ExecutionContext<TContract>;\n readonly driver: SqlDriver<unknown>;\n readonly verify: RuntimeVerifyOptions;\n readonly middleware?: readonly SqlMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n readonly log?: Log;\n}\n\nexport interface Runtime extends RuntimeQueryable {\n connection(): Promise<RuntimeConnection>;\n telemetry(): RuntimeTelemetryEvent | null;\n close(): Promise<void>;\n}\n\nexport interface RuntimeConnection extends RuntimeQueryable {\n transaction(): Promise<RuntimeTransaction>;\n /**\n * Returns the connection to the pool for reuse. Only call this when the connection is known to be in a clean state. If a transaction commit/rollback failed or the connection is otherwise suspect, call `destroy(reason)` instead.\n */\n release(): Promise<void>;\n /**\n * Evicts the connection so it is never reused. Call this when the connection may be in an indeterminate state (e.g. a failed rollback leaving an open transaction, or a broken socket).\n *\n * If teardown fails the error is propagated and the connection remains retryable, so the caller can decide whether to swallow the failure or retry cleanup. Calling destroy() or release() more than once after a successful teardown is caller error.\n *\n * `reason` is advisory context only. It may be surfaced to driver-level observability hooks (e.g. pg-pool's `'release'` event) but does not influence eviction behavior and is not rethrown.\n */\n destroy(reason?: unknown): Promise<void>;\n}\n\nexport interface RuntimeTransaction extends RuntimeQueryable {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\nexport interface RuntimeQueryable extends RuntimeScope {}\n\nexport interface TransactionContext extends RuntimeQueryable {\n readonly invalidated: boolean;\n}\n\nexport type { RuntimeTelemetryEvent, RuntimeVerifyOptions, TelemetryOutcome };\n\nfunction isExecutionPlan(plan: SqlExecutionPlan | SqlQueryPlan): plan is SqlExecutionPlan {\n return 'sql' in plan;\n}\n\n// v8 ignore next 2\nconst noopLogSink = (): void => {};\nconst noopLog: Log = { info: noopLogSink, warn: noopLogSink, error: noopLogSink };\n\nclass SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorage>>\n extends RuntimeCore<SqlQueryPlan, SqlExecutionPlan, SqlMiddleware>\n implements Runtime\n{\n private readonly contract: TContract;\n private readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n private readonly driver: SqlDriver<unknown>;\n private readonly familyAdapter: RuntimeFamilyAdapter<Contract<SqlStorage>>;\n private readonly contractCodecs: ContractCodecRegistry;\n private readonly codecDescriptors: CodecDescriptorRegistry;\n private readonly sqlCtx: SqlMiddlewareContext;\n private readonly verify: RuntimeVerifyOptions;\n private codecRegistryValidated: boolean;\n private verified: boolean;\n private startupVerified: boolean;\n private _telemetry: RuntimeTelemetryEvent | null;\n\n constructor(options: RuntimeOptions<TContract>) {\n const { context, adapter, driver, verify, middleware, mode, log } = options;\n\n if (middleware) {\n for (const mw of middleware) {\n checkMiddlewareCompatibility(mw, 'sql', context.contract.target);\n }\n }\n\n const sqlCtx: SqlMiddlewareContext = {\n contract: context.contract,\n mode: mode ?? 'strict',\n now: () => Date.now(),\n log: log ?? noopLog,\n // ctx is only invoked by runWithMiddleware with execs this runtime lowered; the framework parameter type is the cross-family base.\n contentHash: (exec) => computeSqlContentHash(exec as SqlExecutionPlan),\n };\n\n super({ middleware: middleware ?? [], ctx: sqlCtx });\n\n this.contract = context.contract;\n this.adapter = adapter;\n this.driver = driver;\n this.familyAdapter = new SqlFamilyAdapter(context.contract, adapter.profile);\n this.contractCodecs = context.contractCodecs;\n this.codecDescriptors = context.codecDescriptors;\n this.sqlCtx = sqlCtx;\n this.verify = verify;\n this.codecRegistryValidated = false;\n this.verified = verify.mode === 'startup' ? false : verify.mode === 'always';\n this.startupVerified = false;\n this._telemetry = null;\n\n if (verify.mode === 'startup') {\n validateCodecRegistryCompleteness(this.codecDescriptors, context.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n /**\n * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan` with encoded parameters ready for the driver. This is the single point at which params transition from app-layer values to driver wire-format.\n *\n * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so per-query cancellation reaches every codec body during parameter encoding. The framework abstract typed this as `CodecCallContext`; the SQL family narrows it to the SQL-specific extension. SQL params do not populate `ctx.column` — encode-side column metadata is the middleware's domain.\n */\n protected override async lower(\n plan: SqlQueryPlan,\n ctx: SqlCodecCallContext,\n ): Promise<SqlExecutionPlan> {\n validateParamRefRefs(plan.ast, this.codecDescriptors);\n const lowered = lowerSqlPlan(this.adapter, this.contract, plan);\n return Object.freeze({\n ...lowered,\n params: await encodeParams(lowered, ctx, this.contractCodecs),\n });\n }\n\n /**\n * Default driver invocation required by the abstract `RuntimeCore` contract. Every production path overrides `execute()` and routes through `executeAgainstQueryable`, so this hook is defensive only — subclasses that delegate back to `super.execute()` would land here.\n */\n // v8 ignore next 6\n protected override runDriver(exec: SqlExecutionPlan): AsyncIterable<Record<string, unknown>> {\n return this.driver.execute<Record<string, unknown>>({\n sql: exec.sql,\n params: exec.params,\n });\n }\n\n /**\n * SQL pre-compile hook. Runs the registered middleware `beforeCompile` chain over the plan's draft (AST + meta). Returns the original plan unchanged when no middleware rewrote the AST; otherwise returns a new plan carrying the rewritten AST and meta. The AST is the authoritative source of execution metadata, so a rewrite needs no sidecar reconciliation here — the lowering adapter and the encoder both walk the rewritten\n * AST directly.\n */\n protected override async runBeforeCompile(plan: SqlQueryPlan): Promise<SqlQueryPlan> {\n const rewrittenDraft = await runBeforeCompileChain(\n this.middleware,\n { ast: plan.ast, meta: plan.meta },\n this.sqlCtx,\n );\n return rewrittenDraft.ast === plan.ast\n ? plan\n : { ...plan, ast: rewrittenDraft.ast, meta: rewrittenDraft.meta };\n }\n\n override execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return this.executeAgainstQueryable<Row>(plan, this.driver, options);\n }\n\n private executeAgainstQueryable<Row>(\n plan: SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>,\n queryable: SqlQueryable,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n this.ensureCodecRegistryValidated();\n\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call — the same reference is shared by encodeParams (lower), decodeRow (per-row), and the stream loop's between-row checks. Per-cell ctx allocations inside decodeField add `column` for resolvable cells without re-wrapping the signal. The ctx object is always allocated; the `signal` field is only included when a signal was supplied (exactOptionalPropertyTypes).\n const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal };\n // Per-execute view of the middleware ctx that carries the per-query\n // signal. `self.ctx` is allocated once at construction (no signal); we\n // shallow-clone it here so middleware sees the same `AbortSignal`\n // reference threaded into `codecCtx.signal` (ADR 207 identity).\n const execMiddlewareCtx = signal === undefined ? self.ctx : { ...self.ctx, signal };\n\n const generator = async function* (): AsyncGenerator<Row, void, unknown> {\n checkAborted(codecCtx, 'stream');\n\n let exec: SqlExecutionPlan;\n if (isExecutionPlan(plan)) {\n if (plan.ast) {\n validateParamRefRefs(plan.ast, self.codecDescriptors);\n }\n exec = Object.freeze({\n ...plan,\n params: await encodeParams(plan, codecCtx, self.contractCodecs),\n });\n } else {\n exec = await self.lower(await self.runBeforeCompile(plan), codecCtx);\n }\n\n self.familyAdapter.validatePlan(exec, self.contract);\n self._telemetry = null;\n\n if (!self.startupVerified && self.verify.mode === 'startup') {\n await self.verifyMarker();\n }\n\n if (!self.verified && self.verify.mode === 'onFirstUse') {\n await self.verifyMarker();\n }\n\n const startedAt = Date.now();\n let outcome: TelemetryOutcome | null = null;\n\n try {\n if (self.verify.mode === 'always') {\n await self.verifyMarker();\n }\n\n const paramsMutator: SqlParamRefMutatorInternal = createSqlParamRefMutator(exec);\n const stream = runWithMiddleware<\n SqlExecutionPlan,\n Record<string, unknown>,\n SqlParamRefMutator\n >(\n exec,\n self.middleware,\n execMiddlewareCtx,\n () =>\n queryable.execute<Record<string, unknown>>({\n sql: exec.sql,\n // Read params after the `beforeExecute` middleware chain has\n // run so that any `mutator.replaceValue(...)` calls land in\n // the driver-bound params array. When no middleware mutated,\n // `currentParams()` returns `exec.params` by reference identity.\n params: paramsMutator.currentParams(),\n }),\n paramsMutator,\n );\n\n // Manually drive the driver's async iterator so the between-row abort check fires *before* requesting the next row. With a `for await...of` loop the runtime would await `iterator.next()` first, leaving a window where one extra row is pulled through the driver after the signal aborted.\n const iterator = stream[Symbol.asyncIterator]();\n try {\n while (true) {\n checkAborted(codecCtx, 'stream');\n const next = await iterator.next();\n if (next.done) {\n break;\n }\n const decodedRow = await decodeRow(next.value, exec, codecCtx, self.contractCodecs);\n yield decodedRow as Row;\n }\n } finally {\n // Best-effort iterator cleanup so the driver can release its resources whether the stream finished normally, threw, or was abandoned by the consumer.\n await iterator.return?.();\n }\n\n outcome = 'success';\n } catch (error) {\n outcome = 'runtime-error';\n throw error;\n } finally {\n if (outcome !== null) {\n self.recordTelemetry(exec, outcome, Date.now() - startedAt);\n }\n }\n };\n\n return new AsyncIterableResult(generator());\n }\n\n async connection(): Promise<RuntimeConnection> {\n const driverConn = await this.driver.acquireConnection();\n const self = this;\n\n const wrappedConnection: RuntimeConnection = {\n async transaction(): Promise<RuntimeTransaction> {\n const driverTx = await driverConn.beginTransaction();\n return self.wrapTransaction(driverTx);\n },\n async release(): Promise<void> {\n await driverConn.release();\n },\n async destroy(reason?: unknown): Promise<void> {\n await driverConn.destroy(reason);\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverConn, options);\n },\n };\n\n return wrappedConnection;\n }\n\n private wrapTransaction(driverTx: SqlTransaction): RuntimeTransaction {\n const self = this;\n return {\n async commit(): Promise<void> {\n await driverTx.commit();\n },\n async rollback(): Promise<void> {\n await driverTx.rollback();\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverTx, options);\n },\n };\n }\n\n telemetry(): RuntimeTelemetryEvent | null {\n return this._telemetry;\n }\n\n async close(): Promise<void> {\n await this.driver.close();\n }\n\n private ensureCodecRegistryValidated(): void {\n if (!this.codecRegistryValidated) {\n validateCodecRegistryCompleteness(this.codecDescriptors, this.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n private async verifyMarker(): Promise<void> {\n const readResult = await this.familyAdapter.markerReader.readMarker(this.driver);\n\n if (readResult.kind !== 'present') {\n if (this.verify.requireMarker) {\n throw runtimeError('CONTRACT.MARKER_MISSING', 'Contract marker not found in database');\n }\n\n this.verified = true;\n return;\n }\n\n const marker = readResult.record;\n\n const contract = this.contract as {\n storage: { storageHash: string };\n execution?: { executionHash?: string | null };\n profileHash?: string | null;\n };\n\n if (marker.storageHash !== contract.storage.storageHash) {\n throw runtimeError(\n 'CONTRACT.MARKER_MISMATCH',\n 'Database storage hash does not match contract',\n {\n expected: contract.storage.storageHash,\n actual: marker.storageHash,\n },\n );\n }\n\n const expectedProfile = contract.profileHash ?? null;\n if (expectedProfile !== null && marker.profileHash !== expectedProfile) {\n throw runtimeError(\n 'CONTRACT.MARKER_MISMATCH',\n 'Database profile hash does not match contract',\n {\n expectedProfile,\n actualProfile: marker.profileHash,\n },\n );\n }\n\n this.verified = true;\n this.startupVerified = true;\n }\n\n private recordTelemetry(\n plan: SqlExecutionPlan,\n outcome: TelemetryOutcome,\n durationMs?: number,\n ): void {\n const contract = this.contract as { target: string };\n this._telemetry = Object.freeze({\n lane: plan.meta.lane,\n target: contract.target,\n fingerprint: computeSqlFingerprint(plan.sql),\n outcome,\n ...(durationMs !== undefined ? { durationMs } : {}),\n });\n }\n}\n\nfunction transactionClosedError(): Error {\n return runtimeError(\n 'RUNTIME.TRANSACTION_CLOSED',\n 'Cannot read from a query result after the transaction has ended. Await the result or call .toArray() inside the transaction callback.',\n {},\n );\n}\n\nexport async function withTransaction<R>(\n runtime: Runtime,\n fn: (tx: TransactionContext) => PromiseLike<R>,\n): Promise<R> {\n const connection = await runtime.connection();\n const transaction = await connection.transaction();\n\n let invalidated = false;\n const txContext: TransactionContext = {\n get invalidated() {\n return invalidated;\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n if (invalidated) {\n throw transactionClosedError();\n }\n const inner = transaction.execute(plan, options);\n const guarded = async function* (): AsyncGenerator<Row, void, unknown> {\n for await (const row of inner) {\n if (invalidated) {\n throw transactionClosedError();\n }\n yield row;\n }\n };\n return new AsyncIterableResult(guarded());\n },\n };\n\n let connectionDisposed = false;\n const destroyConnection = async (reason: unknown): Promise<void> => {\n if (connectionDisposed) return;\n connectionDisposed = true;\n // SqlConnection.destroy() propagates teardown errors so callers can decide what to do with them. Here, we're already about to throw a more informative error describing why we're evicting the connection (rollback/commit failure), so swallowing the teardown error is the right call — surfacing it would mask the original cause.\n await connection.destroy(reason).catch(() => undefined);\n };\n\n try {\n let result: R;\n try {\n result = await fn(txContext);\n } catch (error) {\n try {\n await transaction.rollback();\n } catch (rollbackError) {\n await destroyConnection(rollbackError);\n const wrapped = runtimeError(\n 'RUNTIME.TRANSACTION_ROLLBACK_FAILED',\n 'Transaction rollback failed after callback error',\n { rollbackError },\n );\n wrapped.cause = error;\n throw wrapped;\n }\n throw error;\n } finally {\n invalidated = true;\n }\n\n try {\n await transaction.commit();\n } catch (commitError) {\n // After a failed COMMIT the server-side transaction may be: (a) already committed (error on response path), (b) already rolled back (deferred constraint / serialization failure), or (c) still open (COMMIT never reached the server). Attempt a best-effort rollback to cover (c) and confirm the protocol is healthy.\n //\n // If rollback succeeds, the server is definitely no longer in a transaction (no-op in (a)/(b), real cleanup in (c)) and we've just proved the connection round-trips correctly — it's safe to return to the pool. If rollback fails, the connection state is ambiguous (broken socket, protocol desync, etc.) and we must destroy it.\n try {\n await transaction.rollback();\n } catch {\n await destroyConnection(commitError);\n }\n const wrapped = runtimeError(\n 'RUNTIME.TRANSACTION_COMMIT_FAILED',\n 'Transaction commit failed',\n { commitError },\n );\n wrapped.cause = commitError;\n throw wrapped;\n }\n return result;\n } finally {\n if (!connectionDisposed) {\n await connection.release();\n }\n }\n}\n\nexport function createRuntime<TContract extends Contract<SqlStorage>, TTargetId extends string>(\n options: CreateRuntimeOptions<TContract, TTargetId>,\n): Runtime {\n const { stackInstance, context, driver, verify, middleware, mode, log } = options;\n\n return new SqlRuntimeImpl({\n context,\n adapter: stackInstance.adapter,\n driver,\n verify,\n ...ifDefined('middleware', middleware),\n ...ifDefined('mode', mode),\n ...ifDefined('log', log),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAKA,SAAgB,gBAAgB,UAA6C;CAC3E,MAAM,2BAAW,IAAI,KAAa;CAElC,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,QAAQ,OAAO,EACxD,KAAK,MAAM,UAAU,OAAO,OAAO,MAAM,QAAQ,EAAE;EACjD,MAAM,UAAU,OAAO;EACvB,SAAS,IAAI,QAAQ;;CAIzB,OAAO;;AAGT,SAAS,2BAA2B,UAAqD;CACvF,MAAM,2BAAW,IAAI,KAAqB;CAE1C,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,SAAS,QAAQ,OAAO,EACtE,KAAK,MAAM,CAAC,YAAY,WAAW,OAAO,QAAQ,MAAM,QAAQ,EAAE;EAChE,MAAM,UAAU,OAAO;EACvB,MAAM,MAAM,GAAG,UAAU,GAAG;EAC5B,SAAS,IAAI,KAAK,QAAQ;;CAI9B,OAAO;;AAGT,SAAgB,8BACd,UACA,UACM;CACN,MAAM,WAAW,2BAA2B,SAAS;CACrD,MAAM,gBAA2E,EAAE;CAEnF,KAAK,MAAM,CAAC,KAAK,YAAY,SAAS,SAAS,EAC7C,IAAI,SAA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,cAAc,WAAW;EACtC,GAAG,UAAU,QAAQ,KAAK;EAC1B,GAAG,UAAU,OAAO,IAAI;EACzB,CAAC"}
1
+ {"version":3,"file":"exports-B_kfmMPM.mjs","names":[],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/budgets.ts","../src/guardrails/raw.ts","../src/middleware/lints.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/codecs/alias-resolver.ts","../src/codecs/decoding.ts","../src/codecs/encoding.ts","../src/content-hash.ts","../src/fingerprint.ts","../src/middleware/before-compile-chain.ts","../src/sql-family-adapter.ts","../src/sql-runtime.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\n\nexport function extractCodecIds(contract: Contract<SqlStorage>): Set<string> {\n const codecIds = new Set<string>();\n\n for (const table of Object.values(contract.storage.tables)) {\n for (const column of Object.values(table.columns)) {\n const codecId = column.codecId;\n codecIds.add(codecId);\n }\n }\n\n return codecIds;\n}\n\nfunction extractCodecIdsFromColumns(contract: Contract<SqlStorage>): Map<string, string> {\n const codecIds = new Map<string, string>();\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n const codecId = column.codecId;\n const key = `${tableName}.${columnName}`;\n codecIds.set(key, codecId);\n }\n }\n\n return codecIds;\n}\n\nexport function validateContractCodecMappings(\n registry: CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\n const codecIds = extractCodecIdsFromColumns(contract);\n const invalidCodecs: Array<{ table: string; column: string; codecId: string }> = [];\n\n for (const [key, codecId] of codecIds.entries()) {\n if (registry.descriptorFor(codecId) === undefined) {\n const parts = key.split('.');\n const table = parts[0] ?? '';\n const column = parts[1] ?? '';\n invalidCodecs.push({ table, column, codecId });\n }\n }\n\n if (invalidCodecs.length > 0) {\n const details: Record<string, unknown> = {\n contractTarget: contract.target,\n invalidCodecs,\n };\n\n throw runtimeError(\n 'RUNTIME.CODEC_MISSING',\n `Missing codec implementations for column codecIds: ${invalidCodecs.map((c) => `${c.table}.${c.column} (${c.codecId})`).join(', ')}`,\n details,\n );\n }\n}\n\nexport function validateCodecRegistryCompleteness(\n registry: CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\n validateContractCodecMappings(registry, contract);\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Adapter, AnyQueryAst, LoweredStatement } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\n\n/**\n * Lowers a SQL query plan to an executable Plan by calling the adapter's lower method.\n *\n * @param adapter - Adapter to lower AST to SQL\n * @param contract - Contract for lowering context\n * @param queryPlan - SQL query plan from a lane (contains AST, params, meta, but no SQL)\n * @returns Fully executable Plan with SQL string\n */\nexport function lowerSqlPlan<Row>(\n adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>,\n contract: Contract<SqlStorage>,\n queryPlan: SqlQueryPlan<Row>,\n): SqlExecutionPlan<Row> {\n const lowered = adapter.lower(queryPlan.ast, {\n contract,\n params: queryPlan.params,\n });\n\n return Object.freeze({\n sql: lowered.sql,\n params: lowered.params ?? queryPlan.params,\n ast: queryPlan.ast,\n meta: queryPlan.meta,\n });\n}\n","import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { type } from 'arktype';\n\nexport interface ContractMarkerRow {\n core_hash: string;\n profile_hash: string;\n contract_json: unknown | null;\n canonical_version: number | null;\n updated_at: Date;\n app_tag: string | null;\n meta: unknown | null;\n invariants: readonly string[];\n}\n\nconst MetaSchema = type({ '[string]': 'unknown' });\n\nfunction parseMeta(meta: unknown): Record<string, unknown> {\n if (meta === null || meta === undefined) {\n return {};\n }\n\n let parsed: unknown;\n if (typeof meta === 'string') {\n try {\n parsed = JSON.parse(meta);\n } catch {\n return {};\n }\n } else {\n parsed = meta;\n }\n\n const result = MetaSchema(parsed);\n if (result instanceof type.errors) {\n return {};\n }\n\n return result as Record<string, unknown>;\n}\n\nconst ContractMarkerRowSchema = type({\n core_hash: 'string',\n profile_hash: 'string',\n 'contract_json?': 'unknown | null',\n 'canonical_version?': 'number | null',\n 'updated_at?': 'Date | string',\n 'app_tag?': 'string | null',\n 'meta?': 'unknown | null',\n invariants: type('string').array(),\n});\n\nexport function parseContractMarkerRow(row: unknown): ContractMarkerRecord {\n const result = ContractMarkerRowSchema(row);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Invalid contract marker row: ${messages}`);\n }\n\n const updatedAt = result.updated_at\n ? result.updated_at instanceof Date\n ? result.updated_at\n : new Date(result.updated_at)\n : new Date();\n\n return {\n storageHash: result.core_hash,\n profileHash: result.profile_hash,\n contractJson: result.contract_json ?? null,\n canonicalVersion: result.canonical_version ?? null,\n updatedAt,\n appTag: result.app_tag ?? null,\n meta: parseMeta(result.meta),\n invariants: result.invariants,\n };\n}\n","import {\n type AfterExecuteResult,\n type RuntimeErrorEnvelope,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport { isQueryAst, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport interface BudgetsOptions {\n readonly maxRows?: number;\n readonly defaultTableRows?: number;\n readonly tableRows?: Record<string, number>;\n readonly maxLatencyMs?: number;\n readonly severities?: {\n readonly rowCount?: 'warn' | 'error';\n readonly latency?: 'warn' | 'error';\n };\n}\n\nfunction hasAggregateWithoutGroupBy(ast: SelectAst): boolean {\n if (ast.groupBy !== undefined) {\n return false;\n }\n return ast.projection.some((item) => item.expr.kind === 'aggregate');\n}\n\nfunction primaryTableFromAst(ast: SelectAst): string {\n switch (ast.from.kind) {\n case 'table-source':\n return ast.from.name;\n case 'derived-table-source':\n return ast.from.alias;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source kind: ${(ast.from satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction estimateRowsFromAst(\n ast: SelectAst,\n tableRows: Record<string, number>,\n defaultTableRows: number,\n hasAggregateWithoutGroup: boolean,\n): number {\n if (hasAggregateWithoutGroup) {\n return 1;\n }\n\n const tableEstimate = tableRows[primaryTableFromAst(ast)] ?? defaultTableRows;\n\n if (ast.limit !== undefined) {\n return Math.min(ast.limit, tableEstimate);\n }\n\n return tableEstimate;\n}\n\nfunction emitBudgetViolation(\n error: RuntimeErrorEnvelope,\n shouldBlock: boolean,\n ctx: SqlMiddlewareContext,\n): void {\n if (shouldBlock) {\n throw error;\n }\n ctx.log.warn({\n code: error.code,\n message: error.message,\n details: error.details,\n });\n}\n\nexport function budgets(options?: BudgetsOptions): SqlMiddleware {\n const maxRows = options?.maxRows ?? 10_000;\n const defaultTableRows = options?.defaultTableRows ?? 10_000;\n const tableRows = options?.tableRows ?? {};\n const maxLatencyMs = options?.maxLatencyMs ?? 1_000;\n const rowSeverity = options?.severities?.rowCount ?? 'error';\n\n const observedRowsByPlan = new WeakMap<SqlExecutionPlan, { count: number }>();\n\n return Object.freeze({\n name: 'budgets',\n familyId: 'sql' as const,\n\n async beforeExecute(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n observedRowsByPlan.set(plan, { count: 0 });\n\n if (isQueryAst(plan.ast) && plan.ast.kind === 'select') {\n return evaluateSelectAst(plan.ast, ctx);\n }\n },\n\n async onRow(_row: Record<string, unknown>, plan: SqlExecutionPlan, _ctx: SqlMiddlewareContext) {\n const state = observedRowsByPlan.get(plan);\n if (!state) return;\n state.count += 1;\n if (state.count > maxRows) {\n throw runtimeError('BUDGET.ROWS_EXCEEDED', 'Observed row count exceeds budget', {\n source: 'observed',\n observedRows: state.count,\n maxRows,\n });\n }\n },\n\n async afterExecute(\n _plan: SqlExecutionPlan,\n result: AfterExecuteResult,\n ctx: SqlMiddlewareContext,\n ) {\n const latencyMs = result.latencyMs;\n if (latencyMs > maxLatencyMs) {\n const shouldBlock = ctx.mode === 'strict';\n emitBudgetViolation(\n runtimeError('BUDGET.TIME_EXCEEDED', 'Query latency exceeds budget', {\n latencyMs,\n maxLatencyMs,\n }),\n shouldBlock,\n ctx,\n );\n }\n },\n });\n\n function evaluateSelectAst(ast: SelectAst, ctx: SqlMiddlewareContext) {\n const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);\n const estimated = estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggNoGroup);\n const isUnbounded = ast.limit === undefined && !hasAggNoGroup;\n const shouldBlock = rowSeverity === 'error' || ctx.mode === 'strict';\n\n if (isUnbounded) {\n const details =\n estimated >= maxRows\n ? { source: 'ast', estimatedRows: estimated, maxRows }\n : { source: 'ast', maxRows };\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', details),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n if (estimated > maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Estimated row count exceeds budget', {\n source: 'ast',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n }\n }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\n\nexport type LintSeverity = 'error' | 'warn';\nexport type BudgetSeverity = 'error' | 'warn';\n\nexport interface LintFinding {\n readonly code: `LINT.${string}`;\n readonly severity: LintSeverity;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface BudgetFinding {\n readonly code: `BUDGET.${string}`;\n readonly severity: BudgetSeverity;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface RawGuardrailConfig {\n readonly budgets?: {\n readonly unboundedSelectSeverity?: BudgetSeverity;\n readonly estimatedRows?: number;\n };\n}\n\nexport interface RawGuardrailResult {\n readonly lints: LintFinding[];\n readonly budgets: BudgetFinding[];\n readonly statement: 'select' | 'mutation' | 'other';\n}\n\n/**\n * Minimal plan view consumed by raw-SQL guardrails. Structurally satisfied\n * by `SqlExecutionPlan`; declared inline so this module stays decoupled\n * from a specific plan type at the call site.\n */\ninterface RawGuardrailPlan {\n readonly sql: string;\n readonly meta: PlanMeta;\n}\n\nconst SELECT_STAR_REGEX = /select\\s+\\*/i;\nconst LIMIT_REGEX = /\\blimit\\b/i;\nconst MUTATION_PREFIX_REGEX = /^(insert|update|delete|create|alter|drop|truncate)\\b/i;\n\nconst READ_ONLY_INTENTS = new Set(['read', 'report', 'readonly']);\n\nexport function evaluateRawGuardrails(\n plan: RawGuardrailPlan,\n config?: RawGuardrailConfig,\n): RawGuardrailResult {\n const lints: LintFinding[] = [];\n const budgets: BudgetFinding[] = [];\n\n const normalized = normalizeWhitespace(plan.sql);\n const statementType = classifyStatement(normalized);\n\n if (statementType === 'select') {\n if (SELECT_STAR_REGEX.test(normalized)) {\n lints.push(\n createLint('LINT.SELECT_STAR', 'error', 'Raw SQL plan selects all columns via *', {\n sql: snippet(plan.sql),\n }),\n );\n }\n\n if (!LIMIT_REGEX.test(normalized)) {\n const severity = config?.budgets?.unboundedSelectSeverity ?? 'error';\n lints.push(\n createLint('LINT.NO_LIMIT', 'warn', 'Raw SQL plan omits LIMIT clause', {\n sql: snippet(plan.sql),\n }),\n );\n\n budgets.push(\n createBudget(\n 'BUDGET.ROWS_EXCEEDED',\n severity,\n 'Raw SQL plan is unbounded and may exceed row budget',\n {\n sql: snippet(plan.sql),\n ...(config?.budgets?.estimatedRows !== undefined\n ? { estimatedRows: config.budgets.estimatedRows }\n : {}),\n },\n ),\n );\n }\n }\n\n if (isMutationStatement(statementType) && isReadOnlyIntent(plan.meta)) {\n lints.push(\n createLint(\n 'LINT.READ_ONLY_MUTATION',\n 'error',\n 'Raw SQL plan mutates data despite read-only intent',\n {\n sql: snippet(plan.sql),\n intent: plan.meta.annotations?.['intent'],\n },\n ),\n );\n }\n\n return { lints, budgets, statement: statementType };\n}\n\nfunction classifyStatement(sql: string): 'select' | 'mutation' | 'other' {\n const trimmed = sql.trim();\n const lower = trimmed.toLowerCase();\n\n if (lower.startsWith('with')) {\n if (lower.includes('select')) {\n return 'select';\n }\n }\n\n if (lower.startsWith('select')) {\n return 'select';\n }\n\n if (MUTATION_PREFIX_REGEX.test(trimmed)) {\n return 'mutation';\n }\n\n return 'other';\n}\n\nfunction isMutationStatement(statement: 'select' | 'mutation' | 'other'): boolean {\n return statement === 'mutation';\n}\n\nfunction isReadOnlyIntent(meta: PlanMeta): boolean {\n const annotations = meta.annotations as { intent?: string } | undefined;\n const intent =\n typeof annotations?.intent === 'string' ? annotations.intent.toLowerCase() : undefined;\n return intent !== undefined && READ_ONLY_INTENTS.has(intent);\n}\n\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction snippet(sql: string): string {\n return normalizeWhitespace(sql).slice(0, 200);\n}\n\nfunction createLint(\n code: LintFinding['code'],\n severity: LintFinding['severity'],\n message: string,\n details?: Record<string, unknown>,\n): LintFinding {\n return { code, severity, message, ...(details ? { details } : {}) };\n}\n\nfunction createBudget(\n code: BudgetFinding['code'],\n severity: BudgetFinding['severity'],\n message: string,\n details?: Record<string, unknown>,\n): BudgetFinding {\n return { code, severity, message, ...(details ? { details } : {}) };\n}\n","import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport {\n type AnyFromSource,\n type AnyQueryAst,\n isQueryAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { evaluateRawGuardrails } from '../guardrails/raw';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport interface LintsOptions {\n readonly severities?: {\n readonly selectStar?: 'warn' | 'error';\n readonly noLimit?: 'warn' | 'error';\n readonly deleteWithoutWhere?: 'warn' | 'error';\n readonly updateWithoutWhere?: 'warn' | 'error';\n readonly readOnlyMutation?: 'warn' | 'error';\n readonly unindexedPredicate?: 'warn' | 'error';\n };\n readonly fallbackWhenAstMissing?: 'raw' | 'skip';\n}\n\nexport interface LintFinding {\n readonly code: `LINT.${string}`;\n readonly severity: 'error' | 'warn';\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nfunction getFromSourceTableDetail(source: AnyFromSource): string | undefined {\n switch (source.kind) {\n case 'table-source':\n return source.name;\n case 'derived-table-source':\n return source.alias;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source kind: ${(source satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction evaluateAstLints(ast: AnyQueryAst): LintFinding[] {\n const findings: LintFinding[] = [];\n\n switch (ast.kind) {\n case 'delete':\n if (ast.where === undefined) {\n findings.push({\n code: 'LINT.DELETE_WITHOUT_WHERE',\n severity: 'error',\n message:\n 'DELETE without WHERE clause blocks execution to prevent accidental full-table deletion',\n details: { table: ast.table.name },\n });\n }\n break;\n\n case 'update':\n if (ast.where === undefined) {\n findings.push({\n code: 'LINT.UPDATE_WITHOUT_WHERE',\n severity: 'error',\n message:\n 'UPDATE without WHERE clause blocks execution to prevent accidental full-table update',\n details: { table: ast.table.name },\n });\n }\n break;\n\n case 'select':\n if (ast.limit === undefined) {\n const table = getFromSourceTableDetail(ast.from);\n findings.push({\n code: 'LINT.NO_LIMIT',\n severity: 'warn',\n message: 'Unbounded SELECT may return large result sets',\n ...ifDefined('details', table !== undefined ? { table } : undefined),\n });\n }\n if (ast.selectAllIntent !== undefined) {\n const table = ast.selectAllIntent.table;\n findings.push({\n code: 'LINT.SELECT_STAR',\n severity: 'warn',\n message: 'Query selects all columns via selectAll intent',\n ...ifDefined('details', table !== undefined ? { table } : undefined),\n });\n }\n break;\n\n case 'insert':\n break;\n\n case 'raw-sql':\n // Raw-SQL ASTs opt out of structural lints (LIMIT / WHERE etc.) —\n // the embedded SQL fragments are caller-authored and the lint's\n // shape-based heuristics don't apply.\n break;\n\n // v8 ignore next 2\n default:\n throw new Error(`Unsupported AST kind: ${(ast satisfies never as { kind: string }).kind}`);\n }\n\n return findings;\n}\n\nfunction getConfiguredSeverity(code: string, options?: LintsOptions): 'warn' | 'error' | undefined {\n const severities = options?.severities;\n if (!severities) return undefined;\n\n switch (code) {\n case 'LINT.SELECT_STAR':\n return severities.selectStar;\n case 'LINT.NO_LIMIT':\n return severities.noLimit;\n case 'LINT.DELETE_WITHOUT_WHERE':\n return severities.deleteWithoutWhere;\n case 'LINT.UPDATE_WITHOUT_WHERE':\n return severities.updateWithoutWhere;\n case 'LINT.READ_ONLY_MUTATION':\n return severities.readOnlyMutation;\n case 'LINT.UNINDEXED_PREDICATE':\n return severities.unindexedPredicate;\n default:\n return undefined;\n }\n}\n\n/**\n * AST-first lint middleware for SQL plans. When `plan.ast` is a SQL QueryAst, inspects\n * the AST structurally. When `plan.ast` is missing, falls back to raw heuristic\n * guardrails or skips linting depending on `fallbackWhenAstMissing`.\n *\n * Rules (AST-based):\n * - DELETE without WHERE: blocks execution (configurable severity, default error)\n * - UPDATE without WHERE: blocks execution (configurable severity, default error)\n * - Unbounded SELECT: warn/error (severity from noLimit)\n * - SELECT * intent: warn/error (severity from selectStar)\n *\n * Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic\n * SQL parsing; `'skip'` skips all lints. Default is `'raw'`.\n */\nexport function lints(options?: LintsOptions): SqlMiddleware {\n const fallback = options?.fallbackWhenAstMissing ?? 'raw';\n\n return Object.freeze({\n name: 'lints',\n familyId: 'sql' as const,\n\n async beforeExecute(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n const findings: LintFinding[] = [];\n if (isQueryAst(plan.ast)) {\n findings.push(...evaluateAstLints(plan.ast));\n // Raw-SQL ASTs opt out of structural AST lints (no LIMIT /\n // WHERE shape to inspect) but the embedded SQL text still\n // wants the raw-heuristic guardrails. Without this the lint\n // middleware would silently disable both for raw plans.\n if (plan.ast.kind === 'raw-sql') {\n findings.push(...evaluateRawGuardrails(plan).lints);\n }\n } else if (fallback !== 'skip') {\n findings.push(...evaluateRawGuardrails(plan).lints);\n }\n\n for (const lint of findings) {\n const configuredSeverity = getConfiguredSeverity(lint.code, options);\n const effectiveSeverity = configuredSeverity ?? lint.severity;\n\n if (effectiveSeverity === 'error') {\n throw runtimeError(lint.code, lint.message, lint.details);\n }\n if (effectiveSeverity === 'warn') {\n ctx.log.warn({\n code: lint.code,\n message: lint.message,\n details: lint.details,\n });\n }\n }\n },\n });\n}\n","import type { Contract, ExecutionMutationDefaultValue } from '@prisma-next/contract/types';\nimport type { AnyCodecDescriptor, CodecDescriptor } from '@prisma-next/framework-components/codec';\nimport type { ComponentDescriptor } from '@prisma-next/framework-components/components';\nimport { checkContractComponentRequirements } from '@prisma-next/framework-components/components';\nimport {\n createExecutionStack,\n type ExecutionStack,\n type RuntimeAdapterDescriptor,\n type RuntimeAdapterInstance,\n type RuntimeDriverDescriptor,\n type RuntimeDriverInstance,\n type RuntimeExtensionDescriptor,\n type RuntimeExtensionInstance,\n type RuntimeTargetDescriptor,\n type RuntimeTargetInstance,\n} from '@prisma-next/framework-components/execution';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport {\n createSqlOperationRegistry,\n type SqlOperationDescriptors,\n} from '@prisma-next/sql-operations';\nimport type {\n Adapter,\n AnyQueryAst,\n Codec,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecInstanceContext,\n SqlDriver,\n} from '@prisma-next/sql-relational-core/ast';\nimport { buildCodecDescriptorRegistry } from '@prisma-next/sql-relational-core/codec-descriptor-registry';\nimport type {\n AppliedMutationDefault,\n CodecDescriptorRegistry,\n ExecutionContext,\n MutationDefaultsOptions,\n TypeHelperRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Runtime parameterized codec descriptor.\n *\n * The unified `CodecDescriptor<P>` shape applied to parameterized codecs — `paramsSchema: StandardSchemaV1<P>` for JSON-boundary validation, `factory: (P) => (CodecInstanceContext) => Codec` for the curried higher-order codec. The factory is called once per `storage.types` instance (or once per inline-`typeParams` column); per-instance state lives in the closure.\n *\n * Codec-registry-unification spec § Decision.\n */\nexport type RuntimeParameterizedCodecDescriptor<P = Record<string, unknown>> = CodecDescriptor<P>;\n\n/**\n * Contributor protocol for SQL components (target, adapter, extension pack). The unified `codecs:` slot returns the full {@link CodecDescriptor} list — non-parameterized and parameterized descriptors live side-by-side in the same array. The framework dispatches every codec id through the unified descriptor map without branching on parameterization.\n */\nexport interface SqlStaticContributions {\n readonly codecs: () => ReadonlyArray<AnyCodecDescriptor>;\n readonly queryOperations?: () => SqlOperationDescriptors;\n readonly mutationDefaultGenerators?: () => ReadonlyArray<RuntimeMutationDefaultGenerator>;\n}\n\n/**\n * Scope across which a generator's value is constant.\n *\n * - `'field'` — one value per defaulting site (one column, one row). Cache strategy: no cache; call per defaulting site. Right for per-row identifiers (UUIDs, CUIDs, ULIDs, nanoid, ksuid).\n * - `'row'` — one value across all defaulting sites of one row of one operation. Cache strategy: per-call cache keyed by `generatorId`. Right for correlation ids stamped into multiple columns of one row.\n * - `'query'` — one value across all rows and columns of one ORM operation. Cache strategy: caller-provided cache keyed by `generatorId`. Right for `timestampNow` (a single timestamp per bulk insert/update).\n */\nexport type GeneratorStability = 'field' | 'row' | 'query';\n\nexport interface RuntimeMutationDefaultGenerator {\n readonly id: string;\n readonly generate: (params?: Record<string, unknown>) => unknown;\n /**\n * Scope across which the generator's value is constant. The framework derives the cache strategy from this declaration; generator authors never need to know about cache keys. See `GeneratorStability` for the per-value semantics.\n */\n readonly stability: GeneratorStability;\n}\n\nexport interface SqlRuntimeTargetDescriptor<\n TTargetId extends string = string,\n TTargetInstance extends RuntimeTargetInstance<'sql', TTargetId> = RuntimeTargetInstance<\n 'sql',\n TTargetId\n >,\n> extends RuntimeTargetDescriptor<'sql', TTargetId, TTargetInstance>,\n SqlStaticContributions {}\n\nexport interface SqlRuntimeAdapterDescriptor<\n TTargetId extends string = string,\n TAdapterInstance extends RuntimeAdapterInstance<\n 'sql',\n TTargetId\n > = SqlRuntimeAdapterInstance<TTargetId>,\n> extends RuntimeAdapterDescriptor<'sql', TTargetId, TAdapterInstance>,\n SqlStaticContributions {}\n\nexport interface SqlRuntimeExtensionDescriptor<TTargetId extends string = string>\n extends RuntimeExtensionDescriptor<'sql', TTargetId, SqlRuntimeExtensionInstance<TTargetId>>,\n SqlStaticContributions {\n create(): SqlRuntimeExtensionInstance<TTargetId>;\n}\n\nexport interface SqlExecutionStack<TTargetId extends string = string> {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId>;\n readonly extensionPacks: readonly SqlRuntimeExtensionDescriptor<TTargetId>[];\n}\n\nexport type SqlExecutionStackWithDriver<TTargetId extends string = string> = Omit<\n ExecutionStack<\n 'sql',\n TTargetId,\n SqlRuntimeAdapterInstance<TTargetId>,\n SqlRuntimeDriverInstance<TTargetId>,\n SqlRuntimeExtensionInstance<TTargetId>\n >,\n 'target' | 'adapter' | 'driver' | 'extensionPacks'\n> & {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId, SqlRuntimeAdapterInstance<TTargetId>>;\n readonly driver:\n | RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>\n | undefined;\n readonly extensionPacks: readonly SqlRuntimeExtensionDescriptor<TTargetId>[];\n};\n\nexport interface SqlRuntimeExtensionInstance<TTargetId extends string>\n extends RuntimeExtensionInstance<'sql', TTargetId> {}\n\nexport type SqlRuntimeAdapterInstance<TTargetId extends string = string> = RuntimeAdapterInstance<\n 'sql',\n TTargetId\n> &\n Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n\n/**\n * NOTE: Binding type is intentionally erased to unknown at this shared runtime layer. Target clients (for example `postgres()`) validate and construct the concrete binding before calling `driver.connect(binding)`, which keeps runtime behavior safe today. A future follow-up can preserve TBinding through stack/context generics end-to-end.\n */\nexport type SqlRuntimeDriverInstance<TTargetId extends string = string> = RuntimeDriverInstance<\n 'sql',\n TTargetId\n> &\n SqlDriver<unknown>;\n\nexport function createSqlExecutionStack<TTargetId extends string>(options: {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId>;\n readonly driver?:\n | RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>\n | undefined;\n readonly extensionPacks?: readonly SqlRuntimeExtensionDescriptor<TTargetId>[] | undefined;\n}): SqlExecutionStackWithDriver<TTargetId> {\n return createExecutionStack({\n target: options.target,\n adapter: options.adapter,\n driver: options.driver,\n extensionPacks: options.extensionPacks,\n });\n}\n\nexport type { ExecutionContext, TypeHelperRegistry };\n\nexport function assertExecutionStackContractRequirements(\n contract: Contract<SqlStorage>,\n stack: SqlExecutionStack,\n): void {\n const providedComponentIds = new Set<string>([\n stack.target.id,\n stack.adapter.id,\n ...stack.extensionPacks.map((pack) => pack.id),\n ]);\n\n const result = checkContractComponentRequirements({\n contract,\n expectedTargetFamily: 'sql',\n expectedTargetId: stack.target.targetId,\n providedComponentIds,\n });\n\n if (result.familyMismatch) {\n throw runtimeError(\n 'RUNTIME.CONTRACT_FAMILY_MISMATCH',\n `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`,\n {\n actual: result.familyMismatch.actual,\n expected: result.familyMismatch.expected,\n },\n );\n }\n\n if (result.targetMismatch) {\n throw runtimeError(\n 'RUNTIME.CONTRACT_TARGET_MISMATCH',\n `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`,\n {\n actual: result.targetMismatch.actual,\n expected: result.targetMismatch.expected,\n },\n );\n }\n\n if (result.missingExtensionPackIds.length > 0) {\n const packIds = result.missingExtensionPackIds;\n const packList = packIds.map((id) => `'${id}'`).join(', ');\n throw runtimeError(\n 'RUNTIME.MISSING_EXTENSION_PACK',\n `Contract requires extension pack(s) ${packList}, but runtime descriptors do not provide matching component(s).`,\n { packIds },\n );\n }\n}\n\nfunction validateTypeParams(\n typeParams: Record<string, unknown>,\n descriptor: RuntimeParameterizedCodecDescriptor,\n context: { typeName?: string; tableName?: string; columnName?: string },\n): Record<string, unknown> {\n const result = descriptor.paramsSchema['~standard'].validate(typeParams);\n if (result instanceof Promise) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `paramsSchema for codec '${descriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,\n { ...context, codecId: descriptor.codecId, typeParams },\n );\n }\n if (result.issues) {\n const messages = result.issues.map((issue) => issue.message).join('; ');\n const locationInfo = context.typeName\n ? `type '${context.typeName}'`\n : `column '${context.tableName}.${context.columnName}'`;\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Invalid typeParams for ${locationInfo} (codecId: ${descriptor.codecId}): ${messages}`,\n { ...context, codecId: descriptor.codecId, typeParams },\n );\n }\n return result.value as Record<string, unknown>;\n}\n\n/**\n * Collect every {@link CodecDescriptor} contributed by the SQL stack and partition into \"parameterized\" vs \"non-parameterized\" via the descriptor's own {@link CodecDescriptorImpl.isParameterized} getter. The getter is the canonical discriminator — a `paramsSchema` identity check would misroute any descriptor that doesn't reuse the exact `voidParamsSchema` singleton (e.g. a non-parameterized codec authoring its own no-op schema).\n *\n * The unified descriptor list collapses the legacy split (a separate slot used to register parameterized codecs) — every codec id resolves through the same map (codec-registry-unification spec § Decision).\n */\nfunction collectCodecDescriptors(contributors: ReadonlyArray<SqlStaticContributions>): {\n readonly all: ReadonlyArray<AnyCodecDescriptor>;\n readonly parameterized: Map<string, RuntimeParameterizedCodecDescriptor>;\n} {\n const all: AnyCodecDescriptor[] = [];\n const parameterized = new Map<string, RuntimeParameterizedCodecDescriptor>();\n const seen = new Set<string>();\n\n for (const contributor of contributors) {\n for (const descriptor of contributor.codecs()) {\n if (seen.has(descriptor.codecId)) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_CODEC',\n `Duplicate codec descriptor for codecId '${descriptor.codecId}'.`,\n { codecId: descriptor.codecId },\n );\n }\n seen.add(descriptor.codecId);\n all.push(descriptor);\n\n if (descriptor.isParameterized) {\n // Cast widens the descriptor's heterogeneous `P` to the runtime alias surface; consumers narrow per codec id at the dispatch site, where the descriptor's own `paramsSchema` validates JSON-sourced params before the factory ever sees them.\n parameterized.set(\n descriptor.codecId,\n descriptor as unknown as RuntimeParameterizedCodecDescriptor,\n );\n }\n }\n }\n\n return { all, parameterized };\n}\n\nfunction collectTypeRefSites(\n storage: SqlStorage,\n): Map<string, Array<{ readonly table: string; readonly column: string }>> {\n const sites = new Map<string, Array<{ readonly table: string; readonly column: string }>>();\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (typeof column.typeRef !== 'string') continue;\n const list = sites.get(column.typeRef);\n const entry = { table: tableName, column: columnName };\n if (list) {\n list.push(entry);\n } else {\n sites.set(column.typeRef, [entry]);\n }\n }\n }\n return sites;\n}\n\nfunction initializeTypeHelpers(\n storage: SqlStorage,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): TypeHelperRegistry {\n const helpers: TypeHelperRegistry = {};\n const storageTypes = storage.types;\n\n if (!storageTypes) {\n return helpers;\n }\n\n const typeRefSites = collectTypeRefSites(storage);\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes)) {\n const descriptor = codecDescriptors.get(typeInstance.codecId);\n\n if (!descriptor) {\n // No parameterized descriptor for this codec id — store the raw type instance for callers that need typeParams metadata.\n helpers[typeName] = typeInstance;\n continue;\n }\n\n const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, {\n typeName,\n });\n\n const usedAt = typeRefSites.get(typeName) ?? [];\n const ctx: SqlCodecInstanceContext = { name: typeName, usedAt };\n helpers[typeName] = descriptor.factory(validatedParams)(ctx);\n }\n\n return helpers;\n}\n\nfunction validateColumnTypeParams(\n storage: SqlStorage,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): void {\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeParams) {\n const descriptor = codecDescriptors.get(column.codecId);\n if (descriptor) {\n validateTypeParams(column.typeParams, descriptor, { tableName, columnName });\n }\n }\n }\n }\n}\n\nfunction isResolvedCodec(candidate: unknown): candidate is Codec {\n return (\n candidate !== null &&\n typeof candidate === 'object' &&\n 'id' in candidate &&\n 'decode' in candidate\n );\n}\n\n/**\n * Walk the contract's `storage.tables[].columns[]` and resolve each column to a `Codec` through the unified descriptor map. Per-instance behavior:\n *\n * - **typeRef columns**: reuse the resolved codec materialized once by `initializeTypeHelpers` for the `storage.types` entry. Multiple columns sharing one typeRef share one codec instance.\n * - **inline-typeParams columns**: call `descriptor.factory(typeParams) (ctx)` once per column (per-column anonymous instance).\n * - **non-parameterized columns**: call `descriptor.factory()(ctx)` once. The synthesized descriptor's factory is constant — every call returns the same shared codec instance — so columns sharing a non-parameterized codec id share one resolved codec without explicit caching.\n *\n * Codec-registry-unification spec § AC-4: every column resolves through one descriptor map without branching on parameterization. JSON-Schema validation, when required, lives inside the resolved codec's `decode` body (see `arktype-json`'s `ArktypeJsonCodecClass`); the framework no longer maintains a parallel validator registry.\n */\nfunction buildContractCodecRegistry(\n contract: Contract<SqlStorage>,\n codecDescriptors: CodecDescriptorRegistry,\n types: TypeHelperRegistry,\n parameterizedDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): ContractCodecRegistry {\n const byColumn = new Map<string, Codec>();\n const byCodecId = new Map<string, Codec>();\n // Codec ids whose `byCodecId` entry is ambiguous — multiple distinct resolved instances landed under the same parameterized codec id (e.g. `Vector<1024>` and `Vector<1536>` both registering under `pg/vector@1`). The refs-less `forCodecId` fallback rejects these ids so a DSL-param without a column ref cannot silently bind to the wrong instance. The validator pass enforces refs on every parameterized `ParamRef`, so this\n // branch is reachable only as a defensive guard for non-parameterized columns whose `byCodecId` entry is unique by construction.\n const ambiguousCodecIds = new Set<string>();\n\n // Pre-populate `byCodecId` with non-parameterized descriptor instances. Refs-less encode/decode call sites (computed projections without a column ref, transient builder ParamRefs) resolve through `forCodecId(id)` and need a representative instance for codec ids that no contract column declares. Non-parameterized descriptors' factories are constant — every call yields the same shared codec — so a single materialization\n // is correct.\n for (const descriptor of codecDescriptors.values()) {\n if (descriptor.isParameterized) continue;\n const ctx: SqlCodecInstanceContext = {\n name: `<shared:${descriptor.codecId}>`,\n usedAt: [],\n };\n const voidFactory = descriptor.factory as unknown as (\n params: undefined,\n ) => (ctx: SqlCodecInstanceContext) => Codec;\n byCodecId.set(descriptor.codecId, voidFactory(undefined)(ctx));\n }\n\n // Representative instances for parameterized descriptors whose factory tolerates `factory(undefined)` (e.g. pgvector — the factory ignores its params and returns the same shared codec). Used as the last-resort fallback in `forCodecId` for refs-less call sites whose codec id has no contract column the walk could resolve through (e.g. `cosineSimilarity(col, [literal])` builds an inline `ParamRef` without column refs).\n // Stored separately so column-bound walk results don't trip the ambiguity check, and consulted only when `byCodecId` has no column-bound entry. Descriptors whose factory needs real params (arktype-json) raise and are skipped — the per-column dispatch path materializes those lazily when refs are populated.\n const parameterizedRepresentatives = new Map<string, Codec>();\n for (const descriptor of codecDescriptors.values()) {\n if (!descriptor.isParameterized) continue;\n const ctx: SqlCodecInstanceContext = {\n name: `<shared:${descriptor.codecId}>`,\n usedAt: [],\n };\n // Call `factory` *as a method on the descriptor* — `descriptor.factory(undefined)` — rather than detaching it into a local. Several descriptors implement `factory` as a class method whose body returns an arrow that captures `this` (`return () => new SomeCodec(this);`), and detaching loses that binding so the codec ends up with an `undefined` descriptor and `codec.id` throws.\n const factory = descriptor.factory.bind(descriptor) as unknown as (\n params: unknown,\n ) => (ctx: SqlCodecInstanceContext) => Codec;\n try {\n parameterizedRepresentatives.set(descriptor.codecId, factory(undefined)(ctx));\n } catch {\n // Parameterized descriptor whose factory requires real params; refs-less fallback for this codec id is unavailable.\n }\n }\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n const columnKey = `${tableName}.${columnName}`;\n const descriptor = codecDescriptors.descriptorFor(column.codecId);\n\n let resolvedCodec: Codec | undefined;\n\n if (descriptor) {\n const isParameterized = parameterizedDescriptors.has(column.codecId);\n\n if (column.typeRef) {\n // The named instance was already materialized once by `initializeTypeHelpers`; reuse it so multiple columns sharing the same typeRef share one codec instance (and any per-instance helper state on it).\n const helper = types[column.typeRef];\n if (isResolvedCodec(helper)) {\n resolvedCodec = helper;\n }\n } else if (column.typeParams && isParameterized) {\n const parameterizedDescriptor = parameterizedDescriptors.get(column.codecId);\n if (parameterizedDescriptor) {\n const validatedParams = validateTypeParams(column.typeParams, parameterizedDescriptor, {\n tableName,\n columnName,\n });\n const ctx: SqlCodecInstanceContext = {\n name: `<col:${tableName}.${columnName}>`,\n usedAt: [{ table: tableName, column: columnName }],\n };\n resolvedCodec = parameterizedDescriptor.factory(validatedParams)(ctx);\n }\n } else if (!isParameterized) {\n // Non-parameterized column: materialize a fresh codec instance per `forColumn(table, column)` entry with a column-specific `SqlCodecInstanceContext`. The pre-populated `byCodecId` representative (built with the synthetic `<shared:codecId>` context and empty `usedAt`) is reserved for `forCodecId()` refs-less fallbacks; reusing it for column-bound dispatch would erase per-column diagnostics for any descriptor whose factory reads `CodecInstanceContext`.\n const ctx: SqlCodecInstanceContext = {\n name: `<col:${tableName}.${columnName}>`,\n usedAt: [{ table: tableName, column: columnName }],\n };\n // The descriptor's `P` is `void` for non-parameterized codecs; the runtime's `void` value is `undefined`. The cast narrows the descriptor's family-agnostic `CodecInstanceContext` slot to the SQL `SqlCodecInstanceContext` we pass at this call site — function-argument contravariance makes the narrow safe.\n // `bind` preserves the `this`-on-descriptor invariant — several descriptors implement `factory` as a class method whose body returns an arrow that captures `this`; detaching loses the binding and produces a codec whose `descriptor` is `undefined`.\n const voidFactory = descriptor.factory.bind(descriptor) as unknown as (\n params: undefined,\n ) => (ctx: SqlCodecInstanceContext) => Codec;\n resolvedCodec = voidFactory(undefined)(ctx);\n }\n // else: parameterized codec id with no typeRef and no typeParams — this is the legitimate \"undimensioned\" form for codecs that ship a no-params column variant alongside a parameterized one (e.g. pgvector's `vectorColumn` vs. `vector(N)`). Leave `resolvedCodec` undefined; encode/decode for this column flows through `forCodecId`. The fallback works for these cases because their wire format is params-independent (vector\n // formats `[v1,v2,...]` regardless of declared length).\n }\n\n if (resolvedCodec) {\n byColumn.set(columnKey, resolvedCodec);\n const existing = byCodecId.get(column.codecId);\n if (existing === undefined) {\n byCodecId.set(column.codecId, resolvedCodec);\n } else if (existing !== resolvedCodec && parameterizedDescriptors.has(column.codecId)) {\n ambiguousCodecIds.add(column.codecId);\n }\n }\n }\n }\n\n const registry: ContractCodecRegistry = {\n forColumn(table, column) {\n return byColumn.get(`${table}.${column}`);\n },\n forCodecId(codecId) {\n // Codec-id-only fallback for refs-less sites. The validator pass (`validateParamRefRefs`) enforces refs on every parameterized `ParamRef` before encode, so this path is only legitimately reachable for non-parameterized codec ids. The map is pre-populated with every non-parameterized descriptor's canonical instance and overlaid with column-resolved instances from the contract walk; parameterized codec ids without a\n // typeRef/typeParams-bound column never reach this map.\n //\n // Reject ambiguous parameterized fallbacks: if the contract walk resolved more than one distinct codec instance under this id (e.g. multiple vector dimensions, multiple arktype-json schemas), the codec-id-keyed lookup cannot honor the call site — fail fast rather than bind to whichever instance happened to land first.\n if (ambiguousCodecIds.has(codecId)) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Codec '${codecId}' resolves to multiple parameterized instances; column-aware dispatch is required.`,\n { codecId },\n );\n }\n return byCodecId.get(codecId) ?? parameterizedRepresentatives.get(codecId);\n },\n };\n\n return registry;\n}\n\nfunction assertMutationDefaultGeneratorsAvailable(\n contract: Contract<SqlStorage>,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n): void {\n const defaults = contract.execution?.mutations.defaults ?? [];\n if (defaults.length === 0) return;\n\n const missing = new Set<string>();\n for (const mutationDefault of defaults) {\n for (const phase of [mutationDefault.onCreate, mutationDefault.onUpdate]) {\n if (!phase) continue;\n if (phase.kind === 'generator' && !generatorRegistry.has(phase.id)) {\n missing.add(phase.id);\n }\n }\n }\n\n if (missing.size === 0) return;\n\n const ids = Array.from(missing);\n const idList = ids.map((id) => `'${id}'`).join(', ');\n throw runtimeError(\n 'RUNTIME.MISSING_MUTATION_DEFAULT_GENERATOR',\n `Contract requires mutation default generator(s) ${idList}, but no runtime component provides them.`,\n { ids },\n );\n}\n\nfunction collectMutationDefaultGenerators(\n contributors: ReadonlyArray<SqlStaticContributions & { readonly id: string }>,\n): ReadonlyMap<string, RuntimeMutationDefaultGenerator> {\n const generators = new Map<string, RuntimeMutationDefaultGenerator>();\n const owners = new Map<string, string>();\n\n for (const contributor of contributors) {\n const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];\n for (const generator of nextGenerators) {\n const existingOwner = owners.get(generator.id);\n if (existingOwner !== undefined) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR',\n `Duplicate mutation default generator '${generator.id}'.`,\n {\n id: generator.id,\n existingOwner,\n incomingOwner: contributor.id,\n },\n );\n }\n generators.set(generator.id, generator);\n owners.set(generator.id, contributor.id);\n }\n }\n\n return generators;\n}\n\nfunction computeExecutionDefaultValue(\n spec: ExecutionMutationDefaultValue,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n): unknown {\n switch (spec.kind) {\n case 'generator': {\n const generator = generatorRegistry.get(spec.id);\n if (!generator) {\n throw runtimeError(\n 'RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING',\n `Contract references mutation default generator '${spec.id}' but no runtime component provides it.`,\n {\n id: spec.id,\n },\n );\n }\n // nosemgrep: javascript.express.security.express-wkhtml-injection.express-wkhtmltoimage-injection\n return generator.generate(spec.params);\n }\n }\n}\n\nfunction applyMutationDefaults(\n contract: Contract<SqlStorage>,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n options: MutationDefaultsOptions,\n): ReadonlyArray<AppliedMutationDefault> {\n const defaults = contract.execution?.mutations.defaults ?? [];\n if (defaults.length === 0) {\n return [];\n }\n\n const isEmptyUpdate = options.op === 'update' && Object.keys(options.values).length === 0;\n\n const applied: AppliedMutationDefault[] = [];\n const appliedColumns = new Set<string>();\n // Fresh per-call cache for `stability: 'row'` generators — they share across columns of a single row but regenerate on the next call.\n const rowCache = new Map<string, unknown>();\n\n for (const mutationDefault of defaults) {\n if (mutationDefault.ref.table !== options.table) {\n continue;\n }\n\n const defaultSpec =\n options.op === 'create' ? mutationDefault.onCreate : mutationDefault.onUpdate;\n if (!defaultSpec) {\n continue;\n }\n\n // RD2: empty update payloads skip onUpdate defaults — no write means no `@updatedAt` advance.\n if (isEmptyUpdate) {\n continue;\n }\n\n const columnName = mutationDefault.ref.column;\n if (Object.hasOwn(options.values, columnName) || appliedColumns.has(columnName)) {\n continue;\n }\n\n applied.push({\n column: columnName,\n value: resolveScopedValue(\n defaultSpec,\n generatorRegistry,\n rowCache,\n options.defaultValueCache,\n ),\n });\n appliedColumns.add(columnName);\n }\n\n return applied;\n}\n\nfunction resolveScopedValue(\n spec: ExecutionMutationDefaultValue,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n rowCache: Map<string, unknown>,\n queryCache: Map<string, unknown> | undefined,\n): unknown {\n if (spec.kind !== 'generator') {\n return computeExecutionDefaultValue(spec, generatorRegistry);\n }\n const generator = generatorRegistry.get(spec.id);\n const cache = scopedCache(generator?.stability, rowCache, queryCache);\n if (!cache) {\n return computeExecutionDefaultValue(spec, generatorRegistry);\n }\n if (cache.has(spec.id)) {\n return cache.get(spec.id);\n }\n const value = computeExecutionDefaultValue(spec, generatorRegistry);\n cache.set(spec.id, value);\n return value;\n}\n\nfunction scopedCache(\n stability: GeneratorStability | undefined,\n rowCache: Map<string, unknown>,\n queryCache: Map<string, unknown> | undefined,\n): Map<string, unknown> | undefined {\n switch (stability) {\n case 'row':\n return rowCache;\n case 'query':\n return queryCache;\n default:\n return undefined;\n }\n}\n\nexport function createExecutionContext<\n TContract extends Contract<SqlStorage> = Contract<SqlStorage>,\n TTargetId extends string = string,\n>(options: {\n readonly contract: TContract;\n readonly stack: SqlExecutionStack<TTargetId>;\n}): ExecutionContext<TContract> {\n const { contract, stack } = options;\n\n assertExecutionStackContractRequirements(contract, stack);\n\n const contributors: Array<SqlStaticContributions & ComponentDescriptor<string>> = [\n stack.target,\n stack.adapter,\n ...stack.extensionPacks,\n ];\n\n const { all: allCodecDescriptors, parameterized: parameterizedCodecDescriptors } =\n collectCodecDescriptors(contributors);\n\n const queryOperationRegistry = createSqlOperationRegistry();\n for (const contributor of contributors) {\n const ops = contributor.queryOperations?.() ?? {};\n for (const [name, op] of Object.entries(ops)) {\n queryOperationRegistry.register(name, op);\n }\n }\n\n const codecDescriptors = buildCodecDescriptorRegistry(allCodecDescriptors);\n const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);\n assertMutationDefaultGeneratorsAvailable(contract, mutationDefaultGeneratorRegistry);\n\n if (parameterizedCodecDescriptors.size > 0) {\n validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);\n }\n\n const types = initializeTypeHelpers(contract.storage, parameterizedCodecDescriptors);\n\n const contractCodecs = buildContractCodecRegistry(\n contract,\n codecDescriptors,\n types,\n parameterizedCodecDescriptors,\n );\n\n return {\n contract,\n contractCodecs,\n codecDescriptors,\n queryOperations: queryOperationRegistry,\n types,\n applyMutationDefaults: (options) =>\n applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options),\n };\n}\n","import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport type { MarkerStatement } from '@prisma-next/sql-relational-core/ast';\n\nexport { APP_SPACE_ID };\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport interface WriteMarkerInput {\n /**\n * Logical space identifier for this marker row. Required at every\n * call site so the type system surfaces every place that needs to\n * thread the value (rather than letting an `?? APP_SPACE_ID`\n * fall-through silently collapse multi-space markers onto the\n * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}\n * (`'app'`); per-extension callers pass the extension's space id.\n */\n readonly space: string;\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number;\n readonly appTag?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Applied-invariants set on the marker.\n *\n * - `undefined` → existing column left untouched. Sign and\n * verify-database paths use this; they don't accumulate invariants.\n * - explicit value (including `[]`) → column overwritten with\n * exactly that value.\n */\n readonly invariants?: readonly string[];\n}\n\nexport const ensureSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\n/**\n * Schema for `prisma_contract.marker`. The `space text` primary key\n * supports one row per loaded contract space (`'app'`,\n * `'<extension-id>'`, …); brand-new databases create this shape\n * directly. Pre-1.0 single-row markers (no `space` column) are not\n * auto-migrated — the target-specific migration runner detects the\n * legacy shape at boot and surfaces a structured `LEGACY_MARKER_SHAPE`\n * failure pointing the operator at re-running `dbInit`.\n *\n * @see specs/framework-mechanism.spec.md § 2.\n */\nexport const ensureTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n space text not null primary key default '${APP_SPACE_ID}',\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}',\n invariants text[] not null default '{}'\n )`,\n params: [],\n};\n\nexport function readContractMarker(space: string): MarkerStatement {\n return {\n sql: `select\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta,\n invariants\n from prisma_contract.marker\n where space = $1`,\n params: [space],\n };\n}\n\nexport interface WriteContractMarkerStatements {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n}\n\n/**\n * Variable columns that participate in INSERT/UPDATE alongside the\n * always-on `space = $1` and `updated_at = now()`. Each column declares\n * its name, optional cast type, and parameter value; the placeholder\n * (`$N`) is computed positionally below — adding or reordering a\n * column doesn't desync indices. `invariants` only appears when the\n * caller supplies it — see `WriteMarkerInput.invariants`.\n */\nfunction markerColumns(\n input: WriteMarkerInput,\n): ReadonlyArray<{ readonly name: string; readonly type?: string; readonly param: unknown }> {\n return [\n { name: 'core_hash', param: input.storageHash },\n { name: 'profile_hash', param: input.profileHash },\n { name: 'contract_json', type: 'jsonb', param: input.contractJson ?? null },\n { name: 'canonical_version', param: input.canonicalVersion ?? null },\n { name: 'app_tag', param: input.appTag ?? null },\n { name: 'meta', type: 'jsonb', param: JSON.stringify(input.meta ?? {}) },\n ...(input.invariants !== undefined\n ? [{ name: 'invariants' as const, type: 'text[]' as const, param: input.invariants }]\n : []),\n ];\n}\n\nexport function writeContractMarker(input: WriteMarkerInput): WriteContractMarkerStatements {\n const cols = markerColumns(input);\n // $1 is reserved for `space`; subsequent positions follow the order of cols.\n const placed = cols.map((c, i) => ({\n name: c.name,\n expr: c.type ? `$${i + 2}::${c.type}` : `$${i + 2}`,\n param: c.param,\n }));\n const params: readonly unknown[] = [input.space, ...placed.map((c) => c.param)];\n\n // `updated_at = now()` is a SQL literal with no parameter slot, so it\n // sits outside `placed` and is appended directly to each statement.\n const insertColumns = ['space', ...placed.map((c) => c.name), 'updated_at'].join(', ');\n const insertValues = ['$1', ...placed.map((c) => c.expr), 'now()'].join(', ');\n const setClauses = [...placed.map((c) => `${c.name} = ${c.expr}`), 'updated_at = now()'].join(\n ', ',\n );\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (${insertColumns}) values (${insertValues})`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set ${setClauses} where space = $1`,\n params,\n },\n };\n}\n","import type { AnyFromSource, AnyQueryAst } from '@prisma-next/sql-relational-core/ast';\n\n/**\n * Build a map from query-local table aliases to their underlying source table names.\n *\n * Self-joins like `db.sql.post.as('p1').innerJoin(db.sql.post.as('p2'), …)` produce `ColumnRef`s whose `table` is the alias (`p1`, `p2`) — the SQL renderer needs the alias for `SELECT p1.id, …`. Codec dispatch keys `byColumn` by the underlying source table, so aliases must be resolved back to the source name for `forColumn(...)` to hit. Tables that already use their canonical name (no alias) are also entered so a single\n * lookup works for both shapes.\n */\nfunction buildAliasMap(ast: AnyQueryAst): ReadonlyMap<string, string> {\n const aliases = new Map<string, string>();\n const recordSource = (source: AnyFromSource): void => {\n if (source.kind === 'table-source') {\n const key = source.alias ?? source.name;\n aliases.set(key, source.name);\n } else {\n aliases.set(source.alias, source.alias);\n }\n };\n if (ast.kind === 'select') {\n recordSource(ast.from);\n for (const join of ast.joins ?? []) {\n recordSource(join.source);\n }\n } else if (ast.kind === 'raw-sql') {\n // Raw-SQL ASTs do not bind a single primary table — alias resolution\n // is driven by inline `IdentifierRef`s the caller embedded directly.\n } else {\n recordSource(ast.table);\n }\n return aliases;\n}\n\nexport function makeAliasResolver(ast: AnyQueryAst | undefined): (alias: string) => string {\n if (!ast) return (alias) => alias;\n const map = buildAliasMap(ast);\n return (alias) => map.get(alias) ?? alias;\n}\n","import {\n checkAborted,\n isRuntimeError,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport type {\n AnyQueryAst,\n Codec,\n ContractCodecRegistry,\n ProjectionItem,\n SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { makeAliasResolver } from './alias-resolver';\n\ntype ColumnRef = { table: string; column: string };\n\ninterface DecodeContext {\n readonly aliases: ReadonlyArray<string> | undefined;\n readonly codecs: ReadonlyMap<string, Codec>;\n readonly columnRefs: ReadonlyMap<string, ColumnRef>;\n readonly includeAliases: ReadonlySet<string>;\n}\n\nconst WIRE_PREVIEW_LIMIT = 100;\nconst EMPTY_INCLUDE_ALIASES: ReadonlySet<string> = new Set<string>();\n\nfunction isAstBackedPlan(\n plan: SqlExecutionPlan,\n): plan is SqlExecutionPlan & { readonly ast: AnyQueryAst } {\n return plan.ast !== undefined;\n}\n\nfunction projectionListFromAst(ast: AnyQueryAst): ReadonlyArray<ProjectionItem> | undefined {\n if (ast.kind === 'select') {\n return ast.projection;\n }\n if (ast.kind === 'raw-sql') {\n return undefined;\n }\n return ast.returning;\n}\n\n/**\n * Resolve the per-cell codec for a projection item.\n *\n * When a `(table, column)` ref is available — either implicit on a `column-ref` expression or carried explicitly via `item.refs` for column-bound non-`column-ref` projections — prefer `contractCodecs.forColumn(table, column)`: that returns the per-instance codec materialized from the descriptor's factory for that column, encoding any per-instance state (typeParams like vector length, schema validators, etc.).\n *\n * The wrong-instance risk for parameterized codecs is closed off structurally:\n *\n * 1. `buildContractCodecRegistry` pre-populates `byCodecId` with one canonical instance per non-parameterized descriptor; parameterized descriptors are intentionally absent. 2. `forCodecId` rejects ambiguous parameterized fallbacks (`ambiguousCodecIds`). 3. The non-ambiguous parameterized case stores the column-correct per-instance codec under `byCodecId`, so the fall-through still resolves to the right instance.\n *\n * The `forCodecId` fallback otherwise covers projections that are *not* column-bound (computed projections, raw SQL aliases) but still carry a `codecId` (ADR 205 stamps every `ProjectionItem` with the producer's codec id).\n *\n * Codec-registry-unification spec § AC-4 / AC-5.\n */\nfunction resolveProjectionCodec(\n item: ProjectionItem,\n contractCodecs: ContractCodecRegistry | undefined,\n aliasResolver: (alias: string) => string,\n): Codec | undefined {\n if (contractCodecs) {\n if (item.expr.kind === 'column-ref') {\n const byColumn = contractCodecs.forColumn(aliasResolver(item.expr.table), item.expr.column);\n // Only honour `byColumn` when its codec id agrees with `item.codecId`. They can legitimately disagree when an `OperationExpr`-shaped projection carries a single inner column-ref but transforms the value's codec (e.g. `cosineDistance(col, x)` projects `pg/float8@1` while the inner column-ref points at a `pg/vector@1` column).\n if (byColumn && (item.codecId === undefined || byColumn.id === item.codecId)) return byColumn;\n } else if (item.refs) {\n const byColumn = contractCodecs.forColumn(aliasResolver(item.refs.table), item.refs.column);\n if (byColumn && (item.codecId === undefined || byColumn.id === item.codecId)) return byColumn;\n }\n }\n if (item.codecId) {\n return contractCodecs?.forCodecId(item.codecId);\n }\n return undefined;\n}\n\nfunction buildDecodeContext(\n plan: SqlExecutionPlan,\n contractCodecs: ContractCodecRegistry | undefined,\n): DecodeContext {\n if (!isAstBackedPlan(plan)) {\n return {\n aliases: undefined,\n codecs: new Map(),\n columnRefs: new Map(),\n includeAliases: EMPTY_INCLUDE_ALIASES,\n };\n }\n\n const projection = projectionListFromAst(plan.ast);\n if (!projection) {\n return {\n aliases: undefined,\n codecs: new Map(),\n columnRefs: new Map(),\n includeAliases: EMPTY_INCLUDE_ALIASES,\n };\n }\n\n const aliases: string[] = [];\n const codecs = new Map<string, Codec>();\n const columnRefs = new Map<string, ColumnRef>();\n const includeAliases = new Set<string>();\n const aliasResolver = makeAliasResolver(plan.ast);\n\n for (const item of projection) {\n aliases.push(item.alias);\n\n const codec = resolveProjectionCodec(item, contractCodecs, aliasResolver);\n if (codec) {\n codecs.set(item.alias, codec);\n }\n\n if (item.expr.kind === 'column-ref') {\n columnRefs.set(item.alias, {\n table: aliasResolver(item.expr.table),\n column: item.expr.column,\n });\n } else if (item.refs) {\n columnRefs.set(item.alias, {\n table: aliasResolver(item.refs.table),\n column: item.refs.column,\n });\n } else if (item.expr.kind === 'subquery' || item.expr.kind === 'json-array-agg') {\n includeAliases.add(item.alias);\n }\n }\n\n return { aliases, codecs, columnRefs, includeAliases };\n}\n\nfunction previewWireValue(wireValue: unknown): string {\n if (typeof wireValue === 'string') {\n return wireValue.length > WIRE_PREVIEW_LIMIT\n ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...`\n : wireValue;\n }\n return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);\n}\n\nfunction wrapDecodeFailure(\n error: unknown,\n alias: string,\n ref: ColumnRef | undefined,\n codec: Codec,\n wireValue: unknown,\n): never {\n const message = error instanceof Error ? error.message : String(error);\n const target = ref ? `${ref.table}.${ref.column}` : alias;\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to decode column ${target} with codec '${codec.id}': ${message}`,\n {\n ...(ref ? { table: ref.table, column: ref.column } : { alias }),\n codec: codec.id,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nfunction wrapIncludeAggregateFailure(error: unknown, alias: string, wireValue: unknown): never {\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to parse JSON array for include alias '${alias}': ${message}`,\n {\n alias,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nfunction decodeIncludeAggregate(alias: string, wireValue: unknown): unknown {\n if (wireValue === null || wireValue === undefined) {\n return [];\n }\n\n try {\n let parsed: unknown;\n if (typeof wireValue === 'string') {\n parsed = JSON.parse(wireValue);\n } else if (Array.isArray(wireValue)) {\n parsed = wireValue;\n } else {\n parsed = JSON.parse(String(wireValue));\n }\n\n if (!Array.isArray(parsed)) {\n throw new Error(`Expected array for include alias '${alias}', got ${typeof parsed}`);\n }\n\n return parsed;\n } catch (error) {\n wrapIncludeAggregateFailure(error, alias, wireValue);\n }\n}\n\n/**\n * Decodes a single field. Single-armed: every cell takes the same path — `codec.decode → await → return plain value` — so sync- and async-authored codecs are indistinguishable to callers. JSON-Schema validation, when required, lives inside the resolved codec's `decode` body (e.g. `arktype-json` validates against its rehydrated schema and throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` from `decode` directly); there is\n * no separate validator-registry pass.\n *\n * The row-level `rowCtx` is repackaged into a per-cell `SqlCodecCallContext` whose `column = { table, name }` is a structural projection of the per-cell `ColumnRef = { table, column }` resolved from the AST-backed `DecodeContext` (the same resolution `wrapDecodeFailure` uses for envelope construction — one resolution per cell, two consumers). Cells the runtime cannot resolve to a single underlying column (aggregate\n * aliases, computed projections without a simple ref) get `column: undefined`, matching the spec contract that the runtime never silently defaults this field.\n */\nasync function decodeField(\n alias: string,\n wireValue: unknown,\n decodeCtx: DecodeContext,\n rowCtx: SqlCodecCallContext,\n): Promise<unknown> {\n if (wireValue === null) {\n return null;\n }\n\n const codec = decodeCtx.codecs.get(alias);\n if (!codec) {\n return wireValue;\n }\n\n const ref = decodeCtx.columnRefs.get(alias);\n\n // Per-cell ctx: the cell-level `column` is a `SqlColumnRef = { table, name }` projection of the resolved `ColumnRef = { table, column }` (same resolution `wrapDecodeFailure` uses below — no double work). Cells the runtime cannot resolve (aggregate aliases, computed projections without a simple ref) drop the `column` field entirely — explicitly cleared so a previously-populated `rowCtx.column` cannot leak through to\n // unrelated cells. Destructuring (rather than `column: undefined`) is required because `SqlCodecCallContext.column` is declared `column?: SqlColumnRef` under `exactOptionalPropertyTypes`.\n let cellCtx: SqlCodecCallContext;\n if (ref) {\n cellCtx = { ...rowCtx, column: { table: ref.table, name: ref.column } };\n } else {\n const { column: _drop, ...rowCtxWithoutColumn } = rowCtx;\n cellCtx = rowCtxWithoutColumn;\n }\n\n try {\n return await codec.decode(wireValue, cellCtx);\n } catch (error) {\n // Codec-authored runtime envelopes (e.g. `RUNTIME.DECODE_FAILED` thrown from inside the codec body, or `RUNTIME.ABORTED` raised via `CodecCallContext.signal` per ADR 207) carry their own per-codec context — wrapping them again would erase that context and coerce the abort intent into a generic decode failure. Pass them through unchanged; only foreign errors get the `wrapDecodeFailure` envelope.\n if (isRuntimeError(error)) {\n throw error;\n }\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n}\n\n/**\n * Decodes a row by dispatching all per-cell codec calls concurrently via `Promise.all`. Each cell follows the single-armed `decodeField` path. Failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column, codec }` (or `{ alias, codec }` when no column ref is resolvable) and the original error attached on `cause`.\n *\n * When `rowCtx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'decode' }`) before any `codec.decode` call is made.\n * - **Mid-flight aborts** race the per-cell `Promise.all` against the signal so the runtime returns promptly even when codec bodies ignore it. In-flight bodies that ignore the signal complete in the background (cooperative cancellation).\n * - Existing `RUNTIME.DECODE_FAILED` envelopes from codec bodies pass through unchanged (no double wrap).\n */\nexport async function decodeRow(\n row: Record<string, unknown>,\n plan: SqlExecutionPlan,\n rowCtx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<Record<string, unknown>> {\n checkAborted(rowCtx, 'decode');\n const signal = rowCtx.signal;\n\n const decodeCtx = buildDecodeContext(plan, contractCodecs);\n\n const aliases = decodeCtx.aliases ?? Object.keys(row);\n\n if (decodeCtx.aliases !== undefined) {\n for (const alias of decodeCtx.aliases) {\n if (!Object.hasOwn(row, alias)) {\n throw runtimeError('RUNTIME.DECODE_FAILED', `Row missing projection alias \"${alias}\"`, {\n alias,\n expectedAliases: decodeCtx.aliases,\n presentKeys: Object.keys(row),\n });\n }\n }\n }\n\n const tasks: Promise<unknown>[] = [];\n const includeIndices: { index: number; alias: string; value: unknown }[] = [];\n\n for (let i = 0; i < aliases.length; i++) {\n const alias = aliases[i] as string;\n const wireValue = row[alias];\n\n if (decodeCtx.includeAliases.has(alias)) {\n includeIndices.push({ index: i, alias, value: wireValue });\n tasks.push(Promise.resolve(undefined));\n continue;\n }\n\n tasks.push(decodeField(alias, wireValue, decodeCtx, rowCtx));\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'decode');\n\n // Include aggregates are decoded synchronously after concurrent codec dispatch settles, so any decode failures upstream propagate first.\n for (const entry of includeIndices) {\n settled[entry.index] = decodeIncludeAggregate(entry.alias, entry.value);\n }\n\n const decoded: Record<string, unknown> = {};\n for (let i = 0; i < aliases.length; i++) {\n decoded[aliases[i] as string] = settled[i];\n }\n return decoded;\n}\n","import {\n checkAborted,\n isRuntimeError,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport {\n type Codec,\n type ContractCodecRegistry,\n collectOrderedParamRefs,\n type ParamRefBindingRefs,\n type SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { makeAliasResolver } from './alias-resolver';\n\ninterface ParamMetadata {\n readonly codecId: string | undefined;\n readonly name: string | undefined;\n readonly refs: ParamRefBindingRefs | undefined;\n}\n\nconst NO_METADATA: ParamMetadata = Object.freeze({\n codecId: undefined,\n name: undefined,\n refs: undefined,\n});\n\n/**\n * Resolve the codec for an outgoing param.\n *\n * Column-aware dispatch: when `metadata.refs` is populated by a column-bound construction site, prefer `contractCodecs.forColumn(refs.table, refs.column)` — that returns the per-instance codec the contract walk materialized for the `(table, column)` pair, encoding the column's typeParams (e.g. `vector(1024)` vs. `vector(1536)`).\n *\n * On a column-lookup miss the resolver falls through to `forCodecId`. The wrong-instance risk for parameterized codecs is closed off structurally:\n *\n * 1. `buildContractCodecRegistry` pre-populates `byCodecId` with one canonical instance per non-parameterized descriptor; parameterized descriptors are intentionally absent from this pre-population. 2. `forCodecId` rejects ambiguous parameterized fallbacks (`ambiguousCodecIds`) — if the contract walk resolved more than one distinct instance under a single parameterized id, the call throws rather than binding to\n * whichever landed first. 3. For the non-ambiguous parameterized case (a single column with that id), `byCodecId` stores the column-correct per-instance codec, so the fall-through still resolves to the right instance.\n *\n * Refs-less fallback: ParamRefs constructed outside a column-bound site (literals, transient builder state) carry a non-parameterized `codecId` whose dispatch is ambiguity-free. The validator pass (`validateParamRefRefs`) already enforced refs on every parameterized ParamRef before encode runs.\n */\nfunction resolveParamCodec(\n metadata: ParamMetadata,\n contractCodecs: ContractCodecRegistry | undefined,\n aliasResolver: (alias: string) => string,\n): Codec | undefined {\n if (!metadata.codecId) return undefined;\n if (metadata.refs && contractCodecs) {\n const byColumn = contractCodecs.forColumn(\n aliasResolver(metadata.refs.table),\n metadata.refs.column,\n );\n // Only honour `byColumn` when its codec id agrees with the `ParamRef`'s declared `codecId`. They can legitimately disagree when a heuristic (e.g. the ORM's `refsFromLeft`) lifts column refs out of an `OperationExpr` that changed the codec id — e.g. `cosineDistance(p.embedding, x).lt(1)` carries `refs={post,embedding}` (a vector column) but the comparison side's codec is `pg/float8@1`. Trusting `byColumn` blindly would dispatch the float\n // literal through the vector codec.\n if (byColumn && byColumn.id === metadata.codecId) return byColumn;\n }\n return contractCodecs?.forCodecId(metadata.codecId);\n}\n\nfunction paramLabel(metadata: ParamMetadata, paramIndex: number): string {\n return metadata.name ?? `param[${paramIndex}]`;\n}\n\nfunction wrapEncodeFailure(\n error: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\n codecId: string,\n): never {\n const label = paramLabel(metadata, paramIndex);\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.ENCODE_FAILED',\n `Failed to encode parameter ${label} with codec '${codecId}': ${message}`,\n { label, codec: codecId, paramIndex },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\n/**\n * Encodes a single parameter through its codec. Always awaits codec.encode so a Promise can never leak into the driver, even if a sync-authored codec is lifted to async by the codec factory. Failures are wrapped in `RUNTIME.ENCODE_FAILED` with `{ label, codec, paramIndex }` and the original error attached on `cause`.\n *\n * `ctx` is forwarded verbatim to `codec.encode` so codec authors who opt into the `(value, ctx)` arity see the same `SqlCodecCallContext` the runtime built for the surrounding `runtime.execute()` call. The ctx is always present; its `signal` field may be `undefined`. Encode call sites do not populate `ctx.column` — encode-time column context is the middleware's domain.\n */\nexport async function encodeParam(\n value: unknown,\n paramRef: {\n readonly codecId?: string;\n readonly name?: string;\n readonly refs?: ParamRefBindingRefs;\n },\n paramIndex: number,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<unknown> {\n return encodeParamValue(\n value,\n { codecId: paramRef.codecId, name: paramRef.name, refs: paramRef.refs },\n paramIndex,\n ctx,\n contractCodecs,\n (alias) => alias,\n );\n}\n\nasync function encodeParamValue(\n value: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\n ctx: SqlCodecCallContext,\n contractCodecs: ContractCodecRegistry | undefined,\n aliasResolver: (alias: string) => string,\n): Promise<unknown> {\n if (value === null || value === undefined) {\n return null;\n }\n\n const codec = resolveParamCodec(metadata, contractCodecs, aliasResolver);\n if (!codec) {\n return value;\n }\n\n try {\n return await codec.encode(value, ctx);\n } catch (error) {\n // Any `runtimeError`-built envelope is stable by construction — let\n // it pass through unchanged. This covers codec-authored\n // `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` (per-library JSON-with-\n // schema codecs validate inside `encode` per ADR 208 § Case J),\n // codec-authored `RUNTIME.ENCODE_FAILED` (no double wrap), and any\n // future stable code thrown from a codec body. Symmetric with the\n // decode-side guard.\n if (isRuntimeError(error)) throw error;\n wrapEncodeFailure(error, metadata, paramIndex, codec.id);\n }\n}\n\n/**\n * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-and async-authored codecs share the same path: `codec.encode → await → return`. Param-level failures are wrapped in `RUNTIME.ENCODE_FAILED`.\n *\n * When `ctx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'encode' }`) before any `codec.encode` call is made — codecs can pin this with a per-call counter that stays at zero.\n * - **Mid-flight abort** races the per-param `Promise.all` against `abortable(ctx.signal)`. The runtime returns `RUNTIME.ABORTED` promptly even if codec bodies ignore the signal; the in-flight bodies are abandoned and run to completion in the background (cooperative cancellation, see ADR 204).\n * - Existing `RUNTIME.ENCODE_FAILED` envelopes that surface from a codec body before the runtime observes the abort pass through unchanged (no double wrap).\n */\nexport async function encodeParams(\n plan: SqlExecutionPlan,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<readonly unknown[]> {\n checkAborted(ctx, 'encode');\n const signal = ctx.signal;\n\n if (plan.params.length === 0) {\n return plan.params;\n }\n\n const paramCount = plan.params.length;\n const metadata: ParamMetadata[] = new Array(paramCount).fill(NO_METADATA);\n\n if (plan.ast) {\n const refs = collectOrderedParamRefs(plan.ast);\n for (let i = 0; i < paramCount && i < refs.length; i++) {\n const ref = refs[i];\n if (ref) {\n metadata[i] = { codecId: ref.codecId, name: ref.name, refs: ref.refs };\n }\n }\n }\n\n const aliasResolver = makeAliasResolver(plan.ast);\n\n const tasks: Promise<unknown>[] = new Array(paramCount);\n for (let i = 0; i < paramCount; i++) {\n tasks[i] = encodeParamValue(\n plan.params[i],\n metadata[i] ?? NO_METADATA,\n i,\n ctx,\n contractCodecs,\n aliasResolver,\n );\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'encode');\n return Object.freeze(settled);\n}\n","import type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { canonicalStringify } from '@prisma-next/utils/canonical-stringify';\nimport { hashContent } from '@prisma-next/utils/hash-content';\n\n/**\n * Computes a stable content hash for a lowered SQL execution plan.\n *\n * Internally builds an unambiguous canonical-stringified preimage from\n * three components:\n *\n * 1. `meta.storageHash` — discriminates by schema. A migration changes the\n * storage hash, which invalidates cached entries automatically.\n * 2. `exec.sql` — the raw lowered SQL text. Two queries with different\n * structure produce different keys. Note that we deliberately do **not**\n * use `computeSqlFingerprint` here: that helper strips literals to group\n * executions by statement shape (used by telemetry), which is the\n * opposite of what a content hash needs — we want per-execution\n * discrimination, not per-statement-shape grouping.\n * 3. `exec.params` — the bound parameters. `canonicalStringify` produces a\n * deterministic serialization that is stable across object key\n * insertion order and that distinguishes types JSON would otherwise\n * conflate (e.g. `BigInt(1)` vs `1`).\n *\n * The components are wrapped in an object and canonicalized as a single\n * unit (rather than concatenated with a delimiter) so component\n * boundaries are unambiguous: any character appearing inside `sql` or\n * `storageHash` cannot bleed across components and produce a collision\n * with a different split of the same characters.\n *\n * The canonical string is then piped through `hashContent` to produce a\n * bounded, opaque digest. See `@prisma-next/utils/hash-content` for the\n * rationale.\n *\n * @internal\n */\nexport function computeSqlContentHash(exec: SqlExecutionPlan): Promise<string> {\n return hashContent(\n canonicalStringify({\n storageHash: exec.meta.storageHash,\n sql: exec.sql,\n params: exec.params,\n }),\n );\n}\n","import { createHash } from 'node:crypto';\n\nconst STRING_LITERAL_REGEX = /'(?:''|[^'])*'/g;\nconst NUMERIC_LITERAL_REGEX = /\\b\\d+(?:\\.\\d+)?\\b/g;\nconst WHITESPACE_REGEX = /\\s+/g;\n\n/**\n * Computes a literal-stripped, normalized fingerprint of a SQL statement.\n *\n * The function strips string and numeric literals, collapses whitespace, and\n * lowercases the result before hashing — so two structurally equivalent\n * statements (with different parameter values) produce the same fingerprint.\n * Used by SQL telemetry to group queries.\n */\nexport function computeSqlFingerprint(sql: string): string {\n const withoutStrings = sql.replace(STRING_LITERAL_REGEX, '?');\n const withoutNumbers = withoutStrings.replace(NUMERIC_LITERAL_REGEX, '?');\n const normalized = withoutNumbers.replace(WHITESPACE_REGEX, ' ').trim().toLowerCase();\n\n const hash = createHash('sha256').update(normalized).digest('hex');\n return `sha256:${hash}`;\n}\n","import type { DraftPlan, SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport async function runBeforeCompileChain(\n middleware: readonly SqlMiddleware[],\n initial: DraftPlan,\n ctx: SqlMiddlewareContext,\n): Promise<DraftPlan> {\n let current = initial;\n for (const mw of middleware) {\n if (!mw.beforeCompile) {\n continue;\n }\n const result = await mw.beforeCompile(current, ctx);\n if (result === undefined) {\n continue;\n }\n if (result.ast === current.ast) {\n continue;\n }\n ctx.log.debug?.({\n event: 'middleware.rewrite',\n middleware: mw.name,\n lane: current.meta.lane,\n });\n current = result;\n }\n\n return current;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { ExecutionPlan } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { AdapterProfile } from '@prisma-next/sql-relational-core/ast';\nimport type { MarkerReader, RuntimeFamilyAdapter } from './runtime-spi';\n\nexport class SqlFamilyAdapter<TContract extends Contract<SqlStorage>>\n implements RuntimeFamilyAdapter<TContract>\n{\n readonly contract: TContract;\n readonly markerReader: MarkerReader;\n\n constructor(contract: TContract, adapterProfile: AdapterProfile) {\n this.contract = contract;\n this.markerReader = adapterProfile;\n }\n\n validatePlan(plan: ExecutionPlan, contract: TContract): void {\n if (plan.meta.target !== contract.target) {\n throw runtimeError('PLAN.TARGET_MISMATCH', 'Plan target does not match runtime target', {\n planTarget: plan.meta.target,\n runtimeTarget: contract.target,\n });\n }\n\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw runtimeError(\n 'PLAN.HASH_MISMATCH',\n 'Plan storage hash does not match runtime contract',\n {\n planStorageHash: plan.meta.storageHash,\n runtimeStorageHash: contract.storage.storageHash,\n },\n );\n }\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n ExecutionStackInstance,\n RuntimeDriverInstance,\n} from '@prisma-next/framework-components/execution';\nimport {\n AsyncIterableResult,\n checkAborted,\n checkMiddlewareCompatibility,\n RuntimeCore,\n type RuntimeExecuteOptions,\n type RuntimeLog,\n runtimeError,\n runWithMiddleware,\n} from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n AnyQueryAst,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecCallContext,\n SqlDriver,\n SqlQueryable,\n SqlTransaction,\n} from '@prisma-next/sql-relational-core/ast';\nimport { validateParamRefRefs } from '@prisma-next/sql-relational-core/ast';\nimport {\n createSqlParamRefMutator,\n type SqlParamRefMutator,\n type SqlParamRefMutatorInternal,\n} from '@prisma-next/sql-relational-core/middleware';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { RuntimeScope } from '@prisma-next/sql-relational-core/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { decodeRow } from './codecs/decoding';\nimport { encodeParams } from './codecs/encoding';\nimport { validateCodecRegistryCompleteness } from './codecs/validation';\nimport { computeSqlContentHash } from './content-hash';\nimport { computeSqlFingerprint } from './fingerprint';\nimport { lowerSqlPlan } from './lower-sql-plan';\nimport { runBeforeCompileChain } from './middleware/before-compile-chain';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './middleware/sql-middleware';\nimport type {\n RuntimeFamilyAdapter,\n RuntimeTelemetryEvent,\n RuntimeVerifyOptions,\n TelemetryOutcome,\n} from './runtime-spi';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterInstance,\n SqlRuntimeExtensionInstance,\n} from './sql-context';\nimport { SqlFamilyAdapter } from './sql-family-adapter';\n\nexport type Log = RuntimeLog;\n\nexport interface RuntimeOptions<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> {\n readonly context: ExecutionContext<TContract>;\n readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n readonly driver: SqlDriver<unknown>;\n readonly verify: RuntimeVerifyOptions;\n readonly middleware?: readonly SqlMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n readonly log?: Log;\n}\n\nexport interface CreateRuntimeOptions<\n TContract extends Contract<SqlStorage> = Contract<SqlStorage>,\n TTargetId extends string = string,\n> {\n readonly stackInstance: ExecutionStackInstance<\n 'sql',\n TTargetId,\n SqlRuntimeAdapterInstance<TTargetId>,\n RuntimeDriverInstance<'sql', TTargetId>,\n SqlRuntimeExtensionInstance<TTargetId>\n >;\n readonly context: ExecutionContext<TContract>;\n readonly driver: SqlDriver<unknown>;\n readonly verify: RuntimeVerifyOptions;\n readonly middleware?: readonly SqlMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n readonly log?: Log;\n}\n\nexport interface Runtime extends RuntimeQueryable {\n connection(): Promise<RuntimeConnection>;\n telemetry(): RuntimeTelemetryEvent | null;\n close(): Promise<void>;\n}\n\nexport interface RuntimeConnection extends RuntimeQueryable {\n transaction(): Promise<RuntimeTransaction>;\n /**\n * Returns the connection to the pool for reuse. Only call this when the connection is known to be in a clean state. If a transaction commit/rollback failed or the connection is otherwise suspect, call `destroy(reason)` instead.\n */\n release(): Promise<void>;\n /**\n * Evicts the connection so it is never reused. Call this when the connection may be in an indeterminate state (e.g. a failed rollback leaving an open transaction, or a broken socket).\n *\n * If teardown fails the error is propagated and the connection remains retryable, so the caller can decide whether to swallow the failure or retry cleanup. Calling destroy() or release() more than once after a successful teardown is caller error.\n *\n * `reason` is advisory context only. It may be surfaced to driver-level observability hooks (e.g. pg-pool's `'release'` event) but does not influence eviction behavior and is not rethrown.\n */\n destroy(reason?: unknown): Promise<void>;\n}\n\nexport interface RuntimeTransaction extends RuntimeQueryable {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\nexport interface RuntimeQueryable extends RuntimeScope {}\n\nexport interface TransactionContext extends RuntimeQueryable {\n readonly invalidated: boolean;\n}\n\nexport type { RuntimeTelemetryEvent, RuntimeVerifyOptions, TelemetryOutcome };\n\nfunction isExecutionPlan(plan: SqlExecutionPlan | SqlQueryPlan): plan is SqlExecutionPlan {\n return 'sql' in plan;\n}\n\n// v8 ignore next 2\nconst noopLogSink = (): void => {};\nconst noopLog: Log = { info: noopLogSink, warn: noopLogSink, error: noopLogSink };\n\nclass SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorage>>\n extends RuntimeCore<SqlQueryPlan, SqlExecutionPlan, SqlMiddleware>\n implements Runtime\n{\n private readonly contract: TContract;\n private readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n private readonly driver: SqlDriver<unknown>;\n private readonly familyAdapter: RuntimeFamilyAdapter<Contract<SqlStorage>>;\n private readonly contractCodecs: ContractCodecRegistry;\n private readonly codecDescriptors: CodecDescriptorRegistry;\n private readonly sqlCtx: SqlMiddlewareContext;\n private readonly verify: RuntimeVerifyOptions;\n private codecRegistryValidated: boolean;\n private verified: boolean;\n private startupVerified: boolean;\n private _telemetry: RuntimeTelemetryEvent | null;\n\n constructor(options: RuntimeOptions<TContract>) {\n const { context, adapter, driver, verify, middleware, mode, log } = options;\n\n if (middleware) {\n for (const mw of middleware) {\n checkMiddlewareCompatibility(mw, 'sql', context.contract.target);\n }\n }\n\n const sqlCtx: SqlMiddlewareContext = {\n contract: context.contract,\n mode: mode ?? 'strict',\n now: () => Date.now(),\n log: log ?? noopLog,\n // ctx is only invoked by runWithMiddleware with execs this runtime lowered; the framework parameter type is the cross-family base.\n contentHash: (exec) => computeSqlContentHash(exec as SqlExecutionPlan),\n };\n\n super({ middleware: middleware ?? [], ctx: sqlCtx });\n\n this.contract = context.contract;\n this.adapter = adapter;\n this.driver = driver;\n this.familyAdapter = new SqlFamilyAdapter(context.contract, adapter.profile);\n this.contractCodecs = context.contractCodecs;\n this.codecDescriptors = context.codecDescriptors;\n this.sqlCtx = sqlCtx;\n this.verify = verify;\n this.codecRegistryValidated = false;\n this.verified = verify.mode === 'startup' ? false : verify.mode === 'always';\n this.startupVerified = false;\n this._telemetry = null;\n\n if (verify.mode === 'startup') {\n validateCodecRegistryCompleteness(this.codecDescriptors, context.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n /**\n * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan` with encoded parameters ready for the driver. This is the single point at which params transition from app-layer values to driver wire-format.\n *\n * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so per-query cancellation reaches every codec body during parameter encoding. The framework abstract typed this as `CodecCallContext`; the SQL family narrows it to the SQL-specific extension. SQL params do not populate `ctx.column` — encode-side column metadata is the middleware's domain.\n */\n protected override async lower(\n plan: SqlQueryPlan,\n ctx: SqlCodecCallContext,\n ): Promise<SqlExecutionPlan> {\n validateParamRefRefs(plan.ast, this.codecDescriptors);\n const lowered = lowerSqlPlan(this.adapter, this.contract, plan);\n return Object.freeze({\n ...lowered,\n params: await encodeParams(lowered, ctx, this.contractCodecs),\n });\n }\n\n /**\n * Default driver invocation required by the abstract `RuntimeCore` contract. Every production path overrides `execute()` and routes through `executeAgainstQueryable`, so this hook is defensive only — subclasses that delegate back to `super.execute()` would land here.\n */\n // v8 ignore next 6\n protected override runDriver(exec: SqlExecutionPlan): AsyncIterable<Record<string, unknown>> {\n return this.driver.execute<Record<string, unknown>>({\n sql: exec.sql,\n params: exec.params,\n });\n }\n\n /**\n * SQL pre-compile hook. Runs the registered middleware `beforeCompile` chain over the plan's draft (AST + meta). Returns the original plan unchanged when no middleware rewrote the AST; otherwise returns a new plan carrying the rewritten AST and meta. The AST is the authoritative source of execution metadata, so a rewrite needs no sidecar reconciliation here — the lowering adapter and the encoder both walk the rewritten\n * AST directly.\n */\n protected override async runBeforeCompile(plan: SqlQueryPlan): Promise<SqlQueryPlan> {\n const rewrittenDraft = await runBeforeCompileChain(\n this.middleware,\n { ast: plan.ast, meta: plan.meta },\n this.sqlCtx,\n );\n return rewrittenDraft.ast === plan.ast\n ? plan\n : { ...plan, ast: rewrittenDraft.ast, meta: rewrittenDraft.meta };\n }\n\n override execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return this.executeAgainstQueryable<Row>(plan, this.driver, options);\n }\n\n private executeAgainstQueryable<Row>(\n plan: SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>,\n queryable: SqlQueryable,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n this.ensureCodecRegistryValidated();\n\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call — the same reference is shared by encodeParams (lower), decodeRow (per-row), and the stream loop's between-row checks. Per-cell ctx allocations inside decodeField add `column` for resolvable cells without re-wrapping the signal. The ctx object is always allocated; the `signal` field is only included when a signal was supplied (exactOptionalPropertyTypes).\n const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal };\n // Per-execute view of the middleware ctx that carries the per-query\n // signal. `self.ctx` is allocated once at construction (no signal); we\n // shallow-clone it here so middleware sees the same `AbortSignal`\n // reference threaded into `codecCtx.signal` (ADR 207 identity).\n const execMiddlewareCtx = signal === undefined ? self.ctx : { ...self.ctx, signal };\n\n const generator = async function* (): AsyncGenerator<Row, void, unknown> {\n checkAborted(codecCtx, 'stream');\n\n let exec: SqlExecutionPlan;\n if (isExecutionPlan(plan)) {\n if (plan.ast) {\n validateParamRefRefs(plan.ast, self.codecDescriptors);\n }\n exec = Object.freeze({\n ...plan,\n params: await encodeParams(plan, codecCtx, self.contractCodecs),\n });\n } else {\n exec = await self.lower(await self.runBeforeCompile(plan), codecCtx);\n }\n\n self.familyAdapter.validatePlan(exec, self.contract);\n self._telemetry = null;\n\n if (!self.startupVerified && self.verify.mode === 'startup') {\n await self.verifyMarker();\n }\n\n if (!self.verified && self.verify.mode === 'onFirstUse') {\n await self.verifyMarker();\n }\n\n const startedAt = Date.now();\n let outcome: TelemetryOutcome | null = null;\n\n try {\n if (self.verify.mode === 'always') {\n await self.verifyMarker();\n }\n\n const paramsMutator: SqlParamRefMutatorInternal = createSqlParamRefMutator(exec);\n const stream = runWithMiddleware<\n SqlExecutionPlan,\n Record<string, unknown>,\n SqlParamRefMutator\n >(\n exec,\n self.middleware,\n execMiddlewareCtx,\n () =>\n queryable.execute<Record<string, unknown>>({\n sql: exec.sql,\n // Read params after the `beforeExecute` middleware chain has\n // run so that any `mutator.replaceValue(...)` calls land in\n // the driver-bound params array. When no middleware mutated,\n // `currentParams()` returns `exec.params` by reference identity.\n params: paramsMutator.currentParams(),\n }),\n paramsMutator,\n );\n\n // Manually drive the driver's async iterator so the between-row abort check fires *before* requesting the next row. With a `for await...of` loop the runtime would await `iterator.next()` first, leaving a window where one extra row is pulled through the driver after the signal aborted.\n const iterator = stream[Symbol.asyncIterator]();\n try {\n while (true) {\n checkAborted(codecCtx, 'stream');\n const next = await iterator.next();\n if (next.done) {\n break;\n }\n const decodedRow = await decodeRow(next.value, exec, codecCtx, self.contractCodecs);\n yield decodedRow as Row;\n }\n } finally {\n // Best-effort iterator cleanup so the driver can release its resources whether the stream finished normally, threw, or was abandoned by the consumer.\n await iterator.return?.();\n }\n\n outcome = 'success';\n } catch (error) {\n outcome = 'runtime-error';\n throw error;\n } finally {\n if (outcome !== null) {\n self.recordTelemetry(exec, outcome, Date.now() - startedAt);\n }\n }\n };\n\n return new AsyncIterableResult(generator());\n }\n\n async connection(): Promise<RuntimeConnection> {\n const driverConn = await this.driver.acquireConnection();\n const self = this;\n\n const wrappedConnection: RuntimeConnection = {\n async transaction(): Promise<RuntimeTransaction> {\n const driverTx = await driverConn.beginTransaction();\n return self.wrapTransaction(driverTx);\n },\n async release(): Promise<void> {\n await driverConn.release();\n },\n async destroy(reason?: unknown): Promise<void> {\n await driverConn.destroy(reason);\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverConn, options);\n },\n };\n\n return wrappedConnection;\n }\n\n private wrapTransaction(driverTx: SqlTransaction): RuntimeTransaction {\n const self = this;\n return {\n async commit(): Promise<void> {\n await driverTx.commit();\n },\n async rollback(): Promise<void> {\n await driverTx.rollback();\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverTx, options);\n },\n };\n }\n\n telemetry(): RuntimeTelemetryEvent | null {\n return this._telemetry;\n }\n\n async close(): Promise<void> {\n await this.driver.close();\n }\n\n private ensureCodecRegistryValidated(): void {\n if (!this.codecRegistryValidated) {\n validateCodecRegistryCompleteness(this.codecDescriptors, this.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n private async verifyMarker(): Promise<void> {\n const readResult = await this.familyAdapter.markerReader.readMarker(this.driver);\n\n if (readResult.kind !== 'present') {\n if (this.verify.requireMarker) {\n throw runtimeError('CONTRACT.MARKER_MISSING', 'Contract marker not found in database');\n }\n\n this.verified = true;\n return;\n }\n\n const marker = readResult.record;\n\n const contract = this.contract as {\n storage: { storageHash: string };\n execution?: { executionHash?: string | null };\n profileHash?: string | null;\n };\n\n if (marker.storageHash !== contract.storage.storageHash) {\n throw runtimeError(\n 'CONTRACT.MARKER_MISMATCH',\n 'Database storage hash does not match contract',\n {\n expected: contract.storage.storageHash,\n actual: marker.storageHash,\n },\n );\n }\n\n const expectedProfile = contract.profileHash ?? null;\n if (expectedProfile !== null && marker.profileHash !== expectedProfile) {\n throw runtimeError(\n 'CONTRACT.MARKER_MISMATCH',\n 'Database profile hash does not match contract',\n {\n expectedProfile,\n actualProfile: marker.profileHash,\n },\n );\n }\n\n this.verified = true;\n this.startupVerified = true;\n }\n\n private recordTelemetry(\n plan: SqlExecutionPlan,\n outcome: TelemetryOutcome,\n durationMs?: number,\n ): void {\n const contract = this.contract as { target: string };\n this._telemetry = Object.freeze({\n lane: plan.meta.lane,\n target: contract.target,\n fingerprint: computeSqlFingerprint(plan.sql),\n outcome,\n ...(durationMs !== undefined ? { durationMs } : {}),\n });\n }\n}\n\nfunction transactionClosedError(): Error {\n return runtimeError(\n 'RUNTIME.TRANSACTION_CLOSED',\n 'Cannot read from a query result after the transaction has ended. Await the result or call .toArray() inside the transaction callback.',\n {},\n );\n}\n\nexport async function withTransaction<R>(\n runtime: Runtime,\n fn: (tx: TransactionContext) => PromiseLike<R>,\n): Promise<R> {\n const connection = await runtime.connection();\n const transaction = await connection.transaction();\n\n let invalidated = false;\n const txContext: TransactionContext = {\n get invalidated() {\n return invalidated;\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n if (invalidated) {\n throw transactionClosedError();\n }\n const inner = transaction.execute(plan, options);\n const guarded = async function* (): AsyncGenerator<Row, void, unknown> {\n for await (const row of inner) {\n if (invalidated) {\n throw transactionClosedError();\n }\n yield row;\n }\n };\n return new AsyncIterableResult(guarded());\n },\n };\n\n let connectionDisposed = false;\n const destroyConnection = async (reason: unknown): Promise<void> => {\n if (connectionDisposed) return;\n connectionDisposed = true;\n // SqlConnection.destroy() propagates teardown errors so callers can decide what to do with them. Here, we're already about to throw a more informative error describing why we're evicting the connection (rollback/commit failure), so swallowing the teardown error is the right call — surfacing it would mask the original cause.\n await connection.destroy(reason).catch(() => undefined);\n };\n\n try {\n let result: R;\n try {\n result = await fn(txContext);\n } catch (error) {\n try {\n await transaction.rollback();\n } catch (rollbackError) {\n await destroyConnection(rollbackError);\n const wrapped = runtimeError(\n 'RUNTIME.TRANSACTION_ROLLBACK_FAILED',\n 'Transaction rollback failed after callback error',\n { rollbackError },\n );\n wrapped.cause = error;\n throw wrapped;\n }\n throw error;\n } finally {\n invalidated = true;\n }\n\n try {\n await transaction.commit();\n } catch (commitError) {\n // After a failed COMMIT the server-side transaction may be: (a) already committed (error on response path), (b) already rolled back (deferred constraint / serialization failure), or (c) still open (COMMIT never reached the server). Attempt a best-effort rollback to cover (c) and confirm the protocol is healthy.\n //\n // If rollback succeeds, the server is definitely no longer in a transaction (no-op in (a)/(b), real cleanup in (c)) and we've just proved the connection round-trips correctly — it's safe to return to the pool. If rollback fails, the connection state is ambiguous (broken socket, protocol desync, etc.) and we must destroy it.\n try {\n await transaction.rollback();\n } catch {\n await destroyConnection(commitError);\n }\n const wrapped = runtimeError(\n 'RUNTIME.TRANSACTION_COMMIT_FAILED',\n 'Transaction commit failed',\n { commitError },\n );\n wrapped.cause = commitError;\n throw wrapped;\n }\n return result;\n } finally {\n if (!connectionDisposed) {\n await connection.release();\n }\n }\n}\n\nexport function createRuntime<TContract extends Contract<SqlStorage>, TTargetId extends string>(\n options: CreateRuntimeOptions<TContract, TTargetId>,\n): Runtime {\n const { stackInstance, context, driver, verify, middleware, mode, log } = options;\n\n return new SqlRuntimeImpl({\n context,\n adapter: stackInstance.adapter,\n driver,\n verify,\n ...ifDefined('middleware', middleware),\n ...ifDefined('mode', mode),\n ...ifDefined('log', log),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAKA,SAAgB,gBAAgB,UAA6C;CAC3E,MAAM,2BAAW,IAAI,KAAa;CAElC,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,QAAQ,OAAO,EACxD,KAAK,MAAM,UAAU,OAAO,OAAO,MAAM,QAAQ,EAAE;EACjD,MAAM,UAAU,OAAO;EACvB,SAAS,IAAI,QAAQ;;CAIzB,OAAO;;AAGT,SAAS,2BAA2B,UAAqD;CACvF,MAAM,2BAAW,IAAI,KAAqB;CAE1C,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,SAAS,QAAQ,OAAO,EACtE,KAAK,MAAM,CAAC,YAAY,WAAW,OAAO,QAAQ,MAAM,QAAQ,EAAE;EAChE,MAAM,UAAU,OAAO;EACvB,MAAM,MAAM,GAAG,UAAU,GAAG;EAC5B,SAAS,IAAI,KAAK,QAAQ;;CAI9B,OAAO;;AAGT,SAAgB,8BACd,UACA,UACM;CACN,MAAM,WAAW,2BAA2B,SAAS;CACrD,MAAM,gBAA2E,EAAE;CAEnF,KAAK,MAAM,CAAC,KAAK,YAAY,SAAS,SAAS,EAC7C,IAAI,SAAS,cAAc,QAAQ,KAAK,KAAA,GAAW;EACjD,MAAM,QAAQ,IAAI,MAAM,IAAI;EAC5B,MAAM,QAAQ,MAAM,MAAM;EAC1B,MAAM,SAAS,MAAM,MAAM;EAC3B,cAAc,KAAK;GAAE;GAAO;GAAQ;GAAS,CAAC;;CAIlD,IAAI,cAAc,SAAS,GAAG;EAC5B,MAAM,UAAmC;GACvC,gBAAgB,SAAS;GACzB;GACD;EAED,MAAM,aACJ,yBACA,sDAAsD,cAAc,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,EAAE,OAAO,IAAI,E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F,MAAM,wBAAwB;KAEhC,MAAM;;;GAGV,OAAO,IAAI,oBAAoB,SAAS,CAAC;;EAE5C;CAED,IAAI,qBAAqB;CACzB,MAAM,oBAAoB,OAAO,WAAmC;EAClE,IAAI,oBAAoB;EACxB,qBAAqB;EAErB,MAAM,WAAW,QAAQ,OAAO,CAAC,YAAY,KAAA,EAAU;;CAGzD,IAAI;EACF,IAAI;EACJ,IAAI;GACF,SAAS,MAAM,GAAG,UAAU;WACrB,OAAO;GACd,IAAI;IACF,MAAM,YAAY,UAAU;YACrB,eAAe;IACtB,MAAM,kBAAkB,cAAc;IACtC,MAAM,UAAU,aACd,uCACA,oDACA,EAAE,eAAe,CAClB;IACD,QAAQ,QAAQ;IAChB,MAAM;;GAER,MAAM;YACE;GACR,cAAc;;EAGhB,IAAI;GACF,MAAM,YAAY,QAAQ;WACnB,aAAa;GAIpB,IAAI;IACF,MAAM,YAAY,UAAU;WACtB;IACN,MAAM,kBAAkB,YAAY;;GAEtC,MAAM,UAAU,aACd,qCACA,6BACA,EAAE,aAAa,CAChB;GACD,QAAQ,QAAQ;GAChB,MAAM;;EAER,OAAO;WACC;EACR,IAAI,CAAC,oBACH,MAAM,WAAW,SAAS;;;AAKhC,SAAgB,cACd,SACS;CACT,MAAM,EAAE,eAAe,SAAS,QAAQ,QAAQ,YAAY,MAAM,QAAQ;CAE1E,OAAO,IAAI,eAAe;EACxB;EACA,SAAS,cAAc;EACvB;EACA;EACA,GAAG,UAAU,cAAc,WAAW;EACtC,GAAG,UAAU,QAAQ,KAAK;EAC1B,GAAG,UAAU,OAAO,IAAI;EACzB,CAAC"}
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-BSTHn_rH.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-B_kfmMPM.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 { a as ensureTableStatement, c as createExecutionContext, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-BSTHn_rH.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-B_kfmMPM.mjs";
2
2
  import { instantiateExecutionStack } from "@prisma-next/framework-components/execution";
3
3
  import { coreHash, profileHash } from "@prisma-next/contract/types";
4
4
  import { voidParamsSchema } from "@prisma-next/framework-components/codec";
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "@prisma-next/sql-runtime",
3
- "version": "0.6.0-dev.5",
3
+ "version": "0.6.0-dev.6",
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
9
  "arktype": "^2.1.29",
10
- "@prisma-next/contract": "0.6.0-dev.5",
11
- "@prisma-next/ids": "0.6.0-dev.5",
12
- "@prisma-next/sql-contract": "0.6.0-dev.5",
13
- "@prisma-next/sql-relational-core": "0.6.0-dev.5",
14
- "@prisma-next/operations": "0.6.0-dev.5",
15
- "@prisma-next/sql-operations": "0.6.0-dev.5",
16
- "@prisma-next/utils": "0.6.0-dev.5",
17
- "@prisma-next/framework-components": "0.6.0-dev.5"
10
+ "@prisma-next/contract": "0.6.0-dev.6",
11
+ "@prisma-next/utils": "0.6.0-dev.6",
12
+ "@prisma-next/ids": "0.6.0-dev.6",
13
+ "@prisma-next/sql-contract": "0.6.0-dev.6",
14
+ "@prisma-next/operations": "0.6.0-dev.6",
15
+ "@prisma-next/framework-components": "0.6.0-dev.6",
16
+ "@prisma-next/sql-relational-core": "0.6.0-dev.6",
17
+ "@prisma-next/sql-operations": "0.6.0-dev.6"
18
18
  },
19
19
  "devDependencies": {
20
20
  "@types/pg": "8.20.0",
@@ -22,9 +22,9 @@
22
22
  "tsdown": "0.22.0",
23
23
  "typescript": "5.9.3",
24
24
  "vitest": "4.1.5",
25
- "@prisma-next/tsconfig": "0.0.0",
25
+ "@prisma-next/test-utils": "0.0.1",
26
26
  "@prisma-next/tsdown": "0.0.0",
27
- "@prisma-next/test-utils": "0.0.1"
27
+ "@prisma-next/tsconfig": "0.0.0"
28
28
  },
29
29
  "files": [
30
30
  "dist",
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  checkAborted,
3
+ isRuntimeError,
3
4
  raceAgainstAbort,
4
5
  runtimeError,
5
6
  } from '@prisma-next/framework-components/runtime';
@@ -122,6 +123,14 @@ async function encodeParamValue(
122
123
  try {
123
124
  return await codec.encode(value, ctx);
124
125
  } catch (error) {
126
+ // Any `runtimeError`-built envelope is stable by construction — let
127
+ // it pass through unchanged. This covers codec-authored
128
+ // `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` (per-library JSON-with-
129
+ // schema codecs validate inside `encode` per ADR 208 § Case J),
130
+ // codec-authored `RUNTIME.ENCODE_FAILED` (no double wrap), and any
131
+ // future stable code thrown from a codec body. Symmetric with the
132
+ // decode-side guard.
133
+ if (isRuntimeError(error)) throw error;
125
134
  wrapEncodeFailure(error, metadata, paramIndex, codec.id);
126
135
  }
127
136
  }