@prisma-next/sql-runtime 0.5.0-dev.7 → 0.5.0-dev.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -21
- package/dist/{exports-BQZSVXXt.mjs → exports-BOHa3Emo.mjs} +481 -128
- package/dist/exports-BOHa3Emo.mjs.map +1 -0
- package/dist/{index-yb51L_1h.d.mts → index-CZmC2kD3.d.mts} +53 -16
- package/dist/index-CZmC2kD3.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/test/utils.d.mts +6 -5
- package/dist/test/utils.d.mts.map +1 -1
- package/dist/test/utils.mjs +7 -2
- package/dist/test/utils.mjs.map +1 -1
- package/package.json +12 -14
- package/src/codecs/decoding.ts +172 -116
- package/src/codecs/encoding.ts +59 -21
- package/src/exports/index.ts +10 -7
- package/src/fingerprint.ts +22 -0
- package/src/guardrails/raw.ts +214 -0
- package/src/lower-sql-plan.ts +3 -3
- package/src/marker.ts +82 -0
- package/src/middleware/before-compile-chain.ts +32 -1
- package/src/middleware/budgets.ts +14 -11
- package/src/middleware/lints.ts +3 -3
- package/src/middleware/sql-middleware.ts +6 -5
- package/src/runtime-spi.ts +43 -0
- package/src/sql-family-adapter.ts +3 -2
- package/src/sql-marker.ts +1 -1
- package/src/sql-runtime.ts +272 -110
- package/dist/exports-BQZSVXXt.mjs.map +0 -1
- package/dist/index-yb51L_1h.d.mts.map +0 -1
- package/test/async-iterable-result.test.ts +0 -141
- package/test/before-compile-chain.test.ts +0 -223
- package/test/budgets.test.ts +0 -431
- package/test/context.types.test-d.ts +0 -68
- package/test/execution-stack.test.ts +0 -161
- package/test/json-schema-validation.test.ts +0 -571
- package/test/lints.test.ts +0 -160
- package/test/mutation-default-generators.test.ts +0 -254
- package/test/parameterized-types.test.ts +0 -529
- package/test/sql-context.test.ts +0 -384
- package/test/sql-family-adapter.test.ts +0 -103
- package/test/sql-runtime.test.ts +0 -792
- package/test/utils.ts +0 -297
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exports-BOHa3Emo.mjs","names":["invalidCodecs: Array<{ table: string; column: string; codecId: string }>","details: Record<string, unknown>","lints: LintFinding[]","budgets: BudgetFinding[]","lints","findings: LintFinding[]","arktype","helpers: TypeHelperRegistry","applied: AppliedMutationDefault[]","contributors: Array<SqlStaticContributions & ComponentDescriptor<string>>","options","ensureSchemaStatement: SqlStatement","ensureTableStatement: SqlStatement","baseParams: readonly unknown[]","codec","index: ColumnRefIndex","parsed: unknown","decoded: unknown","aliases: readonly string[]","tasks: Promise<unknown>[]","includeIndices: { index: number; alias: string; value: unknown }[]","decoded: Record<string, unknown>","codec","tasks: Promise<unknown>[]","parsed: unknown","meta: PlanMeta","descriptors: ParamDescriptor[]","sqlCtx: SqlMiddlewareContext","exec: SqlExecutionPlan","outcome: TelemetryOutcome | null","txContext: TransactionContext","result: R"],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/middleware/budgets.ts","../src/guardrails/raw.ts","../src/middleware/lints.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/codecs/json-schema-validation.ts","../src/codecs/decoding.ts","../src/codecs/encoding.ts","../src/fingerprint.ts","../src/marker.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 { CodecRegistry } from '@prisma-next/sql-relational-core/ast';\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: CodecRegistry,\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.has(codecId)) {\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: CodecRegistry,\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 {\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 estimateRowsFromAst(\n ast: SelectAst,\n tableRows: Record<string, number>,\n defaultTableRows: number,\n refs: { tables?: readonly string[] } | undefined,\n hasAggregateWithoutGroup: boolean,\n): number | null {\n if (hasAggregateWithoutGroup) {\n return 1;\n }\n\n const table = refs?.tables?.[0];\n if (!table) {\n return null;\n }\n\n const tableEstimate = tableRows[table] ?? defaultTableRows;\n\n if (ast.limit !== undefined) {\n return Math.min(ast.limit, tableEstimate);\n }\n\n return tableEstimate;\n}\n\nfunction estimateRowsFromHeuristics(\n plan: SqlExecutionPlan,\n tableRows: Record<string, number>,\n defaultTableRows: number,\n): number | null {\n const table = plan.meta.refs?.tables?.[0];\n if (!table) {\n return null;\n }\n\n const tableEstimate = tableRows[table] ?? defaultTableRows;\n\n const limit = plan.meta.annotations?.['limit'];\n if (typeof limit === 'number') {\n return Math.min(limit, tableEstimate);\n }\n\n return tableEstimate;\n}\n\nfunction hasDetectableLimitFromHeuristics(plan: SqlExecutionPlan): boolean {\n return typeof plan.meta.annotations?.['limit'] === 'number';\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)) {\n if (plan.ast.kind === 'select') {\n return evaluateSelectAst(plan, plan.ast, ctx);\n }\n return;\n }\n\n return evaluateWithHeuristics(plan, ctx);\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(plan: SqlExecutionPlan, ast: SelectAst, ctx: SqlMiddlewareContext) {\n const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);\n const estimated = estimateRowsFromAst(\n ast,\n tableRows,\n defaultTableRows,\n plan.meta.refs,\n hasAggNoGroup,\n );\n const isUnbounded = ast.limit === undefined && !hasAggNoGroup;\n const shouldBlock = rowSeverity === 'error' || ctx.mode === 'strict';\n\n if (isUnbounded) {\n if (estimated !== null && estimated >= maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', {\n source: 'ast',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', {\n source: 'ast',\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n if (estimated !== null && 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 async function evaluateWithHeuristics(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n const estimated = estimateRowsFromHeuristics(plan, tableRows, defaultTableRows);\n const isUnbounded = !hasDetectableLimitFromHeuristics(plan);\n const sqlUpper = plan.sql.trimStart().toUpperCase();\n const isSelect = sqlUpper.startsWith('SELECT');\n const shouldBlock = rowSeverity === 'error' || ctx.mode === 'strict';\n\n if (isSelect && isUnbounded) {\n if (estimated !== null && estimated >= maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', {\n source: 'heuristic',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', {\n source: 'heuristic',\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n if (estimated !== null) {\n if (estimated > maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Estimated row count exceeds budget', {\n source: 'heuristic',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n }\n return;\n }\n }\n}\n","import type { PlanMeta, PlanRefs } 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 const refs = plan.meta.refs;\n if (refs) {\n evaluateIndexCoverage(refs, lints);\n }\n\n return { lints, budgets, statement: statementType };\n}\n\nfunction evaluateIndexCoverage(refs: PlanRefs, lints: LintFinding[]) {\n const predicateColumns = refs.columns ?? [];\n if (predicateColumns.length === 0) {\n return;\n }\n\n const indexes = refs.indexes ?? [];\n\n if (indexes.length === 0) {\n lints.push(\n createLint(\n 'LINT.UNINDEXED_PREDICATE',\n 'warn',\n 'Raw SQL plan predicates lack supporting indexes',\n {\n predicates: predicateColumns,\n },\n ),\n );\n return;\n }\n\n const hasSupportingIndex = predicateColumns.every((column) =>\n indexes.some(\n (index) =>\n index.table === column.table &&\n index.columns.some((col) => col.toLowerCase() === column.column.toLowerCase()),\n ),\n );\n\n if (!hasSupportingIndex) {\n lints.push(\n createLint(\n 'LINT.UNINDEXED_PREDICATE',\n 'warn',\n 'Raw SQL plan predicates lack supporting indexes',\n {\n predicates: predicateColumns,\n },\n ),\n );\n }\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 // 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 if (isQueryAst(plan.ast)) {\n const findings = evaluateAstLints(plan.ast);\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 return;\n }\n\n if (fallback === 'skip') {\n return;\n }\n\n const evaluation = evaluateRawGuardrails(plan);\n for (const lint of evaluation.lints) {\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 { 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, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport {\n createSqlOperationRegistry,\n type SqlOperationDescriptor,\n} from '@prisma-next/sql-operations';\nimport type {\n Adapter,\n AnyQueryAst,\n CodecParamsDescriptor,\n CodecRegistry,\n LoweredStatement,\n SqlDriver,\n} from '@prisma-next/sql-relational-core/ast';\nimport { createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type {\n AppliedMutationDefault,\n ExecutionContext,\n JsonSchemaValidateFn,\n JsonSchemaValidatorRegistry,\n MutationDefaultsOptions,\n TypeHelperRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport { type as arktype } from 'arktype';\n\n/**\n * Runtime parameterized codec descriptor.\n * Provides validation schema and optional init hook for codecs that support type parameters.\n * Used at runtime to validate typeParams and create type helpers.\n *\n * This is a type alias for `CodecParamsDescriptor` from the AST layer,\n * which is the shared definition used by both adapter and runtime.\n */\nexport type RuntimeParameterizedCodecDescriptor<\n TParams = Record<string, unknown>,\n THelper = unknown,\n> = CodecParamsDescriptor<TParams, THelper>;\n\nexport interface SqlStaticContributions {\n readonly codecs: () => CodecRegistry;\n // biome-ignore lint/suspicious/noExplicitAny: needed for covariance with concrete descriptor types\n readonly parameterizedCodecs: () => ReadonlyArray<RuntimeParameterizedCodecDescriptor<any, any>>;\n readonly queryOperations?: () => ReadonlyArray<SqlOperationDescriptor>;\n readonly mutationDefaultGenerators?: () => ReadonlyArray<RuntimeMutationDefaultGenerator>;\n}\n\nexport interface RuntimeMutationDefaultGenerator {\n readonly id: string;\n readonly generate: (params?: Record<string, unknown>) => unknown;\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.\n * Target clients (for example `postgres()`) validate and construct the concrete binding\n * before calling `driver.connect(binding)`, which keeps runtime behavior safe today.\n * 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, JsonSchemaValidatorRegistry, 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 codecDescriptor: RuntimeParameterizedCodecDescriptor,\n context: { typeName?: string; tableName?: string; columnName?: string },\n): Record<string, unknown> {\n const result = codecDescriptor.paramsSchema(typeParams);\n if (result instanceof arktype.errors) {\n const messages = result.map((p: { message: string }) => p.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: ${codecDescriptor.codecId}): ${messages}`,\n { ...context, codecId: codecDescriptor.codecId, typeParams },\n );\n }\n return result as Record<string, unknown>;\n}\n\nfunction collectParameterizedCodecDescriptors(\n contributors: ReadonlyArray<SqlStaticContributions>,\n): Map<string, RuntimeParameterizedCodecDescriptor> {\n const descriptors = new Map<string, RuntimeParameterizedCodecDescriptor>();\n\n for (const contributor of contributors) {\n for (const descriptor of contributor.parameterizedCodecs()) {\n if (descriptors.has(descriptor.codecId)) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_PARAMETERIZED_CODEC',\n `Duplicate parameterized codec descriptor for codecId '${descriptor.codecId}'.`,\n { codecId: descriptor.codecId },\n );\n }\n descriptors.set(descriptor.codecId, descriptor);\n }\n }\n\n return descriptors;\n}\n\nfunction initializeTypeHelpers(\n storageTypes: Record<string, StorageTypeInstance> | undefined,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): TypeHelperRegistry {\n const helpers: TypeHelperRegistry = {};\n\n if (!storageTypes) {\n return helpers;\n }\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes)) {\n const descriptor = codecDescriptors.get(typeInstance.codecId);\n\n if (descriptor) {\n const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, {\n typeName,\n });\n\n if (descriptor.init) {\n helpers[typeName] = descriptor.init(validatedParams);\n } else {\n helpers[typeName] = typeInstance;\n }\n } else {\n helpers[typeName] = typeInstance;\n }\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\n/**\n * Builds a registry of compiled JSON Schema validators by scanning the contract\n * for columns whose codec descriptor provides an `init` hook returning `{ validate }`.\n *\n * Handles both:\n * - Inline `typeParams.schema` on columns\n * - `typeRef` → `storage.types[ref]` with init hook results already in `types` registry\n */\nfunction buildJsonSchemaValidatorRegistry(\n contract: Contract<SqlStorage>,\n types: TypeHelperRegistry,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): JsonSchemaValidatorRegistry | undefined {\n const validators = new Map<string, JsonSchemaValidateFn>();\n\n // Collect codec IDs that have init hooks (these produce { validate } helpers)\n const codecIdsWithInit = new Set<string>();\n for (const [codecId, descriptor] of codecDescriptors) {\n if (descriptor.init) {\n codecIdsWithInit.add(codecId);\n }\n }\n\n if (codecIdsWithInit.size === 0) {\n return undefined;\n }\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (!codecIdsWithInit.has(column.codecId)) continue;\n\n const key = `${tableName}.${columnName}`;\n\n // Case 1: column references a named type → validator already compiled via init hook\n if (column.typeRef) {\n const helper = types[column.typeRef] as { validate?: JsonSchemaValidateFn } | undefined;\n if (helper?.validate) {\n validators.set(key, helper.validate);\n }\n continue;\n }\n\n // Case 2: inline typeParams with schema → compile via init hook\n if (column.typeParams) {\n const descriptor = codecDescriptors.get(column.codecId);\n if (descriptor?.init) {\n const helper = descriptor.init(column.typeParams) as\n | { validate?: JsonSchemaValidateFn }\n | undefined;\n if (helper?.validate) {\n validators.set(key, helper.validate);\n }\n }\n }\n }\n }\n\n if (validators.size === 0) return undefined;\n return {\n get: (key: string) => validators.get(key),\n size: validators.size,\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 applied: AppliedMutationDefault[] = [];\n const appliedColumns = new Set<string>();\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 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: computeExecutionDefaultValue(defaultSpec, generatorRegistry),\n });\n appliedColumns.add(columnName);\n }\n\n return applied;\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 codecRegistry = createCodecRegistry();\n\n const contributors: Array<SqlStaticContributions & ComponentDescriptor<string>> = [\n stack.target,\n stack.adapter,\n ...stack.extensionPacks,\n ];\n\n for (const contributor of contributors) {\n for (const c of contributor.codecs().values()) {\n codecRegistry.register(c);\n }\n }\n\n const queryOperationRegistry = createSqlOperationRegistry();\n for (const contributor of contributors) {\n for (const op of contributor.queryOperations?.() ?? []) {\n queryOperationRegistry.register(op);\n }\n }\n\n const parameterizedCodecDescriptors = collectParameterizedCodecDescriptors(contributors);\n const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);\n\n if (parameterizedCodecDescriptors.size > 0) {\n validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);\n }\n\n const types = initializeTypeHelpers(contract.storage.types, parameterizedCodecDescriptors);\n\n const jsonSchemaValidators = buildJsonSchemaValidatorRegistry(\n contract,\n types,\n parameterizedCodecDescriptors,\n );\n\n return {\n contract,\n codecs: codecRegistry,\n queryOperations: queryOperationRegistry,\n types,\n ...(jsonSchemaValidators ? { jsonSchemaValidators } : {}),\n applyMutationDefaults: (options) =>\n applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options),\n };\n}\n","import type { MarkerStatement } from '@prisma-next/sql-relational-core/ast';\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport interface WriteMarkerInput {\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\nexport const ensureSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\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 )`,\n params: [],\n};\n\nexport function readContractMarker(): 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 from prisma_contract.marker\n where id = $1`,\n params: [1],\n };\n}\n\nexport interface WriteContractMarkerStatements {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n}\n\nexport function writeContractMarker(input: WriteMarkerInput): WriteContractMarkerStatements {\n const baseParams: readonly unknown[] = [\n 1,\n input.storageHash,\n input.profileHash,\n input.contractJson ?? null,\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n JSON.stringify(input.meta ?? {}),\n ];\n\n const insert: SqlStatement = {\n sql: `insert into prisma_contract.marker (\n id,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb\n )`,\n params: baseParams,\n };\n\n const update: SqlStatement = {\n sql: `update prisma_contract.marker set\n core_hash = $2,\n profile_hash = $3,\n contract_json = $4::jsonb,\n canonical_version = $5,\n updated_at = now(),\n app_tag = $6,\n meta = $7::jsonb\n where id = $1`,\n params: baseParams,\n };\n\n return { insert, update };\n}\n","import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type {\n JsonSchemaValidationError,\n JsonSchemaValidatorRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Validates a JSON value against its column's JSON Schema, if a validator exists.\n *\n * Throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` on validation failure.\n * No-ops if no validator is registered for the column.\n */\nexport function validateJsonValue(\n registry: JsonSchemaValidatorRegistry,\n table: string,\n column: string,\n value: unknown,\n direction: 'encode' | 'decode',\n codecId?: string,\n): void {\n const key = `${table}.${column}`;\n const validate = registry.get(key);\n if (!validate) return;\n\n const result = validate(value);\n if (result.valid) return;\n\n throw createJsonSchemaValidationError(table, column, direction, result.errors, codecId);\n}\n\nfunction createJsonSchemaValidationError(\n table: string,\n column: string,\n direction: 'encode' | 'decode',\n errors: ReadonlyArray<JsonSchemaValidationError>,\n codecId?: string,\n): Error {\n const summary = formatErrorSummary(errors);\n return runtimeError(\n 'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED',\n `JSON schema validation failed for column '${table}.${column}' (${direction}): ${summary}`,\n {\n table,\n column,\n codecId,\n direction,\n errors: [...errors],\n },\n );\n}\n\nfunction formatErrorSummary(errors: ReadonlyArray<JsonSchemaValidationError>): string {\n if (errors.length === 0) return 'unknown validation error';\n if (errors.length === 1) {\n const err = errors[0] as JsonSchemaValidationError;\n return err.path === '/' ? err.message : `${err.path}: ${err.message}`;\n }\n return errors\n .map((err) => (err.path === '/' ? err.message : `${err.path}: ${err.message}`))\n .join('; ');\n}\n","import { isRuntimeError, runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { Codec, CodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { JsonSchemaValidatorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\nimport { validateJsonValue } from './json-schema-validation';\n\ntype ColumnRef = { table: string; column: string };\ntype ColumnRefIndex = Map<string, ColumnRef>;\n\nconst WIRE_PREVIEW_LIMIT = 100;\n\nfunction resolveRowCodec(\n alias: string,\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n): Codec | null {\n const planCodecId = plan.meta.annotations?.codecs?.[alias] as string | undefined;\n if (planCodecId) {\n const codec = registry.get(planCodecId);\n if (codec) {\n return codec;\n }\n }\n\n if (plan.meta.projectionTypes) {\n const typeId = plan.meta.projectionTypes[alias];\n if (typeId) {\n const codec = registry.get(typeId);\n if (codec) {\n return codec;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Builds a lookup index from column name → { table, column } ref.\n * Called once per decodeRow invocation to avoid O(aliases × refs) linear scans.\n */\nfunction buildColumnRefIndex(plan: SqlExecutionPlan): ColumnRefIndex | null {\n const columns = plan.meta.refs?.columns;\n if (!columns) return null;\n\n const index: ColumnRefIndex = new Map();\n for (const ref of columns) {\n index.set(ref.column, ref);\n }\n return index;\n}\n\nfunction parseProjectionRef(value: string): ColumnRef | null {\n if (value.startsWith('include:') || value.startsWith('operation:')) {\n return null;\n }\n\n const separatorIndex = value.indexOf('.');\n if (separatorIndex <= 0 || separatorIndex === value.length - 1) {\n return null;\n }\n\n return {\n table: value.slice(0, separatorIndex),\n column: value.slice(separatorIndex + 1),\n };\n}\n\nfunction resolveColumnRefForAlias(\n alias: string,\n projection: SqlExecutionPlan['meta']['projection'],\n fallbackColumnRefIndex: ColumnRefIndex | null,\n): ColumnRef | undefined {\n if (projection && !Array.isArray(projection)) {\n const mappedRef = (projection as Record<string, string>)[alias];\n if (typeof mappedRef !== 'string') {\n return undefined;\n }\n return parseProjectionRef(mappedRef) ?? undefined;\n }\n\n return fallbackColumnRefIndex?.get(alias);\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 isJsonSchemaValidationError(error: unknown): boolean {\n return isRuntimeError(error) && error.code === 'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED';\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 —\n * `codec.decode → await → JSON-Schema validate → return plain value` — so\n * sync- and async-authored codecs are indistinguishable to callers.\n */\nasync function decodeField(\n alias: string,\n wireValue: unknown,\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n jsonValidators: JsonSchemaValidatorRegistry | undefined,\n projection: SqlExecutionPlan['meta']['projection'],\n fallbackColumnRefIndex: ColumnRefIndex | null,\n): Promise<unknown> {\n if (wireValue === null || wireValue === undefined) {\n return wireValue;\n }\n\n const codec = resolveRowCodec(alias, plan, registry);\n if (!codec) {\n return wireValue;\n }\n\n const ref = resolveColumnRefForAlias(alias, projection, fallbackColumnRefIndex);\n\n let decoded: unknown;\n try {\n decoded = await codec.decode(wireValue);\n } catch (error) {\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n\n if (jsonValidators && ref) {\n try {\n validateJsonValue(jsonValidators, ref.table, ref.column, decoded, 'decode', codec.id);\n } catch (error) {\n if (isJsonSchemaValidationError(error)) throw error;\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n }\n\n return decoded;\n}\n\n/**\n * Decodes a row by dispatching all per-cell codec calls concurrently via\n * `Promise.all`. Each cell follows the single-armed `decodeField` path.\n * Failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column,\n * codec }` (or `{ alias, codec }` when no column ref is resolvable) and the\n * original error attached on `cause`.\n */\nexport async function decodeRow(\n row: Record<string, unknown>,\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n jsonValidators?: JsonSchemaValidatorRegistry,\n): Promise<Record<string, unknown>> {\n const projection = plan.meta.projection;\n\n // Build a column-ref index when the projection alias-to-ref mapping is\n // unavailable so that decode failures and JSON-Schema validation can both\n // surface { table, column } from `meta.refs.columns` when present.\n const fallbackColumnRefIndex =\n !projection || Array.isArray(projection) ? buildColumnRefIndex(plan) : null;\n\n let aliases: readonly string[];\n if (projection && !Array.isArray(projection)) {\n aliases = Object.keys(projection);\n } else if (projection && Array.isArray(projection)) {\n aliases = projection;\n } else {\n aliases = Object.keys(row);\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 const projectionValue =\n projection && typeof projection === 'object' && !Array.isArray(projection)\n ? (projection as Record<string, string>)[alias]\n : undefined;\n\n if (typeof projectionValue === 'string' && projectionValue.startsWith('include:')) {\n includeIndices.push({ index: i, alias, value: wireValue });\n tasks.push(Promise.resolve(undefined));\n continue;\n }\n\n tasks.push(\n decodeField(\n alias,\n wireValue,\n plan,\n registry,\n jsonValidators,\n projection,\n fallbackColumnRefIndex,\n ),\n );\n }\n\n const settled = await Promise.all(tasks);\n\n // Include aggregates are decoded synchronously after concurrent codec\n // 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 type { ParamDescriptor } from '@prisma-next/contract/types';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { Codec, CodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\n\nfunction resolveParamCodec(\n paramDescriptor: ParamDescriptor,\n registry: CodecRegistry,\n): Codec | null {\n if (paramDescriptor.codecId) {\n const codec = registry.get(paramDescriptor.codecId);\n if (codec) {\n return codec;\n }\n }\n\n return null;\n}\n\nfunction paramLabel(paramDescriptor: ParamDescriptor, paramIndex: number): string {\n return paramDescriptor.name ?? `param[${paramIndex}]`;\n}\n\nfunction wrapEncodeFailure(\n error: unknown,\n paramDescriptor: ParamDescriptor,\n paramIndex: number,\n codecId: string,\n): never {\n const label = paramLabel(paramDescriptor, 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\n * a Promise can never leak into the driver, even if a sync-authored codec is\n * lifted to async by the codec() factory. Failures are wrapped in\n * `RUNTIME.ENCODE_FAILED` with `{ label, codec, paramIndex }` and the original\n * error attached on `cause`.\n */\nexport async function encodeParam(\n value: unknown,\n paramDescriptor: ParamDescriptor,\n paramIndex: number,\n registry: CodecRegistry,\n): Promise<unknown> {\n if (value === null || value === undefined) {\n return null;\n }\n\n const codec = resolveParamCodec(paramDescriptor, registry);\n if (!codec) {\n return value;\n }\n\n try {\n return await codec.encode(value);\n } catch (error) {\n wrapEncodeFailure(error, paramDescriptor, paramIndex, codec.id);\n }\n}\n\n/**\n * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-\n * and async-authored codecs share the same path: `codec.encode → await →\n * return`. Param-level failures are wrapped in `RUNTIME.ENCODE_FAILED`.\n */\nexport async function encodeParams(\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n): Promise<readonly unknown[]> {\n if (plan.params.length === 0) {\n return plan.params;\n }\n\n const descriptorCount = plan.meta.paramDescriptors.length;\n const paramCount = plan.params.length;\n\n const tasks: Promise<unknown>[] = new Array(paramCount);\n for (let i = 0; i < paramCount; i++) {\n const paramValue = plan.params[i];\n const paramDescriptor = plan.meta.paramDescriptors[i];\n\n if (!paramDescriptor) {\n throw runtimeError(\n 'RUNTIME.MISSING_PARAM_DESCRIPTOR',\n `Missing paramDescriptor for parameter at index ${i} (plan has ${paramCount} params, ${descriptorCount} descriptors). The planner must emit one descriptor per param; this is a contract violation.`,\n { paramIndex: i, paramCount, descriptorCount },\n );\n }\n\n tasks[i] = encodeParam(paramValue, paramDescriptor, i, registry);\n }\n\n const encoded = await Promise.all(tasks);\n return Object.freeze(encoded);\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 { 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}\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});\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 validatedRow = result as {\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 };\n\n const updatedAt = validatedRow.updated_at\n ? validatedRow.updated_at instanceof Date\n ? validatedRow.updated_at\n : new Date(validatedRow.updated_at)\n : new Date();\n\n return {\n storageHash: validatedRow.core_hash,\n profileHash: validatedRow.profile_hash,\n contractJson: validatedRow.contract_json ?? null,\n canonicalVersion: validatedRow.canonical_version ?? null,\n updatedAt,\n appTag: validatedRow.app_tag ?? null,\n meta: parseMeta(validatedRow.meta),\n };\n}\n","import type { ParamDescriptor, PlanMeta } from '@prisma-next/contract/types';\nimport type { AnyQueryAst } from '@prisma-next/sql-relational-core/ast';\nimport 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 if (current.ast === initial.ast) {\n return current;\n }\n\n // The rewritten AST may have introduced, removed, or replaced ParamRefs, so\n // the descriptors collected at lane build time no longer line up with what\n // the adapter will emit when it walks the new AST. Re-derive descriptors\n // from the rewritten AST so `params` and `paramDescriptors` stay in lockstep\n // by the time `encodeParams` runs.\n const paramDescriptors = deriveParamDescriptorsFromAst(current.ast);\n const meta: PlanMeta = { ...current.meta, paramDescriptors };\n return { ast: current.ast, meta };\n}\n\nfunction deriveParamDescriptorsFromAst(ast: AnyQueryAst): ReadonlyArray<ParamDescriptor> {\n const refs = ast.collectParamRefs();\n const seen = new Set<unknown>();\n const descriptors: ParamDescriptor[] = [];\n for (const ref of refs) {\n if (seen.has(ref)) continue;\n seen.add(ref);\n descriptors.push({\n index: descriptors.length + 1,\n ...(ref.name !== undefined ? { name: ref.name } : {}),\n source: 'dsl',\n ...(ref.codecId !== undefined ? { codecId: ref.codecId } : {}),\n });\n }\n return descriptors;\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 checkMiddlewareCompatibility,\n RuntimeCore,\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 CodecRegistry,\n LoweredStatement,\n SqlDriver,\n SqlQueryable,\n SqlTransaction,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { JsonSchemaValidatorRegistry } 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 { computeSqlFingerprint } from './fingerprint';\nimport { lowerSqlPlan } from './lower-sql-plan';\nimport { parseContractMarkerRow } from './marker';\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\n * connection is known to be in a clean state. If a transaction\n * commit/rollback failed or the connection is otherwise suspect, call\n * `destroy(reason)` instead.\n */\n release(): Promise<void>;\n /**\n * Evicts the connection so it is never reused. Call this when the\n * connection may be in an indeterminate state (e.g. a failed rollback\n * leaving an open transaction, or a broken socket).\n *\n * If teardown fails the error is propagated and the connection remains\n * retryable, so the caller can decide whether to swallow the failure or\n * retry cleanup. Calling destroy() or release() more than once after a\n * successful teardown is caller error.\n *\n * `reason` is advisory context only. It may be surfaced to driver-level\n * observability hooks (e.g. pg-pool's `'release'` event) but does not\n * 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\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 codecRegistry: CodecRegistry;\n private readonly jsonSchemaValidators: JsonSchemaValidatorRegistry | undefined;\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 ?? {\n info: () => {},\n warn: () => {},\n error: () => {},\n },\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.codecRegistry = context.codecs;\n this.jsonSchemaValidators = context.jsonSchemaValidators;\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.codecRegistry, context.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n /**\n * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan` with\n * encoded parameters ready for the driver. This is the single point at\n * which params transition from app-layer values to driver wire-format.\n */\n protected override async lower(plan: SqlQueryPlan): Promise<SqlExecutionPlan> {\n const lowered = lowerSqlPlan(this.adapter, this.contract, plan);\n return Object.freeze({\n ...lowered,\n params: await encodeParams(lowered, this.codecRegistry),\n });\n }\n\n /**\n * Default driver invocation. Production execution paths override the\n * queryable target (e.g. transaction or connection) by going through\n * `executeAgainstQueryable`; this implementation supports any caller of\n * `super.execute(plan)` and the abstract-base contract.\n */\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`\n * chain over the plan's draft (AST + meta) and returns a `SqlQueryPlan`\n * with the rewritten AST and meta when the chain mutates them. The chain\n * re-derives `meta.paramDescriptors` from the rewritten AST so descriptors\n * stay in lockstep with the params the adapter will emit during lowering.\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 ): AsyncIterableResult<Row> {\n return this.executeAgainstQueryable<Row>(plan, this.driver);\n }\n\n private executeAgainstQueryable<Row>(\n plan: SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>,\n queryable: SqlQueryable,\n ): AsyncIterableResult<Row> {\n this.ensureCodecRegistryValidated();\n\n const self = this;\n const generator = async function* (): AsyncGenerator<Row, void, unknown> {\n const exec: SqlExecutionPlan = isExecutionPlan(plan)\n ? Object.freeze({\n ...plan,\n params: await encodeParams(plan, self.codecRegistry),\n })\n : await self.lower(await self.runBeforeCompile(plan));\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 stream = runWithMiddleware<SqlExecutionPlan, Record<string, unknown>>(\n exec,\n self.middleware,\n self.ctx,\n () =>\n queryable.execute<Record<string, unknown>>({\n sql: exec.sql,\n params: exec.params,\n }),\n );\n\n for await (const rawRow of stream) {\n const decodedRow = await decodeRow(\n rawRow,\n exec,\n self.codecRegistry,\n self.jsonSchemaValidators,\n );\n yield decodedRow as Row;\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 ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverConn);\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 ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverTx);\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.codecRegistry, this.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n private async verifyMarker(): Promise<void> {\n if (this.verify.mode === 'always') {\n this.verified = false;\n }\n\n if (this.verified) {\n return;\n }\n\n const readStatement = this.familyAdapter.markerReader.readMarkerStatement();\n const result = await this.driver.query(readStatement.sql, readStatement.params);\n\n if (result.rows.length === 0) {\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 = parseContractMarkerRow(result.rows[0]);\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 ): AsyncIterableResult<Row> {\n if (invalidated) {\n throw transactionClosedError();\n }\n const inner = transaction.execute(plan);\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\n // decide what to do with them. Here, we're already about to throw a\n // more informative error describing why we're evicting the connection\n // (rollback/commit failure), so swallowing the teardown error is the\n // 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\n // committed (error on response path), (b) already rolled back (deferred\n // constraint / serialization failure), or (c) still open (COMMIT never\n // reached the server). Attempt a best-effort rollback to cover (c) and\n // confirm the protocol is healthy.\n //\n // If rollback succeeds, the server is definitely no longer in a\n // transaction (no-op in (a)/(b), real cleanup in (c)) and we've just\n // proved the connection round-trips correctly — it's safe to return\n // to the pool. If rollback fails, the connection state is ambiguous\n // (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;AAElC,MAAK,MAAM,SAAS,OAAO,OAAO,SAAS,QAAQ,OAAO,CACxD,MAAK,MAAM,UAAU,OAAO,OAAO,MAAM,QAAQ,EAAE;EACjD,MAAM,UAAU,OAAO;AACvB,WAAS,IAAI,QAAQ;;AAIzB,QAAO;;AAGT,SAAS,2BAA2B,UAAqD;CACvF,MAAM,2BAAW,IAAI,KAAqB;AAE1C,MAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,SAAS,QAAQ,OAAO,CACtE,MAAK,MAAM,CAAC,YAAY,WAAW,OAAO,QAAQ,MAAM,QAAQ,EAAE;EAChE,MAAM,UAAU,OAAO;EAC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U;WACtB;AACN,UAAM,kBAAkB,YAAY;;GAEtC,MAAM,UAAU,aACd,qCACA,6BACA,EAAE,aAAa,CAChB;AACD,WAAQ,QAAQ;AAChB,SAAM;;AAER,SAAO;WACC;AACR,MAAI,CAAC,mBACH,OAAM,WAAW,SAAS;;;AAKhC,SAAgB,cACd,SACS;CACT,MAAM,EAAE,eAAe,SAAS,QAAQ,QAAQ,YAAY,MAAM,QAAQ;AAE1E,QAAO,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"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { AfterExecuteResult, RuntimeMiddleware, RuntimeMiddlewareContext } from "@prisma-next/framework-components/runtime";
|
|
2
|
-
import { Adapter, AnyQueryAst, CodecParamsDescriptor, CodecRegistry, LoweredStatement, SqlDriver } from "@prisma-next/sql-relational-core/ast";
|
|
3
|
-
import { AfterExecuteResult as AfterExecuteResult$1, AsyncIterableResult, Log, Log as Log$1, MarkerStatement, Middleware, MiddlewareContext, RuntimeTelemetryEvent, RuntimeVerifyOptions, TelemetryOutcome } from "@prisma-next/runtime-executor";
|
|
1
|
+
import { AfterExecuteResult, AfterExecuteResult as AfterExecuteResult$1, ExecutionPlan, RuntimeLog, RuntimeLog as Log, RuntimeMiddleware, RuntimeMiddlewareContext } from "@prisma-next/framework-components/runtime";
|
|
2
|
+
import { Adapter, AnyQueryAst, CodecParamsDescriptor, CodecRegistry, LoweredStatement, MarkerStatement, MarkerStatement as MarkerStatement$1, SqlDriver } from "@prisma-next/sql-relational-core/ast";
|
|
4
3
|
import { ExecutionStack, ExecutionStackInstance, RuntimeAdapterDescriptor, RuntimeAdapterInstance, RuntimeDriverDescriptor, RuntimeDriverInstance, RuntimeExtensionDescriptor, RuntimeExtensionInstance, RuntimeTargetDescriptor, RuntimeTargetInstance } from "@prisma-next/framework-components/execution";
|
|
5
4
|
import { SqlOperationDescriptor } from "@prisma-next/sql-operations";
|
|
6
|
-
import { Contract,
|
|
5
|
+
import { Contract, PlanMeta } from "@prisma-next/contract/types";
|
|
7
6
|
import { SqlStorage } from "@prisma-next/sql-contract/types";
|
|
8
|
-
import { SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
|
|
7
|
+
import { SqlExecutionPlan, SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
|
|
9
8
|
import { ExecutionContext, TypeHelperRegistry } from "@prisma-next/sql-relational-core/query-lane-context";
|
|
9
|
+
import { RuntimeScope } from "@prisma-next/sql-relational-core/types";
|
|
10
10
|
|
|
11
11
|
//#region src/codecs/validation.d.ts
|
|
12
12
|
declare function extractCodecIds(contract: Contract<SqlStorage>): Set<string>;
|
|
@@ -22,7 +22,7 @@ declare function validateCodecRegistryCompleteness(registry: CodecRegistry, cont
|
|
|
22
22
|
* @param queryPlan - SQL query plan from a lane (contains AST, params, meta, but no SQL)
|
|
23
23
|
* @returns Fully executable Plan with SQL string
|
|
24
24
|
*/
|
|
25
|
-
declare function lowerSqlPlan<Row>(adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>, contract: Contract<SqlStorage>, queryPlan: SqlQueryPlan<Row>):
|
|
25
|
+
declare function lowerSqlPlan<Row>(adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>, contract: Contract<SqlStorage>, queryPlan: SqlQueryPlan<Row>): SqlExecutionPlan<Row>;
|
|
26
26
|
//#endregion
|
|
27
27
|
//#region src/middleware/sql-middleware.d.ts
|
|
28
28
|
interface SqlMiddlewareContext extends RuntimeMiddlewareContext {
|
|
@@ -36,7 +36,7 @@ interface DraftPlan {
|
|
|
36
36
|
readonly ast: AnyQueryAst;
|
|
37
37
|
readonly meta: PlanMeta;
|
|
38
38
|
}
|
|
39
|
-
interface SqlMiddleware extends RuntimeMiddleware {
|
|
39
|
+
interface SqlMiddleware extends RuntimeMiddleware<SqlExecutionPlan> {
|
|
40
40
|
readonly familyId?: 'sql';
|
|
41
41
|
/**
|
|
42
42
|
* Rewrite the query AST before it is lowered to SQL. Middlewares run in
|
|
@@ -57,9 +57,9 @@ interface SqlMiddleware extends RuntimeMiddleware {
|
|
|
57
57
|
* See `docs/architecture docs/subsystems/4. Runtime & Middleware Framework.md`.
|
|
58
58
|
*/
|
|
59
59
|
beforeCompile?(draft: DraftPlan, ctx: SqlMiddlewareContext): Promise<DraftPlan | undefined>;
|
|
60
|
-
beforeExecute?(plan:
|
|
61
|
-
onRow?(row: Record<string, unknown>, plan:
|
|
62
|
-
afterExecute?(plan:
|
|
60
|
+
beforeExecute?(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext): Promise<void>;
|
|
61
|
+
onRow?(row: Record<string, unknown>, plan: SqlExecutionPlan, ctx: SqlMiddlewareContext): Promise<void>;
|
|
62
|
+
afterExecute?(plan: SqlExecutionPlan, result: AfterExecuteResult, ctx: SqlMiddlewareContext): Promise<void>;
|
|
63
63
|
}
|
|
64
64
|
//#endregion
|
|
65
65
|
//#region src/middleware/budgets.d.ts
|
|
@@ -103,6 +103,44 @@ interface LintsOptions {
|
|
|
103
103
|
*/
|
|
104
104
|
declare function lints(options?: LintsOptions): SqlMiddleware;
|
|
105
105
|
//#endregion
|
|
106
|
+
//#region src/runtime-spi.d.ts
|
|
107
|
+
/**
|
|
108
|
+
* Reader of the SQL contract marker. SQL runtimes verify the database's
|
|
109
|
+
* `prisma_contract.marker` row against the runtime's contract by issuing
|
|
110
|
+
* this statement before executing user queries (when `verify` is enabled).
|
|
111
|
+
*
|
|
112
|
+
* Structurally satisfied by `AdapterProfile`, which already exposes
|
|
113
|
+
* `readMarkerStatement(): MarkerStatement` for adapter-level introspection.
|
|
114
|
+
*/
|
|
115
|
+
interface MarkerReader {
|
|
116
|
+
readMarkerStatement(): MarkerStatement;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* SQL family adapter SPI consumed by `SqlRuntime`. Encapsulates the
|
|
120
|
+
* runtime contract, marker reader, and plan validation logic so the
|
|
121
|
+
* runtime can be unit-tested without a concrete SQL adapter profile.
|
|
122
|
+
*
|
|
123
|
+
* Implemented by `SqlFamilyAdapter` for production and by mock classes
|
|
124
|
+
* in tests.
|
|
125
|
+
*/
|
|
126
|
+
interface RuntimeFamilyAdapter<TContract = unknown> {
|
|
127
|
+
readonly contract: TContract;
|
|
128
|
+
readonly markerReader: MarkerReader;
|
|
129
|
+
validatePlan(plan: ExecutionPlan, contract: TContract): void;
|
|
130
|
+
}
|
|
131
|
+
interface RuntimeVerifyOptions {
|
|
132
|
+
readonly mode: 'onFirstUse' | 'startup' | 'always';
|
|
133
|
+
readonly requireMarker: boolean;
|
|
134
|
+
}
|
|
135
|
+
type TelemetryOutcome = 'success' | 'runtime-error';
|
|
136
|
+
interface RuntimeTelemetryEvent {
|
|
137
|
+
readonly lane: string;
|
|
138
|
+
readonly target: string;
|
|
139
|
+
readonly fingerprint: string;
|
|
140
|
+
readonly outcome: TelemetryOutcome;
|
|
141
|
+
readonly durationMs?: number;
|
|
142
|
+
}
|
|
143
|
+
//#endregion
|
|
106
144
|
//#region src/sql-context.d.ts
|
|
107
145
|
/**
|
|
108
146
|
* Runtime parameterized codec descriptor.
|
|
@@ -182,6 +220,7 @@ interface WriteContractMarkerStatements {
|
|
|
182
220
|
declare function writeContractMarker(input: WriteMarkerInput): WriteContractMarkerStatements;
|
|
183
221
|
//#endregion
|
|
184
222
|
//#region src/sql-runtime.d.ts
|
|
223
|
+
type Log$1 = RuntimeLog;
|
|
185
224
|
interface CreateRuntimeOptions<TContract extends Contract<SqlStorage> = Contract<SqlStorage>, TTargetId extends string = string> {
|
|
186
225
|
readonly stackInstance: ExecutionStackInstance<'sql', TTargetId, SqlRuntimeAdapterInstance<TTargetId>, RuntimeDriverInstance<'sql', TTargetId>, SqlRuntimeExtensionInstance<TTargetId>>;
|
|
187
226
|
readonly context: ExecutionContext<TContract>;
|
|
@@ -189,7 +228,7 @@ interface CreateRuntimeOptions<TContract extends Contract<SqlStorage> = Contract
|
|
|
189
228
|
readonly verify: RuntimeVerifyOptions;
|
|
190
229
|
readonly middleware?: readonly SqlMiddleware[];
|
|
191
230
|
readonly mode?: 'strict' | 'permissive';
|
|
192
|
-
readonly log?: Log;
|
|
231
|
+
readonly log?: Log$1;
|
|
193
232
|
}
|
|
194
233
|
interface Runtime extends RuntimeQueryable {
|
|
195
234
|
connection(): Promise<RuntimeConnection>;
|
|
@@ -225,14 +264,12 @@ interface RuntimeTransaction extends RuntimeQueryable {
|
|
|
225
264
|
commit(): Promise<void>;
|
|
226
265
|
rollback(): Promise<void>;
|
|
227
266
|
}
|
|
228
|
-
interface RuntimeQueryable {
|
|
229
|
-
execute<Row = Record<string, unknown>>(plan: ExecutionPlan<Row> | SqlQueryPlan<Row>): AsyncIterableResult<Row>;
|
|
230
|
-
}
|
|
267
|
+
interface RuntimeQueryable extends RuntimeScope {}
|
|
231
268
|
interface TransactionContext extends RuntimeQueryable {
|
|
232
269
|
readonly invalidated: boolean;
|
|
233
270
|
}
|
|
234
271
|
declare function withTransaction<R>(runtime: Runtime, fn: (tx: TransactionContext) => PromiseLike<R>): Promise<R>;
|
|
235
272
|
declare function createRuntime<TContract extends Contract<SqlStorage>, TTargetId extends string>(options: CreateRuntimeOptions<TContract, TTargetId>): Runtime;
|
|
236
273
|
//#endregion
|
|
237
|
-
export {
|
|
238
|
-
//# sourceMappingURL=index-
|
|
274
|
+
export { createExecutionContext as A, budgets as B, SqlRuntimeAdapterInstance as C, SqlRuntimeTargetDescriptor as D, SqlRuntimeExtensionInstance as E, RuntimeVerifyOptions as F, validateCodecRegistryCompleteness as G, SqlMiddlewareContext as H, TelemetryOutcome as I, validateContractCodecMappings as K, LintsOptions as L, MarkerReader as M, RuntimeFamilyAdapter as N, SqlStaticContributions as O, RuntimeTelemetryEvent as P, lints as R, SqlRuntimeAdapterDescriptor as S, SqlRuntimeExtensionDescriptor as T, lowerSqlPlan as U, SqlMiddleware as V, extractCodecIds as W, ExecutionContext as _, Runtime as a, SqlExecutionStack as b, RuntimeTransaction as c, withTransaction as d, SqlStatement as f, writeContractMarker as g, readContractMarker as h, CreateRuntimeOptions as i, createSqlExecutionStack as j, TypeHelperRegistry as k, TransactionContext as l, ensureTableStatement as m, Log as n, RuntimeConnection as o, ensureSchemaStatement as p, MarkerStatement$1 as r, RuntimeQueryable as s, AfterExecuteResult$1 as t, createRuntime as u, RuntimeMutationDefaultGenerator as v, SqlRuntimeDriverInstance as w, SqlExecutionStackWithDriver as x, RuntimeParameterizedCodecDescriptor as y, BudgetsOptions as z };
|
|
275
|
+
//# sourceMappingURL=index-CZmC2kD3.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-CZmC2kD3.d.mts","names":[],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/middleware/sql-middleware.ts","../src/middleware/budgets.ts","../src/middleware/lints.ts","../src/runtime-spi.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/sql-runtime.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;iBAKgB,eAAA,WAA0B,SAAS,cAAc;iBA2BjD,6BAAA,WACJ,yBACA,SAAS;iBA4BL,iCAAA,WACJ,yBACA,SAAS;;;;;;;;;;AA3DrB;AAAmD,iBCQnC,YDRmC,CAAA,GAAA,CAAA,CAAA,OAAA,ECSxC,ODTwC,CCShC,WDTgC,ECSnB,QDTmB,CCSV,UDTU,CAAA,ECSG,gBDTH,CAAA,EAAA,QAAA,ECUvC,QDVuC,CCU9B,UDV8B,CAAA,EAAA,SAAA,ECWtC,YDXsC,CCWzB,GDXyB,CAAA,CAAA,ECYhD,gBDZgD,CCY/B,GDZ+B,CAAA;;;UEKlC,oBAAA,SAA6B;qBACzB,SAAS;;;;;AFN9B;AAAmD,UEalC,SAAA,CFbkC;EAAT,SAAA,GAAA,EEc1B,WFd0B;EAAuB,SAAA,IAAA,EEehD,QFfgD;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KA;;;;;EAoB+D,OAAA,CAAA,MAAA,CAAA,EAAA,OAAA,CAAA,EMiElC,ONjEkC,CAAA,IAAA,CAAA;;AACjB,UMmE7B,kBAAA,SAA2B,gBNnEE,CAAA;EAAuB,MAAA,EAAA,EMoEzD,ONpEyD,CAAA,IAAA,CAAA;EAE5D,QAAA,EAAA,EMmEK,ONnEL,CAAA,IAAA,CAAA;;AAEA,UMoEQ,gBAAA,SAAyB,YNpEjC,CAAA;AAGC,UMmEO,kBAAA,SAA2B,gBNnElC,CAAA;EACE,SAAA,WAAA,EAAA,OAAA;;AA7B2B,iBMmajB,eNnaiB,CAAA,CAAA,CAAA,CAAA,OAAA,EMoa5B,ONpa4B,EAAA,EAAA,EAAA,CAAA,EAAA,EMqa5B,kBNra4B,EAAA,GMqaL,WNraK,CMqaO,CNraP,CAAA,CAAA,EMsapC,ONtaoC,CMsa5B,CNta4B,CAAA;AAAiB,iBMugBxC,aNvgBwC,CAAA,kBMugBR,QNvgBQ,CMugBC,UNvgBD,CAAA,EAAA,kBAAA,MAAA,CAAA,CAAA,OAAA,EMwgB7C,oBNxgB6C,CMwgBxB,SNxgBwB,EMwgBb,SNxgBa,CAAA,CAAA,EMygBrD,ONzgBqD"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
export { AfterExecuteResult, BudgetsOptions, CreateRuntimeOptions, ExecutionContext, LintsOptions, Log,
|
|
1
|
+
import { A as createExecutionContext, B as budgets, C as SqlRuntimeAdapterInstance, D as SqlRuntimeTargetDescriptor, E as SqlRuntimeExtensionInstance, F as RuntimeVerifyOptions, G as validateCodecRegistryCompleteness, H as SqlMiddlewareContext, I as TelemetryOutcome, K as validateContractCodecMappings, L as LintsOptions, M as MarkerReader, N as RuntimeFamilyAdapter, O as SqlStaticContributions, P as RuntimeTelemetryEvent, R as lints, S as SqlRuntimeAdapterDescriptor, T as SqlRuntimeExtensionDescriptor, U as lowerSqlPlan, V as SqlMiddleware, W as extractCodecIds, _ as ExecutionContext, a as Runtime, b as SqlExecutionStack, c as RuntimeTransaction, d as withTransaction, f as SqlStatement, g as writeContractMarker, h as readContractMarker, i as CreateRuntimeOptions, j as createSqlExecutionStack, k as TypeHelperRegistry, l as TransactionContext, m as ensureTableStatement, n as Log, o as RuntimeConnection, p as ensureSchemaStatement, r as MarkerStatement, s as RuntimeQueryable, t as AfterExecuteResult, u as createRuntime, v as RuntimeMutationDefaultGenerator, w as SqlRuntimeDriverInstance, x as SqlExecutionStackWithDriver, y as RuntimeParameterizedCodecDescriptor, z as BudgetsOptions } from "./index-CZmC2kD3.mjs";
|
|
2
|
+
export { AfterExecuteResult, BudgetsOptions, CreateRuntimeOptions, ExecutionContext, LintsOptions, Log, MarkerReader, MarkerStatement, Runtime, RuntimeConnection, RuntimeFamilyAdapter, RuntimeMutationDefaultGenerator, RuntimeParameterizedCodecDescriptor, RuntimeQueryable, RuntimeTelemetryEvent, RuntimeTransaction, RuntimeVerifyOptions, SqlExecutionStack, SqlExecutionStackWithDriver, SqlMiddleware, SqlMiddlewareContext, SqlRuntimeAdapterDescriptor, SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance, SqlRuntimeExtensionDescriptor, SqlRuntimeExtensionInstance, SqlRuntimeTargetDescriptor, SqlStatement, SqlStaticContributions, TelemetryOutcome, TransactionContext, TypeHelperRegistry, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as readContractMarker, c as createSqlExecutionStack, d as lowerSqlPlan, f as extractCodecIds, i as ensureTableStatement, l as lints, m as validateContractCodecMappings, n as withTransaction, o as writeContractMarker, p as validateCodecRegistryCompleteness, r as ensureSchemaStatement, s as createExecutionContext, t as createRuntime, u as budgets } from "./exports-
|
|
1
|
+
import { a as readContractMarker, c as createSqlExecutionStack, d as lowerSqlPlan, f as extractCodecIds, i as ensureTableStatement, l as lints, m as validateContractCodecMappings, n as withTransaction, o as writeContractMarker, p as validateCodecRegistryCompleteness, r as ensureSchemaStatement, s as createExecutionContext, t as createRuntime, u as budgets } from "./exports-BOHa3Emo.mjs";
|
|
2
2
|
|
|
3
3
|
export { budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
|
package/dist/test/utils.d.mts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as SqlRuntimeAdapterInstance, D as SqlRuntimeTargetDescriptor, E as SqlRuntimeExtensionInstance, S as SqlRuntimeAdapterDescriptor, T as SqlRuntimeExtensionDescriptor, _ as ExecutionContext, f as SqlStatement, u as createRuntime, w as SqlRuntimeDriverInstance } from "../index-CZmC2kD3.mjs";
|
|
2
|
+
import { ResultType } from "@prisma-next/framework-components/runtime";
|
|
2
3
|
import { Adapter, LoweredStatement, SelectAst } from "@prisma-next/sql-relational-core/ast";
|
|
3
4
|
import * as _prisma_next_framework_components_execution0 from "@prisma-next/framework-components/execution";
|
|
4
5
|
import { RuntimeDriverDescriptor } from "@prisma-next/framework-components/execution";
|
|
5
|
-
import { Contract
|
|
6
|
+
import { Contract } from "@prisma-next/contract/types";
|
|
6
7
|
import { DevDatabase, collectAsync, createDevDatabase, teardownTestDatabase, withClient } from "@prisma-next/test-utils";
|
|
7
8
|
import { SqlStorage } from "@prisma-next/sql-contract/types";
|
|
8
|
-
import { SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
|
|
9
|
+
import { SqlExecutionPlan, SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
|
|
9
10
|
import { Client } from "pg";
|
|
10
11
|
|
|
11
12
|
//#region test/utils.d.ts
|
|
@@ -15,12 +16,12 @@ import { Client } from "pg";
|
|
|
15
16
|
* This helper DRYs up the common pattern of executing plans in tests.
|
|
16
17
|
* The return type is inferred from the plan's type parameter.
|
|
17
18
|
*/
|
|
18
|
-
declare function executePlanAndCollect<P extends
|
|
19
|
+
declare function executePlanAndCollect<P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]>;
|
|
19
20
|
/**
|
|
20
21
|
* Drains a plan execution, consuming all results without collecting them.
|
|
21
22
|
* Useful for testing side effects without memory overhead.
|
|
22
23
|
*/
|
|
23
|
-
declare function drainPlanExecution(runtime: ReturnType<typeof createRuntime>, plan:
|
|
24
|
+
declare function drainPlanExecution(runtime: ReturnType<typeof createRuntime>, plan: SqlExecutionPlan | SqlQueryPlan<unknown>): Promise<void>;
|
|
24
25
|
/**
|
|
25
26
|
* Executes a SQL statement on a database client.
|
|
26
27
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","names":[],"sources":["../../test/utils.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.d.mts","names":[],"sources":["../../test/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;AA6CA;;;AACY,iBADU,qBACV,CAAA,UAAA,gBAAA,CAAiB,UAAjB,CAA4B,CAA5B,CAAA,CAAA,GAAkC,YAAlC,CAA+C,UAA/C,CAA0D,CAA1D,CAAA,CAAA,CAAA,CAAA,OAAA,EACD,UADC,CAAA,OACiB,aADjB,CAAA,EAAA,IAAA,EACuC,CADvC,CAAA,EAC2C,OAD3C,CACmD,UADnD,CAC8D,CAD9D,CAAA,EAAA,CAAA;;;;;AACD,iBASW,kBAAA,CATX,OAAA,EAUA,UAVA,CAAA,OAUkB,aAVlB,CAAA,EAAA,IAAA,EAWH,gBAXG,GAWgB,YAXhB,CAAA,OAAA,CAAA,CAAA,EAYR,OA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AA,CAAA,EA6DjC,aA7DiC,CA6DnB,6BA7DmB,CAAA,UAAA,CAAA,CAAA;EAAzC,MAAA,CAAA,EA8DA,uBA9DA,CAAA,KAAA,EAAA,UAAA,EAAA,OAAA,EAkEP,wBAlEO,CAAA,UAAA,CAAA,CAAA;CACR,CAAA,EAmEF,4CAAA,CAAA,sBAnEE,CAAA,KAAA,EAAA,UAAA,EAmEF,yBAnEE,CAAA,UAAA,CAAA,EAmEF,wBAnEE,CAAA,UAAA,CAAA,EAmEF,2BAnEE,CAAA,UAAA,CAAA,CAAA;;AAoBH;AAsBA;;;;;AAEuC,iBAyCvB,iBAAA,CAAA,CAzCuB,EAyCF,OAzCE,CAyCM,SAzCN,EAyCiB,QAzCjB,CAyC0B,UAzC1B,CAAA,EAyCuC,gBAzCvC,CAAA;AAAT,iBAuGd,kBAAA,CAvGc,QAAA,EAwGlB,OAxGkB,CAwGV,IAxGU,CAwGL,QAxGK,CAwGI,UAxGJ,CAAA,EAAA,aAAA,GAAA,SAAA,CAAA,CAAA,GAAA;EAAsB,WAAA,CAAA,EAAA,MAAA;EAAzC,WAAA,CAAA,EAAA,MAAA;EAEwB,OAAA,CAAA,EAyGrB,IAzGqB,CAyGhB,UAzGgB,EAAA,aAAA,CAAA;CAAd,CAAA,EA2GlB,QA3GkB,CA2GT,UA3GS,CAAA"}
|
package/dist/test/utils.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as createSqlExecutionStack, i as ensureTableStatement, o as writeContractMarker, r as ensureSchemaStatement, s as createExecutionContext } from "../exports-
|
|
1
|
+
import { c as createSqlExecutionStack, i as ensureTableStatement, o as writeContractMarker, r as ensureSchemaStatement, s as createExecutionContext } from "../exports-BOHa3Emo.mjs";
|
|
2
2
|
import { codec, createCodecRegistry } from "@prisma-next/sql-relational-core/ast";
|
|
3
3
|
import { instantiateExecutionStack } from "@prisma-next/framework-components/execution";
|
|
4
4
|
import { coreHash, profileHash } from "@prisma-next/contract/types";
|
|
@@ -164,7 +164,12 @@ function createStubAdapter() {
|
|
|
164
164
|
typeId: "pg/timestamptz@1",
|
|
165
165
|
targetTypes: ["timestamptz"],
|
|
166
166
|
encode: (value) => value instanceof Date ? value.toISOString() : value,
|
|
167
|
-
decode: (wire) => wire instanceof Date ? wire : new Date(wire)
|
|
167
|
+
decode: (wire) => wire instanceof Date ? wire : new Date(wire),
|
|
168
|
+
encodeJson: (value) => value instanceof Date ? value.toISOString() : value,
|
|
169
|
+
decodeJson: (json) => {
|
|
170
|
+
if (typeof json !== "string") throw new Error("expected ISO date string");
|
|
171
|
+
return new Date(json);
|
|
172
|
+
}
|
|
168
173
|
}));
|
|
169
174
|
return {
|
|
170
175
|
profile: {
|
package/dist/test/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","names":["collectAsync"],"sources":["../../test/utils.ts"],"sourcesContent":["import type { Contract, ExecutionPlan, ResultType } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Adapter, LoweredStatement, SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport { codec, createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array.\n * This helper DRYs up the common pattern of executing plans in tests.\n * The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends ExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them.\n * Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: ExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker.\n * This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database.\n * This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter.\n * Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions\n * derived from the adapter's codec registry.\n */\nexport function createTestAdapterDescriptor(\n adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const codecRegistry = adapter.profile.codecs();\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => codecRegistry,\n parameterizedCodecs: () => [],\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => createCodecRegistry(),\n parameterizedCodecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing.\n * This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the\n * adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Creates a stub adapter for testing.\n * This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1)\n * to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> {\n const codecRegistry = createCodecRegistry();\n\n // Register stub codecs for common test types\n // These match the codec IDs used in test contracts (pg/int4@1, pg/text@1, pg/timestamptz@1)\n // but don't require importing from the postgres adapter package\n codecRegistry.register(\n codec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n );\n\n codecRegistry.register(\n codec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n );\n\n codecRegistry.register(\n codec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: string | Date) => (value instanceof Date ? value.toISOString() : value),\n decode: (wire: string | Date) => (wire instanceof Date ? wire : new Date(wire)),\n }),\n );\n\n return {\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n codecs() {\n return codecRegistry;\n },\n readMarkerStatement() {\n return {\n sql: 'select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1',\n params: [1],\n };\n },\n },\n lower(ast: SelectAst, ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n return Object.freeze({ sql: sqlText, params: ctx.params ? [...ctx.params] : [] });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorage, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? { ...rest['storage'], storageHash: storageHashValue }\n : { storageHash: storageHashValue, tables: {} },\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;;AAgCA,SAAS,sCAAsC;AAC7C,QAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC,WAAW,SAAS;GAAE;GAAI;GAAQ,GAAG,EAAE,IAAI,CAAC;EAC7F,EAAE;;;;;;;AAQL,eAAsB,sBAEpB,SAA2C,MAAmC;AAE9E,QAAOA,eAAkB,QAAQ,QAAa,KAAK,CAAC;;;;;;AAOtD,eAAsB,mBACpB,SACA,MACe;AACf,QAAO,mBAAmB,QAAQ,QAAQ,KAAK,CAAC;;;;;AAMlD,eAAsB,iBAAiB,QAAgB,WAAwC;AAC7F,KAAI,UAAU,OAAO,SAAS,GAAG;AAC/B,QAAM,OAAO,MAAM,UAAU,KAAK,CAAC,GAAG,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,KAAK;GAAY,aAAa;GAAkB,GACrD;GAAE,aAAa;GAAkB,QAAQ,EAAE;GAAE;EACjD,QAAQ,KAAK,aAAa,EAAE;EAC5B,OAAO,KAAK,YAAY,EAAE;EAC1B,cAAc,KAAK,mBAAmB,EAAE;EACxC,gBAAgB,KAAK,qBAAqB,EAAE;EAC5C,MAAM,KAAK,WAAW,EAAE;EACxB,GAAI,YAAY,EAAE,WAAW,GAAG,EAAE;EAClC,aAAa,YAAY,KAAK,kBAAkB,qBAAqB;EACtE"}
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":["collectAsync"],"sources":["../../test/utils.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Adapter, LoweredStatement, SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport { codec, createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array.\n * This helper DRYs up the common pattern of executing plans in tests.\n * The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them.\n * Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker.\n * This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database.\n * This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter.\n * Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions\n * derived from the adapter's codec registry.\n */\nexport function createTestAdapterDescriptor(\n adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const codecRegistry = adapter.profile.codecs();\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => codecRegistry,\n parameterizedCodecs: () => [],\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => createCodecRegistry(),\n parameterizedCodecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing.\n * This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the\n * adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Creates a stub adapter for testing.\n * This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1)\n * to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> {\n const codecRegistry = createCodecRegistry();\n\n // Register stub codecs for common test types\n // These match the codec IDs used in test contracts (pg/int4@1, pg/text@1, pg/timestamptz@1)\n // but don't require importing from the postgres adapter package\n codecRegistry.register(\n codec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n );\n\n codecRegistry.register(\n codec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n );\n\n codecRegistry.register(\n codec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: string | Date) => (value instanceof Date ? value.toISOString() : value),\n decode: (wire: string | Date) => (wire instanceof Date ? wire : new Date(wire)),\n // string | Date includes Date which is not assignable to JsonValue, so\n // the JSON round-trip pair must be supplied explicitly.\n encodeJson: (value: string | Date) => (value instanceof Date ? value.toISOString() : value),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n );\n\n return {\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n codecs() {\n return codecRegistry;\n },\n readMarkerStatement() {\n return {\n sql: 'select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1',\n params: [1],\n };\n },\n },\n lower(ast: SelectAst, ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n return Object.freeze({ sql: sqlText, params: ctx.params ? [...ctx.params] : [] });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorage, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? { ...rest['storage'], storageHash: storageHashValue }\n : { storageHash: storageHashValue, tables: {} },\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;;AAiCA,SAAS,sCAAsC;AAC7C,QAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC,WAAW,SAAS;GAAE;GAAI;GAAQ,GAAG,EAAE,IAAI,CAAC;EAC7F,EAAE;;;;;;;AAQL,eAAsB,sBAEpB,SAA2C,MAAmC;AAE9E,QAAOA,eAAkB,QAAQ,QAAa,KAAK,CAAC;;;;;;AAOtD,eAAsB,mBACpB,SACA,MACe;AACf,QAAO,mBAAmB,QAAQ,QAAQ,KAAK,CAAC;;;;;AAMlD,eAAsB,iBAAiB,QAAgB,WAAwC;AAC7F,KAAI,UAAU,OAAO,SAAS,GAAG;AAC/B,QAAM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