@prisma-next/sql-contract-ts
Advanced tools
| // src/contract.ts | ||
| import { type } from "arktype"; | ||
| var StorageColumnSchema = type.declare().type({ | ||
| nativeType: "string", | ||
| codecId: "string", | ||
| nullable: "boolean" | ||
| }); | ||
| var PrimaryKeySchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| var UniqueConstraintSchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| var IndexSchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| var ForeignKeyReferencesSchema = type.declare().type({ | ||
| table: "string", | ||
| columns: type.string.array().readonly() | ||
| }); | ||
| var ForeignKeySchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| references: ForeignKeyReferencesSchema, | ||
| "name?": "string" | ||
| }); | ||
| var StorageTableSchema = type.declare().type({ | ||
| columns: type({ "[string]": StorageColumnSchema }), | ||
| "primaryKey?": PrimaryKeySchema, | ||
| uniques: UniqueConstraintSchema.array().readonly(), | ||
| indexes: IndexSchema.array().readonly(), | ||
| foreignKeys: ForeignKeySchema.array().readonly() | ||
| }); | ||
| var StorageSchema = type.declare().type({ | ||
| tables: type({ "[string]": StorageTableSchema }) | ||
| }); | ||
| var ModelFieldSchema = type.declare().type({ | ||
| column: "string" | ||
| }); | ||
| var ModelStorageSchema = type.declare().type({ | ||
| table: "string" | ||
| }); | ||
| var ModelSchema = type.declare().type({ | ||
| storage: ModelStorageSchema, | ||
| fields: type({ "[string]": ModelFieldSchema }), | ||
| relations: type({ "[string]": "unknown" }) | ||
| }); | ||
| var SqlContractSchema = type({ | ||
| "schemaVersion?": "'1'", | ||
| target: "string", | ||
| targetFamily: "'sql'", | ||
| coreHash: "string", | ||
| "profileHash?": "string", | ||
| "capabilities?": "Record<string, Record<string, boolean>>", | ||
| "extensions?": "Record<string, unknown>", | ||
| "meta?": "Record<string, unknown>", | ||
| "sources?": "Record<string, unknown>", | ||
| models: type({ "[string]": ModelSchema }), | ||
| storage: StorageSchema | ||
| }); | ||
| function validateContractStructure(value) { | ||
| const rawValue = value; | ||
| if (rawValue.targetFamily !== void 0 && rawValue.targetFamily !== "sql") { | ||
| throw new Error(`Unsupported target family: ${rawValue.targetFamily}`); | ||
| } | ||
| const contractResult = SqlContractSchema(value); | ||
| if (contractResult instanceof type.errors) { | ||
| const messages = contractResult.map((p) => p.message).join("; "); | ||
| throw new Error(`Contract structural validation failed: ${messages}`); | ||
| } | ||
| return contractResult; | ||
| } | ||
| function computeMappings(models, _storage, existingMappings) { | ||
| const modelToTable = {}; | ||
| const tableToModel = {}; | ||
| const fieldToColumn = {}; | ||
| const columnToField = {}; | ||
| for (const [modelName, model] of Object.entries(models)) { | ||
| const tableName = model.storage.table; | ||
| modelToTable[modelName] = tableName; | ||
| tableToModel[tableName] = modelName; | ||
| const modelFieldToColumn = {}; | ||
| for (const [fieldName, field] of Object.entries(model.fields)) { | ||
| const columnName = field.column; | ||
| modelFieldToColumn[fieldName] = columnName; | ||
| if (!columnToField[tableName]) { | ||
| columnToField[tableName] = {}; | ||
| } | ||
| columnToField[tableName][columnName] = fieldName; | ||
| } | ||
| fieldToColumn[modelName] = modelFieldToColumn; | ||
| } | ||
| return { | ||
| modelToTable: existingMappings?.modelToTable ?? modelToTable, | ||
| tableToModel: existingMappings?.tableToModel ?? tableToModel, | ||
| fieldToColumn: existingMappings?.fieldToColumn ?? fieldToColumn, | ||
| columnToField: existingMappings?.columnToField ?? columnToField, | ||
| codecTypes: existingMappings?.codecTypes ?? {}, | ||
| operationTypes: existingMappings?.operationTypes ?? {} | ||
| }; | ||
| } | ||
| function validateContractLogic(structurallyValidatedContract) { | ||
| const { storage, models } = structurallyValidatedContract; | ||
| const tableNames = new Set(Object.keys(storage.tables)); | ||
| for (const [modelName, modelUnknown] of Object.entries(models)) { | ||
| const model = modelUnknown; | ||
| if (!model.storage?.table) { | ||
| throw new Error(`Model "${modelName}" is missing storage.table`); | ||
| } | ||
| const tableName = model.storage.table; | ||
| if (!tableNames.has(tableName)) { | ||
| throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`); | ||
| } | ||
| const table = storage.tables[tableName]; | ||
| if (!table) { | ||
| throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`); | ||
| } | ||
| if (!table.primaryKey) { | ||
| throw new Error(`Model "${modelName}" table "${tableName}" is missing a primary key`); | ||
| } | ||
| const columnNames = new Set(Object.keys(table.columns)); | ||
| if (!model.fields) { | ||
| throw new Error(`Model "${modelName}" is missing fields`); | ||
| } | ||
| for (const [fieldName, fieldUnknown] of Object.entries(model.fields)) { | ||
| const field = fieldUnknown; | ||
| if (!field.column) { | ||
| throw new Error(`Model "${modelName}" field "${fieldName}" is missing column property`); | ||
| } | ||
| if (!columnNames.has(field.column)) { | ||
| throw new Error( | ||
| `Model "${modelName}" field "${fieldName}" references non-existent column "${field.column}" in table "${tableName}"` | ||
| ); | ||
| } | ||
| } | ||
| if (model.relations) { | ||
| for (const [relationName, relation] of Object.entries(model.relations)) { | ||
| if (typeof relation === "object" && relation !== null && "on" in relation && "to" in relation) { | ||
| const on = relation.on; | ||
| const cardinality = relation.cardinality; | ||
| if (on.parentCols && on.childCols) { | ||
| if (cardinality === "1:N") { | ||
| continue; | ||
| } | ||
| const hasMatchingFk = table.foreignKeys?.some((fk) => { | ||
| return fk.columns.length === on.childCols?.length && fk.columns.every((col, i) => col === on.childCols?.[i]) && fk.references.table && fk.references.columns.length === on.parentCols?.length && fk.references.columns.every((col, i) => col === on.parentCols?.[i]); | ||
| }); | ||
| if (!hasMatchingFk) { | ||
| throw new Error( | ||
| `Model "${modelName}" relation "${relationName}" does not have a corresponding foreign key in table "${tableName}"` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| for (const [tableName, table] of Object.entries(storage.tables)) { | ||
| const columnNames = new Set(Object.keys(table.columns)); | ||
| if (table.primaryKey) { | ||
| for (const colName of table.primaryKey.columns) { | ||
| if (!columnNames.has(colName)) { | ||
| throw new Error( | ||
| `Table "${tableName}" primaryKey references non-existent column "${colName}"` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| for (const unique of table.uniques) { | ||
| for (const colName of unique.columns) { | ||
| if (!columnNames.has(colName)) { | ||
| throw new Error( | ||
| `Table "${tableName}" unique constraint references non-existent column "${colName}"` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| for (const index of table.indexes) { | ||
| for (const colName of index.columns) { | ||
| if (!columnNames.has(colName)) { | ||
| throw new Error(`Table "${tableName}" index references non-existent column "${colName}"`); | ||
| } | ||
| } | ||
| } | ||
| for (const fk of table.foreignKeys) { | ||
| for (const colName of fk.columns) { | ||
| if (!columnNames.has(colName)) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey references non-existent column "${colName}"` | ||
| ); | ||
| } | ||
| } | ||
| if (!tableNames.has(fk.references.table)) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"` | ||
| ); | ||
| } | ||
| const referencedTable = storage.tables[fk.references.table]; | ||
| if (!referencedTable) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"` | ||
| ); | ||
| } | ||
| const referencedColumnNames = new Set(Object.keys(referencedTable.columns)); | ||
| for (const colName of fk.references.columns) { | ||
| if (!referencedColumnNames.has(colName)) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey references non-existent column "${colName}" in table "${fk.references.table}"` | ||
| ); | ||
| } | ||
| } | ||
| if (fk.columns.length !== fk.references.columns.length) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| function normalizeContract(contract) { | ||
| const contractObj = contract; | ||
| let normalizedStorage = contractObj["storage"]; | ||
| if (normalizedStorage && typeof normalizedStorage === "object" && normalizedStorage !== null) { | ||
| const storage = normalizedStorage; | ||
| const tables = storage["tables"]; | ||
| if (tables) { | ||
| const normalizedTables = {}; | ||
| for (const [tableName, table] of Object.entries(tables)) { | ||
| const tableObj = table; | ||
| const columns = tableObj["columns"]; | ||
| if (columns) { | ||
| const normalizedColumns = {}; | ||
| for (const [columnName, column] of Object.entries(columns)) { | ||
| const columnObj = column; | ||
| const normalizedColumn = { | ||
| ...columnObj, | ||
| nullable: columnObj["nullable"] ?? false | ||
| }; | ||
| normalizedColumns[columnName] = normalizedColumn; | ||
| } | ||
| normalizedTables[tableName] = { | ||
| ...tableObj, | ||
| columns: normalizedColumns, | ||
| uniques: tableObj["uniques"] ?? [], | ||
| indexes: tableObj["indexes"] ?? [], | ||
| foreignKeys: tableObj["foreignKeys"] ?? [] | ||
| }; | ||
| } else { | ||
| normalizedTables[tableName] = tableObj; | ||
| } | ||
| } | ||
| normalizedStorage = { | ||
| ...storage, | ||
| tables: normalizedTables | ||
| }; | ||
| } | ||
| } | ||
| let normalizedModels = contractObj["models"]; | ||
| if (normalizedModels && typeof normalizedModels === "object" && normalizedModels !== null) { | ||
| const models = normalizedModels; | ||
| const normalizedModelsObj = {}; | ||
| for (const [modelName, model] of Object.entries(models)) { | ||
| const modelObj = model; | ||
| normalizedModelsObj[modelName] = { | ||
| ...modelObj, | ||
| relations: modelObj["relations"] ?? {} | ||
| }; | ||
| } | ||
| normalizedModels = normalizedModelsObj; | ||
| } | ||
| return { | ||
| ...contractObj, | ||
| models: normalizedModels, | ||
| relations: contractObj["relations"] ?? {}, | ||
| storage: normalizedStorage, | ||
| extensions: contractObj["extensions"] ?? {}, | ||
| capabilities: contractObj["capabilities"] ?? {}, | ||
| meta: contractObj["meta"] ?? {}, | ||
| sources: contractObj["sources"] ?? {} | ||
| }; | ||
| } | ||
| function validateContract(value) { | ||
| const normalized = normalizeContract(value); | ||
| const structurallyValid = validateContractStructure(normalized); | ||
| const contractForValidation = structurallyValid; | ||
| validateContractLogic(contractForValidation); | ||
| const existingMappings = contractForValidation.mappings; | ||
| const mappings = computeMappings( | ||
| contractForValidation.models, | ||
| contractForValidation.storage, | ||
| existingMappings | ||
| ); | ||
| const contractWithMappings = { | ||
| ...structurallyValid, | ||
| models: contractForValidation.models, | ||
| relations: contractForValidation.relations, | ||
| storage: contractForValidation.storage, | ||
| mappings | ||
| }; | ||
| return contractWithMappings; | ||
| } | ||
| export { | ||
| computeMappings, | ||
| validateContract | ||
| }; | ||
| //# sourceMappingURL=chunk-TALJTLJN.js.map |
| {"version":3,"sources":["../../src/contract.ts"],"sourcesContent":["import type {\n ForeignKey,\n ForeignKeyReferences,\n Index,\n ModelDefinition,\n ModelField,\n ModelStorage,\n PrimaryKey,\n SqlContract,\n SqlMappings,\n SqlStorage,\n StorageColumn,\n StorageTable,\n UniqueConstraint,\n} from '@prisma-next/sql-contract/types';\nimport { type } from 'arktype';\nimport type { O } from 'ts-toolbelt';\n\n/**\n * Structural validation schema for SqlContract using Arktype.\n * This validates the shape and types of the contract structure.\n */\nconst StorageColumnSchema = type.declare<StorageColumn>().type({\n nativeType: 'string',\n codecId: 'string',\n nullable: 'boolean',\n});\n\nconst PrimaryKeySchema = type.declare<PrimaryKey>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraint>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst IndexSchema = type.declare<Index>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst ForeignKeyReferencesSchema = type.declare<ForeignKeyReferences>().type({\n table: 'string',\n columns: type.string.array().readonly(),\n});\n\nconst ForeignKeySchema = type.declare<ForeignKey>().type({\n columns: type.string.array().readonly(),\n references: ForeignKeyReferencesSchema,\n 'name?': 'string',\n});\n\nconst StorageTableSchema = type.declare<StorageTable>().type({\n columns: type({ '[string]': StorageColumnSchema }),\n 'primaryKey?': PrimaryKeySchema,\n uniques: UniqueConstraintSchema.array().readonly(),\n indexes: IndexSchema.array().readonly(),\n foreignKeys: ForeignKeySchema.array().readonly(),\n});\n\nconst StorageSchema = type.declare<SqlStorage>().type({\n tables: type({ '[string]': StorageTableSchema }),\n});\n\nconst ModelFieldSchema = type.declare<ModelField>().type({\n column: 'string',\n});\n\nconst ModelStorageSchema = type.declare<ModelStorage>().type({\n table: 'string',\n});\n\nconst ModelSchema = type.declare<ModelDefinition>().type({\n storage: ModelStorageSchema,\n fields: type({ '[string]': ModelFieldSchema }),\n relations: type({ '[string]': 'unknown' }),\n});\n\n/**\n * Complete SqlContract schema for structural validation.\n * This validates the entire contract structure at once.\n */\nconst SqlContractSchema = type({\n 'schemaVersion?': \"'1'\",\n target: 'string',\n targetFamily: \"'sql'\",\n coreHash: 'string',\n 'profileHash?': 'string',\n 'capabilities?': 'Record<string, Record<string, boolean>>',\n 'extensions?': 'Record<string, unknown>',\n 'meta?': 'Record<string, unknown>',\n 'sources?': 'Record<string, unknown>',\n models: type({ '[string]': ModelSchema }),\n storage: StorageSchema,\n});\n\n/**\n * Validates the structural shape of a SqlContract using Arktype.\n *\n * **Responsibility: Validation Only**\n * This function validates that the contract has the correct structure and types.\n * It does NOT normalize the contract - normalization must happen in the contract builder.\n *\n * The contract passed to this function must already be normalized (all required fields present).\n * If normalization is needed, it should be done by the contract builder before calling this function.\n *\n * This ensures all required fields are present and have the correct types.\n *\n * @param value - The contract value to validate (typically from a JSON import)\n * @returns The validated contract if structure is valid\n * @throws Error if the contract structure is invalid\n */\nfunction validateContractStructure<T extends SqlContract<SqlStorage>>(\n value: unknown,\n): O.Overwrite<T, { targetFamily: 'sql' }> {\n // Check targetFamily first to provide a clear error message for unsupported target families\n const rawValue = value as { targetFamily?: string };\n if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {\n /* c8 ignore next */\n throw new Error(`Unsupported target family: ${rawValue.targetFamily}`);\n }\n\n const contractResult = SqlContractSchema(value);\n\n if (contractResult instanceof type.errors) {\n const messages = contractResult.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Contract structural validation failed: ${messages}`);\n }\n\n // After validation, contractResult matches the schema and preserves the input structure\n // TypeScript needs an assertion here due to exactOptionalPropertyTypes differences\n // between Arktype's inferred type and the generic T, but runtime-wise they're compatible\n return contractResult as O.Overwrite<T, { targetFamily: 'sql' }>;\n}\n\n/**\n * Computes mapping dictionaries from models and storage structures.\n * Assumes valid input - validation happens separately in validateContractLogic().\n *\n * @param models - Models object from contract\n * @param storage - Storage object from contract\n * @param existingMappings - Existing mappings from contract input (optional)\n * @returns Computed mappings dictionary\n */\nexport function computeMappings(\n models: Record<string, ModelDefinition>,\n _storage: SqlStorage,\n existingMappings?: Partial<SqlMappings>,\n): SqlMappings {\n const modelToTable: Record<string, string> = {};\n const tableToModel: Record<string, string> = {};\n const fieldToColumn: Record<string, Record<string, string>> = {};\n const columnToField: Record<string, Record<string, string>> = {};\n\n for (const [modelName, model] of Object.entries(models)) {\n const tableName = model.storage.table;\n modelToTable[modelName] = tableName;\n tableToModel[tableName] = modelName;\n\n const modelFieldToColumn: Record<string, string> = {};\n for (const [fieldName, field] of Object.entries(model.fields)) {\n const columnName = field.column;\n modelFieldToColumn[fieldName] = columnName;\n\n if (!columnToField[tableName]) {\n columnToField[tableName] = {};\n }\n columnToField[tableName][columnName] = fieldName;\n }\n fieldToColumn[modelName] = modelFieldToColumn;\n }\n\n // Preserve existing mappings if provided, otherwise use computed ones\n return {\n modelToTable: existingMappings?.modelToTable ?? modelToTable,\n tableToModel: existingMappings?.tableToModel ?? tableToModel,\n fieldToColumn: existingMappings?.fieldToColumn ?? fieldToColumn,\n columnToField: existingMappings?.columnToField ?? columnToField,\n codecTypes: existingMappings?.codecTypes ?? {},\n operationTypes: existingMappings?.operationTypes ?? {},\n };\n}\n\n/**\n * Validates logical consistency of a **structurally validated** SqlContract.\n * This checks that references (e.g., foreign keys, primary keys, uniques) point to storage objects that already exist.\n * Structural validation is expected to have already completed before this helper runs.\n *\n * @param structurallyValidatedContract - The contract whose structure has already been validated\n * @throws Error if logical validation fails\n */\nfunction validateContractLogic(structurallyValidatedContract: SqlContract<SqlStorage>): void {\n const { storage, models } = structurallyValidatedContract;\n const tableNames = new Set(Object.keys(storage.tables));\n\n // Validate models\n for (const [modelName, modelUnknown] of Object.entries(models)) {\n const model = modelUnknown as ModelDefinition;\n // Validate model has storage.table\n if (!model.storage?.table) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" is missing storage.table`);\n }\n\n const tableName = model.storage.table;\n\n // Validate model's table exists in storage\n if (!tableNames.has(tableName)) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" references non-existent table \"${tableName}\"`);\n }\n\n const table = storage.tables[tableName];\n if (!table) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" references non-existent table \"${tableName}\"`);\n }\n\n // Validate model's table has a primary key\n if (!table.primaryKey) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" table \"${tableName}\" is missing a primary key`);\n }\n\n const columnNames = new Set(Object.keys(table.columns));\n\n // Validate model fields\n if (!model.fields) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" is missing fields`);\n }\n\n for (const [fieldName, fieldUnknown] of Object.entries(model.fields)) {\n const field = fieldUnknown as { column: string };\n // Validate field has column property\n if (!field.column) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" field \"${fieldName}\" is missing column property`);\n }\n\n // Validate field's column exists in the model's backing table\n if (!columnNames.has(field.column)) {\n /* c8 ignore next */\n throw new Error(\n `Model \"${modelName}\" field \"${fieldName}\" references non-existent column \"${field.column}\" in table \"${tableName}\"`,\n );\n }\n }\n\n // Validate model relations have corresponding foreign keys\n if (model.relations) {\n for (const [relationName, relation] of Object.entries(model.relations)) {\n // For now, we'll do basic validation. Full FK validation can be added later\n // This would require checking that the relation's on.parentCols/childCols match FKs\n if (\n typeof relation === 'object' &&\n relation !== null &&\n 'on' in relation &&\n 'to' in relation\n ) {\n const on = relation.on as { parentCols?: string[]; childCols?: string[] };\n const cardinality = (relation as { cardinality?: string }).cardinality;\n if (on.parentCols && on.childCols) {\n // For 1:N relations, the foreign key is on the child table\n // For N:1 relations, the foreign key is on the parent table (this table)\n // For now, we'll skip validation for 1:N relations as the FK is on the child table\n // and we'll validate it when we process the child model\n if (cardinality === '1:N') {\n // Foreign key is on the child table, skip validation here\n // It will be validated when we process the child model\n continue;\n }\n\n // For N:1 relations, check that there's a foreign key matching this relation\n const hasMatchingFk = table.foreignKeys?.some((fk) => {\n return (\n fk.columns.length === on.childCols?.length &&\n fk.columns.every((col, i) => col === on.childCols?.[i]) &&\n fk.references.table &&\n fk.references.columns.length === on.parentCols?.length &&\n fk.references.columns.every((col, i) => col === on.parentCols?.[i])\n );\n });\n\n if (!hasMatchingFk) {\n /* c8 ignore next */\n throw new Error(\n `Model \"${modelName}\" relation \"${relationName}\" does not have a corresponding foreign key in table \"${tableName}\"`,\n );\n }\n }\n }\n }\n }\n }\n\n for (const [tableName, table] of Object.entries(storage.tables)) {\n const columnNames = new Set(Object.keys(table.columns));\n\n // Validate primaryKey references existing columns\n if (table.primaryKey) {\n for (const colName of table.primaryKey.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\n );\n }\n }\n }\n\n // Validate unique constraints reference existing columns\n for (const unique of table.uniques) {\n for (const colName of unique.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\n );\n }\n }\n }\n\n // Validate indexes reference existing columns\n for (const index of table.indexes) {\n for (const colName of index.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(`Table \"${tableName}\" index references non-existent column \"${colName}\"`);\n }\n }\n }\n\n // Validate foreignKeys reference existing tables and columns\n for (const fk of table.foreignKeys) {\n // Validate FK columns exist in the referencing table\n for (const colName of fk.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n );\n }\n }\n\n // Validate referenced table exists\n if (!tableNames.has(fk.references.table)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n );\n }\n\n // Validate referenced columns exist in the referenced table\n const referencedTable = storage.tables[fk.references.table];\n if (!referencedTable) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n );\n }\n const referencedColumnNames = new Set(Object.keys(referencedTable.columns));\n\n for (const colName of fk.references.columns) {\n if (!referencedColumnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\" in table \"${fk.references.table}\"`,\n );\n }\n }\n\n if (fk.columns.length !== fk.references.columns.length) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`,\n );\n }\n }\n }\n}\n\nexport function normalizeContract(contract: unknown): SqlContract<SqlStorage> {\n const contractObj = contract as Record<string, unknown>;\n\n // Only normalize if storage exists (validation will catch if it's missing)\n let normalizedStorage = contractObj['storage'];\n if (normalizedStorage && typeof normalizedStorage === 'object' && normalizedStorage !== null) {\n const storage = normalizedStorage as Record<string, unknown>;\n const tables = storage['tables'] as Record<string, unknown> | undefined;\n\n if (tables) {\n // Normalize storage tables\n const normalizedTables: Record<string, unknown> = {};\n for (const [tableName, table] of Object.entries(tables)) {\n const tableObj = table as Record<string, unknown>;\n const columns = tableObj['columns'] as Record<string, unknown> | undefined;\n\n if (columns) {\n // Normalize columns: add nullable: false if missing\n const normalizedColumns: Record<string, unknown> = {};\n for (const [columnName, column] of Object.entries(columns)) {\n const columnObj = column as Record<string, unknown>;\n const normalizedColumn: Record<string, unknown> = {\n ...columnObj,\n nullable: columnObj['nullable'] ?? false,\n };\n\n normalizedColumns[columnName] = normalizedColumn;\n }\n\n // Normalize table arrays: add empty arrays if missing\n normalizedTables[tableName] = {\n ...tableObj,\n columns: normalizedColumns,\n uniques: tableObj['uniques'] ?? [],\n indexes: tableObj['indexes'] ?? [],\n foreignKeys: tableObj['foreignKeys'] ?? [],\n };\n } else {\n normalizedTables[tableName] = tableObj;\n }\n }\n\n normalizedStorage = {\n ...storage,\n tables: normalizedTables,\n };\n }\n }\n\n // Only normalize if models exists (validation will catch if it's missing)\n let normalizedModels = contractObj['models'];\n if (normalizedModels && typeof normalizedModels === 'object' && normalizedModels !== null) {\n const models = normalizedModels as Record<string, unknown>;\n const normalizedModelsObj: Record<string, unknown> = {};\n for (const [modelName, model] of Object.entries(models)) {\n const modelObj = model as Record<string, unknown>;\n normalizedModelsObj[modelName] = {\n ...modelObj,\n relations: modelObj['relations'] ?? {},\n };\n }\n normalizedModels = normalizedModelsObj;\n }\n\n // Normalize top-level fields: add empty objects if missing\n return {\n ...contractObj,\n models: normalizedModels,\n relations: contractObj['relations'] ?? {},\n storage: normalizedStorage,\n extensions: contractObj['extensions'] ?? {},\n capabilities: contractObj['capabilities'] ?? {},\n meta: contractObj['meta'] ?? {},\n sources: contractObj['sources'] ?? {},\n } as SqlContract<SqlStorage>;\n}\n\n/**\n * Validates that a JSON import conforms to the SqlContract structure\n * and returns a fully typed SqlContract.\n *\n * This function is specifically for validating JSON imports (e.g., from contract.json).\n * Contracts created via the builder API (defineContract) are already valid and should\n * not be passed to this function - use them directly without validation.\n *\n * Performs both structural validation (using Arktype) and logical validation\n * (ensuring all references are valid).\n *\n *\n * The type parameter `TContract` must be a fully-typed contract type (e.g., from `contract.d.ts`),\n * NOT a generic `SqlContract<SqlStorage>`.\n *\n * **Correct:**\n * ```typescript\n * import type { Contract } from './contract.d';\n * const contract = validateContract<Contract>(contractJson);\n * ```\n *\n * **Incorrect:**\n * ```typescript\n * import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';\n * const contract = validateContract<SqlContract<SqlStorage>>(contractJson);\n * // ❌ Types will be inferred as 'unknown' - this won't work!\n * ```\n *\n * The type parameter provides the specific table structure, column types, and model definitions.\n * This function validates the runtime structure matches the type, but does not infer types\n * from JSON (as JSON imports lose literal type information).\n *\n * @param value - The contract value to validate (must be from a JSON import, not a builder)\n * @returns A validated contract matching the TContract type\n * @throws Error if the contract structure or logic is invalid\n */\nexport function validateContract<TContract extends SqlContract<SqlStorage>>(\n value: unknown,\n): TContract {\n // Normalize contract first (add defaults for missing fields)\n const normalized = normalizeContract(value);\n\n const structurallyValid = validateContractStructure<SqlContract<SqlStorage>>(normalized);\n\n const contractForValidation = structurallyValid as SqlContract<SqlStorage>;\n\n // Validate contract logic (contracts must already have fully qualified type IDs)\n validateContractLogic(contractForValidation);\n\n // Extract existing mappings (optional - will be computed if missing)\n const existingMappings = (contractForValidation as { mappings?: Partial<SqlMappings> }).mappings;\n\n // Compute mappings from models and storage\n const mappings = computeMappings(\n contractForValidation.models as Record<string, ModelDefinition>,\n contractForValidation.storage,\n existingMappings,\n );\n\n // Add default values for optional metadata fields if missing\n const contractWithMappings = {\n ...structurallyValid,\n models: contractForValidation.models,\n relations: contractForValidation.relations,\n storage: contractForValidation.storage,\n mappings,\n };\n\n // Type assertion: The caller provides the strict type via TContract.\n // We validate the structure matches, but the precise types come from contract.d.ts\n return contractWithMappings as TContract;\n}\n"],"mappings":";AAeA,SAAS,YAAY;AAOrB,IAAM,sBAAsB,KAAK,QAAuB,EAAE,KAAK;AAAA,EAC7D,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,UAAU;AACZ,CAAC;AAED,IAAM,mBAAmB,KAAK,QAAoB,EAAE,KAAK;AAAA,EACvD,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,SAAS;AACX,CAAC;AAED,IAAM,yBAAyB,KAAK,QAA0B,EAAE,KAAK;AAAA,EACnE,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,SAAS;AACX,CAAC;AAED,IAAM,cAAc,KAAK,QAAe,EAAE,KAAK;AAAA,EAC7C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B,0BAAoB,SAAS,IAAI;AAAA,QAC/B,GAAG;AAAA,QACH,WAAW,SAAS,WAAW,KAAK,CAAC;AAAA,MACvC;AAAA,IACF;AACA,uBAAmB;AAAA,EACrB;AAGA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ;AAAA,IACR,WAAW,YAAY,WAAW,KAAK,CAAC;AAAA,IACxC,SAAS;AAAA,IACT,YAAY,YAAY,YAAY,KAAK,CAAC;AAAA,IAC1C,cAAc,YAAY,cAAc,KAAK,CAAC;AAAA,IAC9C,MAAM,YAAY,MAAM,KAAK,CAAC;AAAA,IAC9B,SAAS,YAAY,SAAS,KAAK,CAAC;AAAA,EACtC;AACF;AAsCO,SAAS,iBACd,OACW;AAEX,QAAM,aAAa,kBAAkB,KAAK;AAE1C,QAAM,oBAAoB,0BAAmD,UAAU;AAEvF,QAAM,wBAAwB;AAG9B,wBAAsB,qBAAqB;AAG3C,QAAM,mBAAoB,sBAA8D;AAGxF,QAAM,WAAW;AAAA,IACf,sBAAsB;AAAA,IACtB,sBAAsB;AAAA,IACtB;AAAA,EACF;AAGA,QAAM,uBAAuB;AAAA,IAC3B,GAAG;AAAA,IACH,QAAQ,sBAAsB;AAAA,IAC9B,WAAW,sBAAsB;AAAA,IACjC,SAAS,sBAAsB;AAAA,IAC/B;AAAA,EACF;AAIA,SAAO;AACT;","names":[]} |
@@ -48,5 +48,2 @@ import { ColumnBuilderState, TableBuilderState, ModelBuilderState, RelationDefinition, ContractBuilder, BuildStorageColumn, ExtractColumns, ExtractPrimaryKey, BuildModels, BuildRelations, TableBuilder, ModelBuilder } from '@prisma-next/contract-authoring'; | ||
| /** | ||
| * Builds and normalizes the contract. | ||
| * | ||
| * **Responsibility: Normalization** | ||
| * This method is responsible for normalizing the contract IR by setting default values | ||
@@ -59,2 +56,3 @@ * for all required fields: | ||
| * - `relations`: defaults to `{}` (empty object) for both model-level and contract-level | ||
| * - `nativeType`: required field set from column type descriptor when columns are defined | ||
| * | ||
@@ -64,2 +62,5 @@ * The contract builder is the **only** place where normalization should occur. | ||
| * | ||
| * **Required**: Use column type descriptors (e.g., `int4Column`, `textColumn`) when defining columns. | ||
| * This ensures `nativeType` is set correctly at build time. | ||
| * | ||
| * @returns A normalized SqlContract with all required fields present | ||
@@ -66,0 +67,0 @@ */ |
| import { | ||
| computeMappings | ||
| } from "./chunk-BJOMVCU6.js"; | ||
| } from "./chunk-TALJTLJN.js"; | ||
@@ -13,5 +13,2 @@ // src/contract-builder.ts | ||
| /** | ||
| * Builds and normalizes the contract. | ||
| * | ||
| * **Responsibility: Normalization** | ||
| * This method is responsible for normalizing the contract IR by setting default values | ||
@@ -24,2 +21,3 @@ * for all required fields: | ||
| * - `relations`: defaults to `{}` (empty object) for both model-level and contract-level | ||
| * - `nativeType`: required field set from column type descriptor when columns are defined | ||
| * | ||
@@ -29,2 +27,5 @@ * The contract builder is the **only** place where normalization should occur. | ||
| * | ||
| * **Required**: Use column type descriptors (e.g., `int4Column`, `textColumn`) when defining columns. | ||
| * This ensures `nativeType` is set correctly at build time. | ||
| * | ||
| * @returns A normalized SqlContract with all required fields present | ||
@@ -45,4 +46,7 @@ */ | ||
| if (!columnState) continue; | ||
| const codecId = columnState.type; | ||
| const nativeType = columnState.nativeType; | ||
| columns[columnName] = { | ||
| type: columnState.type, | ||
| nativeType, | ||
| codecId, | ||
| nullable: columnState.nullable ?? false | ||
@@ -49,0 +53,0 @@ }; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../src/contract-builder.ts"],"sourcesContent":["import type {\n ColumnBuilderState,\n ModelBuilderState,\n RelationDefinition,\n TableBuilderState,\n} from '@prisma-next/contract-authoring';\nimport {\n type BuildModels,\n type BuildRelations,\n type BuildStorageColumn,\n ContractBuilder,\n type ExtractColumns,\n type ExtractPrimaryKey,\n ModelBuilder,\n type Mutable,\n TableBuilder,\n} from '@prisma-next/contract-authoring';\nimport type {\n ModelDefinition,\n ModelField,\n SqlContract,\n SqlMappings,\n SqlStorage,\n} from '@prisma-next/sql-contract/types';\nimport { computeMappings } from './contract';\n\n/**\n * Type-level mappings structure for contracts built via `defineContract()`.\n *\n * Compile-time type helper (not a runtime object) that ensures mappings match what the builder\n * produces. `codecTypes` uses the generic `CodecTypes` parameter; `operationTypes` is always\n * empty since operations are added via extensions at runtime.\n *\n * **Difference from RuntimeContext**: This is a compile-time type for contract construction.\n * `RuntimeContext` is a runtime object with populated registries for query execution.\n *\n * @template C - The `CodecTypes` generic parameter passed to `defineContract<CodecTypes>()`\n */\ntype ContractBuilderMappings<C extends Record<string, { output: unknown }>> = Omit<\n SqlMappings,\n 'codecTypes' | 'operationTypes'\n> & {\n readonly codecTypes: C;\n readonly operationTypes: Record<string, never>;\n};\n\ntype BuildStorageTable<\n _TableName extends string,\n Columns extends Record<string, ColumnBuilderState<string, boolean, string>>,\n PK extends readonly string[] | undefined,\n> = {\n readonly columns: {\n readonly [K in keyof Columns]: Columns[K] extends ColumnBuilderState<\n string,\n infer Null,\n infer TType\n >\n ? BuildStorageColumn<Null & boolean, TType>\n : never;\n };\n readonly uniques: ReadonlyArray<never>;\n readonly indexes: ReadonlyArray<never>;\n readonly foreignKeys: ReadonlyArray<never>;\n} & (PK extends readonly string[]\n ? { readonly primaryKey: { readonly columns: PK } }\n : Record<string, never>);\n\ntype BuildStorage<\n Tables extends Record<\n string,\n TableBuilderState<\n string,\n Record<string, ColumnBuilderState<string, boolean, string>>,\n readonly string[] | undefined\n >\n >,\n> = {\n readonly tables: {\n readonly [K in keyof Tables]: BuildStorageTable<\n K & string,\n ExtractColumns<Tables[K]>,\n ExtractPrimaryKey<Tables[K]>\n >;\n };\n};\n\ntype BuildStorageTables<\n Tables extends Record<\n string,\n TableBuilderState<\n string,\n Record<string, ColumnBuilderState<string, boolean, string>>,\n readonly string[] | undefined\n >\n >,\n> = {\n readonly [K in keyof Tables]: BuildStorageTable<\n K & string,\n ExtractColumns<Tables[K]>,\n ExtractPrimaryKey<Tables[K]>\n >;\n};\n\nexport interface ColumnBuilder<Name extends string, Nullable extends boolean, Type extends string> {\n nullable<Value extends boolean>(value?: Value): ColumnBuilder<Name, Value, Type>;\n type<Id extends string>(id: Id): ColumnBuilder<Name, Nullable, Id>;\n build(): ColumnBuilderState<Name, Nullable, Type>;\n}\n\nclass SqlContractBuilder<\n CodecTypes extends Record<string, { output: unknown }> = Record<string, never>,\n Target extends string | undefined = undefined,\n Tables extends Record<\n string,\n TableBuilderState<\n string,\n Record<string, ColumnBuilderState<string, boolean, string>>,\n readonly string[] | undefined\n >\n > = Record<never, never>,\n Models extends Record<\n string,\n ModelBuilderState<string, string, Record<string, string>, Record<string, RelationDefinition>>\n > = Record<never, never>,\n CoreHash extends string | undefined = undefined,\n Extensions extends Record<string, unknown> | undefined = undefined,\n Capabilities extends Record<string, Record<string, boolean>> | undefined = undefined,\n> extends ContractBuilder<Target, Tables, Models, CoreHash, Extensions, Capabilities> {\n /**\n * Builds and normalizes the contract.\n *\n * **Responsibility: Normalization**\n * This method is responsible for normalizing the contract IR by setting default values\n * for all required fields:\n * - `nullable`: defaults to `false` if not provided\n * - `uniques`: defaults to `[]` (empty array)\n * - `indexes`: defaults to `[]` (empty array)\n * - `foreignKeys`: defaults to `[]` (empty array)\n * - `relations`: defaults to `{}` (empty object) for both model-level and contract-level\n *\n * The contract builder is the **only** place where normalization should occur.\n * Validators, parsers, and emitters should assume the contract is already normalized.\n *\n * @returns A normalized SqlContract with all required fields present\n */\n build(): Target extends string\n ? SqlContract<\n BuildStorage<Tables>,\n BuildModels<Models>,\n BuildRelations<Models>,\n ContractBuilderMappings<CodecTypes>\n > & {\n readonly schemaVersion: '1';\n readonly target: Target;\n readonly targetFamily: 'sql';\n readonly coreHash: CoreHash extends string ? CoreHash : string;\n } & (Extensions extends Record<string, unknown>\n ? { readonly extensions: Extensions }\n : Record<string, never>) &\n (Capabilities extends Record<string, Record<string, boolean>>\n ? { readonly capabilities: Capabilities }\n : Record<string, never>)\n : never {\n // Type helper to ensure literal types are preserved in return type\n type BuiltContract = Target extends string\n ? SqlContract<\n BuildStorage<Tables>,\n BuildModels<Models>,\n BuildRelations<Models>,\n ContractBuilderMappings<CodecTypes>\n > & {\n readonly schemaVersion: '1';\n readonly target: Target;\n readonly targetFamily: 'sql';\n readonly coreHash: CoreHash extends string ? CoreHash : string;\n } & (Extensions extends Record<string, unknown>\n ? { readonly extensions: Extensions }\n : Record<string, never>) &\n (Capabilities extends Record<string, Record<string, boolean>>\n ? { readonly capabilities: Capabilities }\n : Record<string, never>)\n : never;\n if (!this.state.target) {\n throw new Error('target is required. Call .target() before .build()');\n }\n\n const target = this.state.target as Target & string;\n\n const storageTables = {} as Partial<Mutable<BuildStorageTables<Tables>>>;\n\n for (const tableName of Object.keys(this.state.tables) as Array<keyof Tables & string>) {\n const tableState = this.state.tables[tableName];\n if (!tableState) continue;\n\n type TableKey = typeof tableName;\n type ColumnDefs = ExtractColumns<Tables[TableKey]>;\n type PrimaryKey = ExtractPrimaryKey<Tables[TableKey]>;\n\n const columns = {} as Partial<{\n [K in keyof ColumnDefs]: BuildStorageColumn<\n ColumnDefs[K]['nullable'] & boolean,\n ColumnDefs[K]['type']\n >;\n }>;\n\n for (const columnName in tableState.columns) {\n const columnState = tableState.columns[columnName];\n if (!columnState) continue;\n columns[columnName as keyof ColumnDefs] = {\n type: columnState.type,\n nullable: (columnState.nullable ?? false) as ColumnDefs[keyof ColumnDefs]['nullable'] &\n boolean,\n } as BuildStorageColumn<\n ColumnDefs[keyof ColumnDefs]['nullable'] & boolean,\n ColumnDefs[keyof ColumnDefs]['type']\n >;\n }\n\n const table = {\n columns: columns as {\n [K in keyof ColumnDefs]: BuildStorageColumn<\n ColumnDefs[K]['nullable'] & boolean,\n ColumnDefs[K]['type']\n >;\n },\n uniques: [],\n indexes: [],\n foreignKeys: [],\n ...(tableState.primaryKey\n ? {\n primaryKey: {\n columns: tableState.primaryKey,\n },\n }\n : {}),\n } as unknown as BuildStorageTable<TableKey & string, ColumnDefs, PrimaryKey>;\n\n (storageTables as Mutable<BuildStorageTables<Tables>>)[tableName] = table;\n }\n\n const storage = { tables: storageTables as BuildStorageTables<Tables> } as BuildStorage<Tables>;\n\n // Build models - construct as partial first, then assert full type\n const modelsPartial: Partial<BuildModels<Models>> = {};\n\n // Iterate over models - TypeScript will see keys as string, but type assertion preserves literals\n for (const modelName in this.state.models) {\n const modelState = this.state.models[modelName];\n if (!modelState) continue;\n\n const modelStateTyped = modelState as unknown as {\n name: string;\n table: string;\n fields: Record<string, string>;\n };\n\n // Build fields object\n const fields: Partial<Record<string, ModelField>> = {};\n\n // Iterate over fields\n for (const fieldName in modelStateTyped.fields) {\n const columnName = modelStateTyped.fields[fieldName];\n if (columnName) {\n fields[fieldName] = {\n column: columnName,\n };\n }\n }\n\n // Assign to models - type assertion preserves literal keys\n (modelsPartial as unknown as Record<string, ModelDefinition>)[modelName] = {\n storage: {\n table: modelStateTyped.table,\n },\n fields: fields as Record<string, ModelField>,\n relations: {},\n };\n }\n\n // Build relations object - organized by table name\n const relationsPartial: Partial<Record<string, Record<string, RelationDefinition>>> = {};\n\n // Iterate over models to collect relations\n for (const modelName in this.state.models) {\n const modelState = this.state.models[modelName];\n if (!modelState) continue;\n\n const modelStateTyped = modelState as unknown as {\n name: string;\n table: string;\n fields: Record<string, string>;\n relations: Record<string, RelationDefinition>;\n };\n\n const tableName = modelStateTyped.table;\n if (!tableName) continue;\n\n // Only initialize relations object for this table if it has relations\n if (modelStateTyped.relations && Object.keys(modelStateTyped.relations).length > 0) {\n if (!relationsPartial[tableName]) {\n relationsPartial[tableName] = {};\n }\n\n // Add relations from this model to the table's relations\n const tableRelations = relationsPartial[tableName];\n if (tableRelations) {\n for (const relationName in modelStateTyped.relations) {\n const relation = modelStateTyped.relations[relationName];\n if (relation) {\n tableRelations[relationName] = relation;\n }\n }\n }\n }\n }\n\n const models = modelsPartial as unknown as BuildModels<Models>;\n\n const baseMappings = computeMappings(\n models as unknown as Record<string, ModelDefinition>,\n storage as SqlStorage,\n );\n\n const mappings = {\n ...baseMappings,\n codecTypes: {} as CodecTypes,\n operationTypes: {} as Record<string, never>,\n } as ContractBuilderMappings<CodecTypes>;\n\n // Construct contract with explicit type that matches the generic parameters\n // This ensures TypeScript infers literal types from the generics, not runtime values\n // Always include relations, even if empty (normalized to empty object)\n const contract = {\n schemaVersion: '1' as const,\n target,\n targetFamily: 'sql' as const,\n coreHash: this.state.coreHash || 'sha256:ts-builder-placeholder',\n models,\n relations: relationsPartial,\n storage,\n mappings,\n extensions: this.state.extensions || {},\n capabilities: this.state.capabilities || {},\n meta: {},\n sources: {},\n } as unknown as BuiltContract;\n\n return contract as unknown as ReturnType<\n SqlContractBuilder<\n CodecTypes,\n Target,\n Tables,\n Models,\n CoreHash,\n Extensions,\n Capabilities\n >['build']\n >;\n }\n\n override target<T extends string>(\n target: T,\n ): SqlContractBuilder<CodecTypes, T, Tables, Models, CoreHash, Extensions, Capabilities> {\n return new SqlContractBuilder<\n CodecTypes,\n T,\n Tables,\n Models,\n CoreHash,\n Extensions,\n Capabilities\n >({\n ...this.state,\n target,\n });\n }\n\n override extensions<E extends Record<string, unknown>>(\n extensions: E,\n ): SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, E, Capabilities> {\n return new SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, E, Capabilities>({\n ...this.state,\n extensions,\n });\n }\n\n override capabilities<C extends Record<string, Record<string, boolean>>>(\n capabilities: C,\n ): SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, Extensions, C> {\n return new SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, Extensions, C>({\n ...this.state,\n capabilities,\n });\n }\n\n override coreHash<H extends string>(\n hash: H,\n ): SqlContractBuilder<CodecTypes, Target, Tables, Models, H, Extensions, Capabilities> {\n return new SqlContractBuilder<CodecTypes, Target, Tables, Models, H, Extensions, Capabilities>({\n ...this.state,\n coreHash: hash,\n });\n }\n\n override table<\n TableName extends string,\n T extends TableBuilder<\n TableName,\n Record<string, ColumnBuilderState<string, boolean, string>>,\n readonly string[] | undefined\n >,\n >(\n name: TableName,\n callback: (t: TableBuilder<TableName>) => T | undefined,\n ): SqlContractBuilder<\n CodecTypes,\n Target,\n Tables & Record<TableName, ReturnType<T['build']>>,\n Models,\n CoreHash,\n Extensions,\n Capabilities\n > {\n const tableBuilder = new TableBuilder<TableName>(name);\n const result = callback(tableBuilder);\n const finalBuilder = result instanceof TableBuilder ? result : tableBuilder;\n const tableState = finalBuilder.build();\n\n return new SqlContractBuilder<\n CodecTypes,\n Target,\n Tables & Record<TableName, ReturnType<T['build']>>,\n Models,\n CoreHash,\n Extensions,\n Capabilities\n >({\n ...this.state,\n tables: { ...this.state.tables, [name]: tableState } as Tables &\n Record<TableName, ReturnType<T['build']>>,\n });\n }\n\n override model<\n ModelName extends string,\n TableName extends string,\n M extends ModelBuilder<\n ModelName,\n TableName,\n Record<string, string>,\n Record<string, RelationDefinition>\n >,\n >(\n name: ModelName,\n table: TableName,\n callback: (\n m: ModelBuilder<ModelName, TableName, Record<string, string>, Record<never, never>>,\n ) => M | undefined,\n ): SqlContractBuilder<\n CodecTypes,\n Target,\n Tables,\n Models & Record<ModelName, ReturnType<M['build']>>,\n CoreHash,\n Extensions,\n Capabilities\n > {\n const modelBuilder = new ModelBuilder<ModelName, TableName>(name, table);\n const result = callback(modelBuilder);\n const finalBuilder = result instanceof ModelBuilder ? result : modelBuilder;\n const modelState = finalBuilder.build();\n\n return new SqlContractBuilder<\n CodecTypes,\n Target,\n Tables,\n Models & Record<ModelName, ReturnType<M['build']>>,\n CoreHash,\n Extensions,\n Capabilities\n >({\n ...this.state,\n models: { ...this.state.models, [name]: modelState } as Models &\n Record<ModelName, ReturnType<M['build']>>,\n });\n }\n}\n\nexport function defineContract<\n CodecTypes extends Record<string, { output: unknown }> = Record<string, never>,\n>(): SqlContractBuilder<CodecTypes> {\n return new SqlContractBuilder<CodecTypes>();\n}\n"],"mappings":";;;;;AAMA;AAAA,EAIE;AAAA,EAGA;AAA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| ||
| {"version":3,"sources":["../../src/contract-builder.ts"],"sourcesContent":["import type {\n ColumnBuilderState,\n ModelBuilderState,\n RelationDefinition,\n TableBuilderState,\n} from '@prisma-next/contract-authoring';\nimport {\n type BuildModels,\n type BuildRelations,\n type BuildStorageColumn,\n ContractBuilder,\n type ExtractColumns,\n type ExtractPrimaryKey,\n ModelBuilder,\n type Mutable,\n TableBuilder,\n} from '@prisma-next/contract-authoring';\nimport type {\n ModelDefinition,\n ModelField,\n SqlContract,\n SqlMappings,\n SqlStorage,\n} from '@prisma-next/sql-contract/types';\nimport { computeMappings } from './contract';\n\n/**\n * Type-level mappings structure for contracts built via `defineContract()`.\n *\n * Compile-time type helper (not a runtime object) that ensures mappings match what the builder\n * produces. `codecTypes` uses the generic `CodecTypes` parameter; `operationTypes` is always\n * empty since operations are added via extensions at runtime.\n *\n * **Difference from RuntimeContext**: This is a compile-time type for contract construction.\n * `RuntimeContext` is a runtime object with populated registries for query execution.\n *\n * @template C - The `CodecTypes` generic parameter passed to `defineContract<CodecTypes>()`\n */\ntype ContractBuilderMappings<C extends Record<string, { output: unknown }>> = Omit<\n SqlMappings,\n 'codecTypes' | 'operationTypes'\n> & {\n readonly codecTypes: C;\n readonly operationTypes: Record<string, never>;\n};\n\ntype BuildStorageTable<\n _TableName extends string,\n Columns extends Record<string, ColumnBuilderState<string, boolean, string>>,\n PK extends readonly string[] | undefined,\n> = {\n readonly columns: {\n readonly [K in keyof Columns]: Columns[K] extends ColumnBuilderState<\n string,\n infer Null,\n infer TType\n >\n ? BuildStorageColumn<Null & boolean, TType>\n : never;\n };\n readonly uniques: ReadonlyArray<never>;\n readonly indexes: ReadonlyArray<never>;\n readonly foreignKeys: ReadonlyArray<never>;\n} & (PK extends readonly string[]\n ? { readonly primaryKey: { readonly columns: PK } }\n : Record<string, never>);\n\ntype BuildStorage<\n Tables extends Record<\n string,\n TableBuilderState<\n string,\n Record<string, ColumnBuilderState<string, boolean, string>>,\n readonly string[] | undefined\n >\n >,\n> = {\n readonly tables: {\n readonly [K in keyof Tables]: BuildStorageTable<\n K & string,\n ExtractColumns<Tables[K]>,\n ExtractPrimaryKey<Tables[K]>\n >;\n };\n};\n\ntype BuildStorageTables<\n Tables extends Record<\n string,\n TableBuilderState<\n string,\n Record<string, ColumnBuilderState<string, boolean, string>>,\n readonly string[] | undefined\n >\n >,\n> = {\n readonly [K in keyof Tables]: BuildStorageTable<\n K & string,\n ExtractColumns<Tables[K]>,\n ExtractPrimaryKey<Tables[K]>\n >;\n};\n\nexport interface ColumnBuilder<Name extends string, Nullable extends boolean, Type extends string> {\n nullable<Value extends boolean>(value?: Value): ColumnBuilder<Name, Value, Type>;\n type<Id extends string>(id: Id): ColumnBuilder<Name, Nullable, Id>;\n build(): ColumnBuilderState<Name, Nullable, Type>;\n}\n\nclass SqlContractBuilder<\n CodecTypes extends Record<string, { output: unknown }> = Record<string, never>,\n Target extends string | undefined = undefined,\n Tables extends Record<\n string,\n TableBuilderState<\n string,\n Record<string, ColumnBuilderState<string, boolean, string>>,\n readonly string[] | undefined\n >\n > = Record<never, never>,\n Models extends Record<\n string,\n ModelBuilderState<string, string, Record<string, string>, Record<string, RelationDefinition>>\n > = Record<never, never>,\n CoreHash extends string | undefined = undefined,\n Extensions extends Record<string, unknown> | undefined = undefined,\n Capabilities extends Record<string, Record<string, boolean>> | undefined = undefined,\n> extends ContractBuilder<Target, Tables, Models, CoreHash, Extensions, Capabilities> {\n /**\n * This method is responsible for normalizing the contract IR by setting default values\n * for all required fields:\n * - `nullable`: defaults to `false` if not provided\n * - `uniques`: defaults to `[]` (empty array)\n * - `indexes`: defaults to `[]` (empty array)\n * - `foreignKeys`: defaults to `[]` (empty array)\n * - `relations`: defaults to `{}` (empty object) for both model-level and contract-level\n * - `nativeType`: required field set from column type descriptor when columns are defined\n *\n * The contract builder is the **only** place where normalization should occur.\n * Validators, parsers, and emitters should assume the contract is already normalized.\n *\n * **Required**: Use column type descriptors (e.g., `int4Column`, `textColumn`) when defining columns.\n * This ensures `nativeType` is set correctly at build time.\n *\n * @returns A normalized SqlContract with all required fields present\n */\n build(): Target extends string\n ? SqlContract<\n BuildStorage<Tables>,\n BuildModels<Models>,\n BuildRelations<Models>,\n ContractBuilderMappings<CodecTypes>\n > & {\n readonly schemaVersion: '1';\n readonly target: Target;\n readonly targetFamily: 'sql';\n readonly coreHash: CoreHash extends string ? CoreHash : string;\n } & (Extensions extends Record<string, unknown>\n ? { readonly extensions: Extensions }\n : Record<string, never>) &\n (Capabilities extends Record<string, Record<string, boolean>>\n ? { readonly capabilities: Capabilities }\n : Record<string, never>)\n : never {\n // Type helper to ensure literal types are preserved in return type\n type BuiltContract = Target extends string\n ? SqlContract<\n BuildStorage<Tables>,\n BuildModels<Models>,\n BuildRelations<Models>,\n ContractBuilderMappings<CodecTypes>\n > & {\n readonly schemaVersion: '1';\n readonly target: Target;\n readonly targetFamily: 'sql';\n readonly coreHash: CoreHash extends string ? CoreHash : string;\n } & (Extensions extends Record<string, unknown>\n ? { readonly extensions: Extensions }\n : Record<string, never>) &\n (Capabilities extends Record<string, Record<string, boolean>>\n ? { readonly capabilities: Capabilities }\n : Record<string, never>)\n : never;\n if (!this.state.target) {\n throw new Error('target is required. Call .target() before .build()');\n }\n\n const target = this.state.target as Target & string;\n\n const storageTables = {} as Partial<Mutable<BuildStorageTables<Tables>>>;\n\n for (const tableName of Object.keys(this.state.tables) as Array<keyof Tables & string>) {\n const tableState = this.state.tables[tableName];\n if (!tableState) continue;\n\n type TableKey = typeof tableName;\n type ColumnDefs = ExtractColumns<Tables[TableKey]>;\n type PrimaryKey = ExtractPrimaryKey<Tables[TableKey]>;\n\n const columns = {} as Partial<{\n [K in keyof ColumnDefs]: BuildStorageColumn<\n ColumnDefs[K]['nullable'] & boolean,\n ColumnDefs[K]['type']\n >;\n }>;\n\n for (const columnName in tableState.columns) {\n const columnState = tableState.columns[columnName];\n if (!columnState) continue;\n const codecId = columnState.type;\n const nativeType = columnState.nativeType;\n\n columns[columnName as keyof ColumnDefs] = {\n nativeType,\n codecId,\n nullable: (columnState.nullable ?? false) as ColumnDefs[keyof ColumnDefs]['nullable'] &\n boolean,\n } as BuildStorageColumn<\n ColumnDefs[keyof ColumnDefs]['nullable'] & boolean,\n ColumnDefs[keyof ColumnDefs]['type']\n >;\n }\n\n const table = {\n columns: columns as {\n [K in keyof ColumnDefs]: BuildStorageColumn<\n ColumnDefs[K]['nullable'] & boolean,\n ColumnDefs[K]['type']\n >;\n },\n uniques: [],\n indexes: [],\n foreignKeys: [],\n ...(tableState.primaryKey\n ? {\n primaryKey: {\n columns: tableState.primaryKey,\n },\n }\n : {}),\n } as unknown as BuildStorageTable<TableKey & string, ColumnDefs, PrimaryKey>;\n\n (storageTables as Mutable<BuildStorageTables<Tables>>)[tableName] = table;\n }\n\n const storage = { tables: storageTables as BuildStorageTables<Tables> } as BuildStorage<Tables>;\n\n // Build models - construct as partial first, then assert full type\n const modelsPartial: Partial<BuildModels<Models>> = {};\n\n // Iterate over models - TypeScript will see keys as string, but type assertion preserves literals\n for (const modelName in this.state.models) {\n const modelState = this.state.models[modelName];\n if (!modelState) continue;\n\n const modelStateTyped = modelState as unknown as {\n name: string;\n table: string;\n fields: Record<string, string>;\n };\n\n // Build fields object\n const fields: Partial<Record<string, ModelField>> = {};\n\n // Iterate over fields\n for (const fieldName in modelStateTyped.fields) {\n const columnName = modelStateTyped.fields[fieldName];\n if (columnName) {\n fields[fieldName] = {\n column: columnName,\n };\n }\n }\n\n // Assign to models - type assertion preserves literal keys\n (modelsPartial as unknown as Record<string, ModelDefinition>)[modelName] = {\n storage: {\n table: modelStateTyped.table,\n },\n fields: fields as Record<string, ModelField>,\n relations: {},\n };\n }\n\n // Build relations object - organized by table name\n const relationsPartial: Partial<Record<string, Record<string, RelationDefinition>>> = {};\n\n // Iterate over models to collect relations\n for (const modelName in this.state.models) {\n const modelState = this.state.models[modelName];\n if (!modelState) continue;\n\n const modelStateTyped = modelState as unknown as {\n name: string;\n table: string;\n fields: Record<string, string>;\n relations: Record<string, RelationDefinition>;\n };\n\n const tableName = modelStateTyped.table;\n if (!tableName) continue;\n\n // Only initialize relations object for this table if it has relations\n if (modelStateTyped.relations && Object.keys(modelStateTyped.relations).length > 0) {\n if (!relationsPartial[tableName]) {\n relationsPartial[tableName] = {};\n }\n\n // Add relations from this model to the table's relations\n const tableRelations = relationsPartial[tableName];\n if (tableRelations) {\n for (const relationName in modelStateTyped.relations) {\n const relation = modelStateTyped.relations[relationName];\n if (relation) {\n tableRelations[relationName] = relation;\n }\n }\n }\n }\n }\n\n const models = modelsPartial as unknown as BuildModels<Models>;\n\n const baseMappings = computeMappings(\n models as unknown as Record<string, ModelDefinition>,\n storage as SqlStorage,\n );\n\n const mappings = {\n ...baseMappings,\n codecTypes: {} as CodecTypes,\n operationTypes: {} as Record<string, never>,\n } as ContractBuilderMappings<CodecTypes>;\n\n // Construct contract with explicit type that matches the generic parameters\n // This ensures TypeScript infers literal types from the generics, not runtime values\n // Always include relations, even if empty (normalized to empty object)\n const contract = {\n schemaVersion: '1' as const,\n target,\n targetFamily: 'sql' as const,\n coreHash: this.state.coreHash || 'sha256:ts-builder-placeholder',\n models,\n relations: relationsPartial,\n storage,\n mappings,\n extensions: this.state.extensions || {},\n capabilities: this.state.capabilities || {},\n meta: {},\n sources: {},\n } as unknown as BuiltContract;\n\n return contract as unknown as ReturnType<\n SqlContractBuilder<\n CodecTypes,\n Target,\n Tables,\n Models,\n CoreHash,\n Extensions,\n Capabilities\n >['build']\n >;\n }\n\n override target<T extends string>(\n target: T,\n ): SqlContractBuilder<CodecTypes, T, Tables, Models, CoreHash, Extensions, Capabilities> {\n return new SqlContractBuilder<\n CodecTypes,\n T,\n Tables,\n Models,\n CoreHash,\n Extensions,\n Capabilities\n >({\n ...this.state,\n target,\n });\n }\n\n override extensions<E extends Record<string, unknown>>(\n extensions: E,\n ): SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, E, Capabilities> {\n return new SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, E, Capabilities>({\n ...this.state,\n extensions,\n });\n }\n\n override capabilities<C extends Record<string, Record<string, boolean>>>(\n capabilities: C,\n ): SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, Extensions, C> {\n return new SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, Extensions, C>({\n ...this.state,\n capabilities,\n });\n }\n\n override coreHash<H extends string>(\n hash: H,\n ): SqlContractBuilder<CodecTypes, Target, Tables, Models, H, Extensions, Capabilities> {\n return new SqlContractBuilder<CodecTypes, Target, Tables, Models, H, Extensions, Capabilities>({\n ...this.state,\n coreHash: hash,\n });\n }\n\n override table<\n TableName extends string,\n T extends TableBuilder<\n TableName,\n Record<string, ColumnBuilderState<string, boolean, string>>,\n readonly string[] | undefined\n >,\n >(\n name: TableName,\n callback: (t: TableBuilder<TableName>) => T | undefined,\n ): SqlContractBuilder<\n CodecTypes,\n Target,\n Tables & Record<TableName, ReturnType<T['build']>>,\n Models,\n CoreHash,\n Extensions,\n Capabilities\n > {\n const tableBuilder = new TableBuilder<TableName>(name);\n const result = callback(tableBuilder);\n const finalBuilder = result instanceof TableBuilder ? result : tableBuilder;\n const tableState = finalBuilder.build();\n\n return new SqlContractBuilder<\n CodecTypes,\n Target,\n Tables & Record<TableName, ReturnType<T['build']>>,\n Models,\n CoreHash,\n Extensions,\n Capabilities\n >({\n ...this.state,\n tables: { ...this.state.tables, [name]: tableState } as Tables &\n Record<TableName, ReturnType<T['build']>>,\n });\n }\n\n override model<\n ModelName extends string,\n TableName extends string,\n M extends ModelBuilder<\n ModelName,\n TableName,\n Record<string, string>,\n Record<string, RelationDefinition>\n >,\n >(\n name: ModelName,\n table: TableName,\n callback: (\n m: ModelBuilder<ModelName, TableName, Record<string, string>, Record<never, never>>,\n ) => M | undefined,\n ): SqlContractBuilder<\n CodecTypes,\n Target,\n Tables,\n Models & Record<ModelName, ReturnType<M['build']>>,\n CoreHash,\n Extensions,\n Capabilities\n > {\n const modelBuilder = new ModelBuilder<ModelName, TableName>(name, table);\n const result = callback(modelBuilder);\n const finalBuilder = result instanceof ModelBuilder ? result : modelBuilder;\n const modelState = finalBuilder.build();\n\n return new SqlContractBuilder<\n CodecTypes,\n Target,\n Tables,\n Models & Record<ModelName, ReturnType<M['build']>>,\n CoreHash,\n Extensions,\n Capabilities\n >({\n ...this.state,\n models: { ...this.state.models, [name]: modelState } as Models &\n Record<ModelName, ReturnType<M['build']>>,\n });\n }\n}\n\nexport function defineContract<\n CodecTypes extends Record<string, { output: unknown }> = Record<string, never>,\n>(): SqlContractBuilder<CodecTypes> {\n return new SqlContractBuilder<CodecTypes>();\n}\n"],"mappings":";;;;;AAMA;AAAA,EAIE;AAAA,EAGA;AAAA,EAEA;AAAA,OACK;AA6FP,IAAM,qBAAN,MAAM,4BAkBI,gBAA4E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBpF,QAiBU;AAoBR,QAAI,CAAC,KAAK,MAAM,QAAQ;AACtB,YAAM,IAAI,MAAM,oDAAoD;AAAA,IACtE;AAEA,UAAM,SAAS,KAAK,MAAM;AAE1B,UAAM,gBAAgB,CAAC;AAEvB,eAAW,aAAa,OAAO,KAAK,KAAK,MAAM,MAAM,GAAmC;AACtF,YAAM,aAAa,KAAK,MAAM,OAAO,SAAS;AAC9C,UAAI,CAAC,WAAY;AAMjB,YAAM,UAAU,CAAC;AAOjB,iBAAW,cAAc,WAAW,SAAS;AAC3C,cAAM,cAAc,WAAW,QAAQ,UAAU;AACjD,YAAI,CAAC,YAAa;AAClB,cAAM,UAAU,YAAY;AAC5B,cAAM,aAAa,YAAY;AAE/B,gBAAQ,UAA8B,IAAI;AAAA,UACxC;AAAA,UACA;AAAA,UACA,UAAW,YAAY,YAAY;AAAA,QAErC;AAAA,MAIF;AAEA,YAAM,QAAQ;AAAA,QACZ;AAAA,QAMA,SAAS,CAAC;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AAK;AAAA,MACR,QAAQ,EAAE,GAAG,KAAK,MAAM,QAAQ,CAAC,IAAI,GAAG,WAAW;AAAA,IAErD,CAAC;AAAA,EACH;AAAA,EAES,MAUP,MACA,OACA,UAWA;AACA,UAAM,eAAe,IAAI,aAAmC,MAAM,KAAK;AACvE,UAAM,SAAS,SAAS,YAAY;AACpC,UAAM,eAAe,kBAAkB,eAAe,SAAS;AAC/D,UAAM,aAAa,aAAa,MAAM;AAEtC,WAAO,IAAI,oBAQT;AAAA,MACA,GAAG,KAAK;AAAA,MACR,QAAQ,EAAE,GAAG,KAAK,MAAM,QAAQ,CAAC,IAAI,GAAG,WAAW;AAAA,IAErD,CAAC;AAAA,EACH;AACF;AAEO,SAAS,iBAEoB;AAClC,SAAO,IAAI,mBAA+B;AAC5C;","names":[]} |
| import { | ||
| computeMappings, | ||
| validateContract | ||
| } from "./chunk-BJOMVCU6.js"; | ||
| } from "./chunk-TALJTLJN.js"; | ||
| export { | ||
@@ -6,0 +6,0 @@ computeMappings, |
+4
-4
| { | ||
| "name": "@prisma-next/sql-contract-ts", | ||
| "version": "0.0.1", | ||
| "version": "0.1.0-pr.32.1", | ||
| "type": "module", | ||
@@ -10,5 +10,5 @@ "sideEffects": false, | ||
| "ts-toolbelt": "^9.6.0", | ||
| "@prisma-next/contract": "0.0.1", | ||
| "@prisma-next/sql-contract": "0.0.1", | ||
| "@prisma-next/contract-authoring": "0.0.1" | ||
| "@prisma-next/contract": "0.1.0-pr.32.1", | ||
| "@prisma-next/contract-authoring": "0.1.0-pr.32.1", | ||
| "@prisma-next/sql-contract": "0.1.0-pr.32.1" | ||
| }, | ||
@@ -15,0 +15,0 @@ "devDependencies": { |
+6
-7
@@ -36,12 +36,9 @@ # @prisma-next/sql-contract-ts | ||
| - **Composes generic core**: Uses `@prisma-next/contract-authoring` for generic builder state management (`TableBuilder`, `ModelBuilder`, `ContractBuilder` base class) | ||
| - **SQL-specific types**: Provides SQL-specific contract types (`SqlContract`, `SqlStorage`, `SqlMappings`) from `@prisma-next/sql-target` | ||
| - **SQL-specific types**: Provides SQL-specific contract types (`SqlContract`, `SqlStorage`, `SqlMappings`) from `@prisma-next/sql-contract/types` | ||
| - **SQL-specific validation**: Implements SQL-specific contract validation (`validateContractStructure`, `validateContractLogic`, `validateContract`) and normalization (`normalizeContract`) | ||
| - **SQL-specific build()**: Implements SQL-specific `build()` method in `SqlContractBuilder` that constructs `SqlContract` instances with SQL-specific structure (uniques, indexes, foreignKeys arrays) | ||
| ## Architecture | ||
| This package is part of the package layering architecture: | ||
| - **Location**: `packages/sql/authoring/sql-contract-ts` (SQL family namespace) | ||
| - **Ring**: SQL family namespace (can import from core, authoring, targets, and other SQL family packages) | ||
| - **Dependencies**: `@prisma-next/contract`, `@prisma-next/sql-target`, `arktype`, `ts-toolbelt` | ||
@@ -62,2 +59,4 @@ ## Exports | ||
| import { int4Column, textColumn } from '@prisma-next/adapter-postgres/column-types'; | ||
| const contract = defineContract<CodecTypes>() | ||
@@ -67,4 +66,4 @@ .target('postgres') | ||
| t | ||
| .column('id', { type: 'pg/int4@1', nullable: false }) | ||
| .column('email', { type: 'pg/text@1', nullable: false }) | ||
| .column('id', { type: int4Column, nullable: false }) | ||
| .column('email', { type: textColumn, nullable: false }) | ||
| .primaryKey(['id']), | ||
@@ -80,3 +79,3 @@ ) | ||
| import { validateContract } from '@prisma-next/sql-contract-ts/contract'; | ||
| import type { SqlContract, SqlStorage } from '@prisma-next/sql-target'; | ||
| import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types'; | ||
| import type { Contract } from './contract.d'; | ||
@@ -83,0 +82,0 @@ |
| // src/contract.ts | ||
| import { type } from "arktype"; | ||
| var StorageColumnSchema = type.declare().type({ | ||
| type: "string", | ||
| nullable: "boolean" | ||
| }); | ||
| var PrimaryKeySchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| var UniqueConstraintSchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| var IndexSchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| "name?": "string" | ||
| }); | ||
| var ForeignKeyReferencesSchema = type.declare().type({ | ||
| table: "string", | ||
| columns: type.string.array().readonly() | ||
| }); | ||
| var ForeignKeySchema = type.declare().type({ | ||
| columns: type.string.array().readonly(), | ||
| references: ForeignKeyReferencesSchema, | ||
| "name?": "string" | ||
| }); | ||
| var StorageTableSchema = type.declare().type({ | ||
| columns: type({ "[string]": StorageColumnSchema }), | ||
| "primaryKey?": PrimaryKeySchema, | ||
| uniques: UniqueConstraintSchema.array().readonly(), | ||
| indexes: IndexSchema.array().readonly(), | ||
| foreignKeys: ForeignKeySchema.array().readonly() | ||
| }); | ||
| var StorageSchema = type.declare().type({ | ||
| tables: type({ "[string]": StorageTableSchema }) | ||
| }); | ||
| var ModelFieldSchema = type.declare().type({ | ||
| column: "string" | ||
| }); | ||
| var ModelStorageSchema = type.declare().type({ | ||
| table: "string" | ||
| }); | ||
| var ModelSchema = type.declare().type({ | ||
| storage: ModelStorageSchema, | ||
| fields: type({ "[string]": ModelFieldSchema }), | ||
| relations: type({ "[string]": "unknown" }) | ||
| }); | ||
| var SqlContractSchema = type({ | ||
| "schemaVersion?": "'1'", | ||
| target: "string", | ||
| targetFamily: "'sql'", | ||
| coreHash: "string", | ||
| "profileHash?": "string", | ||
| "capabilities?": "Record<string, Record<string, boolean>>", | ||
| "extensions?": "Record<string, unknown>", | ||
| "meta?": "Record<string, unknown>", | ||
| "sources?": "Record<string, unknown>", | ||
| models: type({ "[string]": ModelSchema }), | ||
| storage: StorageSchema | ||
| }); | ||
| function validateContractStructure(value) { | ||
| const rawValue = value; | ||
| if (rawValue.targetFamily !== void 0 && rawValue.targetFamily !== "sql") { | ||
| throw new Error(`Unsupported target family: ${rawValue.targetFamily}`); | ||
| } | ||
| const contractResult = SqlContractSchema(value); | ||
| if (contractResult instanceof type.errors) { | ||
| const messages = contractResult.map((p) => p.message).join("; "); | ||
| throw new Error(`Contract structural validation failed: ${messages}`); | ||
| } | ||
| return contractResult; | ||
| } | ||
| function computeMappings(models, _storage, existingMappings) { | ||
| const modelToTable = {}; | ||
| const tableToModel = {}; | ||
| const fieldToColumn = {}; | ||
| const columnToField = {}; | ||
| for (const [modelName, model] of Object.entries(models)) { | ||
| const tableName = model.storage.table; | ||
| modelToTable[modelName] = tableName; | ||
| tableToModel[tableName] = modelName; | ||
| const modelFieldToColumn = {}; | ||
| for (const [fieldName, field] of Object.entries(model.fields)) { | ||
| const columnName = field.column; | ||
| modelFieldToColumn[fieldName] = columnName; | ||
| if (!columnToField[tableName]) { | ||
| columnToField[tableName] = {}; | ||
| } | ||
| columnToField[tableName][columnName] = fieldName; | ||
| } | ||
| fieldToColumn[modelName] = modelFieldToColumn; | ||
| } | ||
| return { | ||
| modelToTable: existingMappings?.modelToTable ?? modelToTable, | ||
| tableToModel: existingMappings?.tableToModel ?? tableToModel, | ||
| fieldToColumn: existingMappings?.fieldToColumn ?? fieldToColumn, | ||
| columnToField: existingMappings?.columnToField ?? columnToField, | ||
| codecTypes: existingMappings?.codecTypes ?? {}, | ||
| operationTypes: existingMappings?.operationTypes ?? {} | ||
| }; | ||
| } | ||
| function validateContractLogic(structurallyValidatedContract) { | ||
| const { storage, models } = structurallyValidatedContract; | ||
| const tableNames = new Set(Object.keys(storage.tables)); | ||
| for (const [modelName, modelUnknown] of Object.entries(models)) { | ||
| const model = modelUnknown; | ||
| if (!model.storage?.table) { | ||
| throw new Error(`Model "${modelName}" is missing storage.table`); | ||
| } | ||
| const tableName = model.storage.table; | ||
| if (!tableNames.has(tableName)) { | ||
| throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`); | ||
| } | ||
| const table = storage.tables[tableName]; | ||
| if (!table) { | ||
| throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`); | ||
| } | ||
| if (!table.primaryKey) { | ||
| throw new Error(`Model "${modelName}" table "${tableName}" is missing a primary key`); | ||
| } | ||
| const columnNames = new Set(Object.keys(table.columns)); | ||
| if (!model.fields) { | ||
| throw new Error(`Model "${modelName}" is missing fields`); | ||
| } | ||
| for (const [fieldName, fieldUnknown] of Object.entries(model.fields)) { | ||
| const field = fieldUnknown; | ||
| if (!field.column) { | ||
| throw new Error(`Model "${modelName}" field "${fieldName}" is missing column property`); | ||
| } | ||
| if (!columnNames.has(field.column)) { | ||
| throw new Error( | ||
| `Model "${modelName}" field "${fieldName}" references non-existent column "${field.column}" in table "${tableName}"` | ||
| ); | ||
| } | ||
| } | ||
| if (model.relations) { | ||
| for (const [relationName, relation] of Object.entries(model.relations)) { | ||
| if (typeof relation === "object" && relation !== null && "on" in relation && "to" in relation) { | ||
| const on = relation.on; | ||
| const cardinality = relation.cardinality; | ||
| if (on.parentCols && on.childCols) { | ||
| if (cardinality === "1:N") { | ||
| continue; | ||
| } | ||
| const hasMatchingFk = table.foreignKeys?.some((fk) => { | ||
| return fk.columns.length === on.childCols?.length && fk.columns.every((col, i) => col === on.childCols?.[i]) && fk.references.table && fk.references.columns.length === on.parentCols?.length && fk.references.columns.every((col, i) => col === on.parentCols?.[i]); | ||
| }); | ||
| if (!hasMatchingFk) { | ||
| throw new Error( | ||
| `Model "${modelName}" relation "${relationName}" does not have a corresponding foreign key in table "${tableName}"` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| for (const [tableName, table] of Object.entries(storage.tables)) { | ||
| const columnNames = new Set(Object.keys(table.columns)); | ||
| if (table.primaryKey) { | ||
| for (const colName of table.primaryKey.columns) { | ||
| if (!columnNames.has(colName)) { | ||
| throw new Error( | ||
| `Table "${tableName}" primaryKey references non-existent column "${colName}"` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| for (const unique of table.uniques) { | ||
| for (const colName of unique.columns) { | ||
| if (!columnNames.has(colName)) { | ||
| throw new Error( | ||
| `Table "${tableName}" unique constraint references non-existent column "${colName}"` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| for (const index of table.indexes) { | ||
| for (const colName of index.columns) { | ||
| if (!columnNames.has(colName)) { | ||
| throw new Error(`Table "${tableName}" index references non-existent column "${colName}"`); | ||
| } | ||
| } | ||
| } | ||
| for (const fk of table.foreignKeys) { | ||
| for (const colName of fk.columns) { | ||
| if (!columnNames.has(colName)) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey references non-existent column "${colName}"` | ||
| ); | ||
| } | ||
| } | ||
| if (!tableNames.has(fk.references.table)) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"` | ||
| ); | ||
| } | ||
| const referencedTable = storage.tables[fk.references.table]; | ||
| if (!referencedTable) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"` | ||
| ); | ||
| } | ||
| const referencedColumnNames = new Set(Object.keys(referencedTable.columns)); | ||
| for (const colName of fk.references.columns) { | ||
| if (!referencedColumnNames.has(colName)) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey references non-existent column "${colName}" in table "${fk.references.table}"` | ||
| ); | ||
| } | ||
| } | ||
| if (fk.columns.length !== fk.references.columns.length) { | ||
| throw new Error( | ||
| `Table "${tableName}" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| function normalizeContract(contract) { | ||
| const contractObj = contract; | ||
| let normalizedStorage = contractObj["storage"]; | ||
| if (normalizedStorage && typeof normalizedStorage === "object" && normalizedStorage !== null) { | ||
| const storage = normalizedStorage; | ||
| const tables = storage["tables"]; | ||
| if (tables) { | ||
| const normalizedTables = {}; | ||
| for (const [tableName, table] of Object.entries(tables)) { | ||
| const tableObj = table; | ||
| const columns = tableObj["columns"]; | ||
| if (columns) { | ||
| const normalizedColumns = {}; | ||
| for (const [columnName, column] of Object.entries(columns)) { | ||
| const columnObj = column; | ||
| normalizedColumns[columnName] = { | ||
| ...columnObj, | ||
| nullable: columnObj["nullable"] ?? false | ||
| }; | ||
| } | ||
| normalizedTables[tableName] = { | ||
| ...tableObj, | ||
| columns: normalizedColumns, | ||
| uniques: tableObj["uniques"] ?? [], | ||
| indexes: tableObj["indexes"] ?? [], | ||
| foreignKeys: tableObj["foreignKeys"] ?? [] | ||
| }; | ||
| } else { | ||
| normalizedTables[tableName] = tableObj; | ||
| } | ||
| } | ||
| normalizedStorage = { | ||
| ...storage, | ||
| tables: normalizedTables | ||
| }; | ||
| } | ||
| } | ||
| let normalizedModels = contractObj["models"]; | ||
| if (normalizedModels && typeof normalizedModels === "object" && normalizedModels !== null) { | ||
| const models = normalizedModels; | ||
| const normalizedModelsObj = {}; | ||
| for (const [modelName, model] of Object.entries(models)) { | ||
| const modelObj = model; | ||
| normalizedModelsObj[modelName] = { | ||
| ...modelObj, | ||
| relations: modelObj["relations"] ?? {} | ||
| }; | ||
| } | ||
| normalizedModels = normalizedModelsObj; | ||
| } | ||
| return { | ||
| ...contractObj, | ||
| models: normalizedModels, | ||
| relations: contractObj["relations"] ?? {}, | ||
| storage: normalizedStorage, | ||
| extensions: contractObj["extensions"] ?? {}, | ||
| capabilities: contractObj["capabilities"] ?? {}, | ||
| meta: contractObj["meta"] ?? {}, | ||
| sources: contractObj["sources"] ?? {} | ||
| }; | ||
| } | ||
| function validateContract(value) { | ||
| const normalized = normalizeContract(value); | ||
| const structurallyValid = validateContractStructure(normalized); | ||
| const contractForValidation = structurallyValid; | ||
| validateContractLogic(contractForValidation); | ||
| const existingMappings = contractForValidation.mappings; | ||
| const mappings = computeMappings( | ||
| contractForValidation.models, | ||
| contractForValidation.storage, | ||
| existingMappings | ||
| ); | ||
| const contractWithMappings = { | ||
| ...structurallyValid, | ||
| models: contractForValidation.models, | ||
| relations: contractForValidation.relations, | ||
| storage: contractForValidation.storage, | ||
| mappings | ||
| }; | ||
| return contractWithMappings; | ||
| } | ||
| export { | ||
| computeMappings, | ||
| validateContract | ||
| }; | ||
| //# sourceMappingURL=chunk-BJOMVCU6.js.map |
| {"version":3,"sources":["../../src/contract.ts"],"sourcesContent":["import type {\n ForeignKey,\n ForeignKeyReferences,\n Index,\n ModelDefinition,\n ModelField,\n ModelStorage,\n PrimaryKey,\n SqlContract,\n SqlMappings,\n SqlStorage,\n StorageColumn,\n StorageTable,\n UniqueConstraint,\n} from '@prisma-next/sql-contract/types';\nimport { type } from 'arktype';\nimport type { O } from 'ts-toolbelt';\n\n/**\n * Structural validation schema for SqlContract using Arktype.\n * This validates the shape and types of the contract structure.\n */\nconst StorageColumnSchema = type.declare<StorageColumn>().type({\n type: 'string',\n nullable: 'boolean',\n});\n\nconst PrimaryKeySchema = type.declare<PrimaryKey>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraint>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst IndexSchema = type.declare<Index>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst ForeignKeyReferencesSchema = type.declare<ForeignKeyReferences>().type({\n table: 'string',\n columns: type.string.array().readonly(),\n});\n\nconst ForeignKeySchema = type.declare<ForeignKey>().type({\n columns: type.string.array().readonly(),\n references: ForeignKeyReferencesSchema,\n 'name?': 'string',\n});\n\nconst StorageTableSchema = type.declare<StorageTable>().type({\n columns: type({ '[string]': StorageColumnSchema }),\n 'primaryKey?': PrimaryKeySchema,\n uniques: UniqueConstraintSchema.array().readonly(),\n indexes: IndexSchema.array().readonly(),\n foreignKeys: ForeignKeySchema.array().readonly(),\n});\n\nconst StorageSchema = type.declare<SqlStorage>().type({\n tables: type({ '[string]': StorageTableSchema }),\n});\n\nconst ModelFieldSchema = type.declare<ModelField>().type({\n column: 'string',\n});\n\nconst ModelStorageSchema = type.declare<ModelStorage>().type({\n table: 'string',\n});\n\nconst ModelSchema = type.declare<ModelDefinition>().type({\n storage: ModelStorageSchema,\n fields: type({ '[string]': ModelFieldSchema }),\n relations: type({ '[string]': 'unknown' }),\n});\n\n/**\n * Complete SqlContract schema for structural validation.\n * This validates the entire contract structure at once.\n */\nconst SqlContractSchema = type({\n 'schemaVersion?': \"'1'\",\n target: 'string',\n targetFamily: \"'sql'\",\n coreHash: 'string',\n 'profileHash?': 'string',\n 'capabilities?': 'Record<string, Record<string, boolean>>',\n 'extensions?': 'Record<string, unknown>',\n 'meta?': 'Record<string, unknown>',\n 'sources?': 'Record<string, unknown>',\n models: type({ '[string]': ModelSchema }),\n storage: StorageSchema,\n});\n\n/**\n * Validates the structural shape of a SqlContract using Arktype.\n *\n * **Responsibility: Validation Only**\n * This function validates that the contract has the correct structure and types.\n * It does NOT normalize the contract - normalization must happen in the contract builder.\n *\n * The contract passed to this function must already be normalized (all required fields present).\n * If normalization is needed, it should be done by the contract builder before calling this function.\n *\n * This ensures all required fields are present and have the correct types.\n *\n * @param value - The contract value to validate (typically from a JSON import)\n * @returns The validated contract if structure is valid\n * @throws Error if the contract structure is invalid\n */\nfunction validateContractStructure<T extends SqlContract<SqlStorage>>(\n value: unknown,\n): O.Overwrite<T, { targetFamily: 'sql' }> {\n // Check targetFamily first to provide a clear error message for unsupported target families\n const rawValue = value as { targetFamily?: string };\n if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {\n /* c8 ignore next */\n throw new Error(`Unsupported target family: ${rawValue.targetFamily}`);\n }\n\n const contractResult = SqlContractSchema(value);\n\n if (contractResult instanceof type.errors) {\n const messages = contractResult.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Contract structural validation failed: ${messages}`);\n }\n\n // After validation, contractResult matches the schema and preserves the input structure\n // TypeScript needs an assertion here due to exactOptionalPropertyTypes differences\n // between Arktype's inferred type and the generic T, but runtime-wise they're compatible\n return contractResult as O.Overwrite<T, { targetFamily: 'sql' }>;\n}\n\n/**\n * Computes mapping dictionaries from models and storage structures.\n * Assumes valid input - validation happens separately in validateContractLogic().\n *\n * @param models - Models object from contract\n * @param storage - Storage object from contract\n * @param existingMappings - Existing mappings from contract input (optional)\n * @returns Computed mappings dictionary\n */\nexport function computeMappings(\n models: Record<string, ModelDefinition>,\n _storage: SqlStorage,\n existingMappings?: Partial<SqlMappings>,\n): SqlMappings {\n const modelToTable: Record<string, string> = {};\n const tableToModel: Record<string, string> = {};\n const fieldToColumn: Record<string, Record<string, string>> = {};\n const columnToField: Record<string, Record<string, string>> = {};\n\n for (const [modelName, model] of Object.entries(models)) {\n const tableName = model.storage.table;\n modelToTable[modelName] = tableName;\n tableToModel[tableName] = modelName;\n\n const modelFieldToColumn: Record<string, string> = {};\n for (const [fieldName, field] of Object.entries(model.fields)) {\n const columnName = field.column;\n modelFieldToColumn[fieldName] = columnName;\n\n if (!columnToField[tableName]) {\n columnToField[tableName] = {};\n }\n columnToField[tableName][columnName] = fieldName;\n }\n fieldToColumn[modelName] = modelFieldToColumn;\n }\n\n // Preserve existing mappings if provided, otherwise use computed ones\n return {\n modelToTable: existingMappings?.modelToTable ?? modelToTable,\n tableToModel: existingMappings?.tableToModel ?? tableToModel,\n fieldToColumn: existingMappings?.fieldToColumn ?? fieldToColumn,\n columnToField: existingMappings?.columnToField ?? columnToField,\n codecTypes: existingMappings?.codecTypes ?? {},\n operationTypes: existingMappings?.operationTypes ?? {},\n };\n}\n\n/**\n * Validates logical consistency of a **structurally validated** SqlContract.\n * This checks that references (e.g., foreign keys, primary keys, uniques) point to storage objects that already exist.\n * Structural validation is expected to have already completed before this helper runs.\n *\n * @param structurallyValidatedContract - The contract whose structure has already been validated\n * @throws Error if logical validation fails\n */\nfunction validateContractLogic(structurallyValidatedContract: SqlContract<SqlStorage>): void {\n const { storage, models } = structurallyValidatedContract;\n const tableNames = new Set(Object.keys(storage.tables));\n\n // Validate models\n for (const [modelName, modelUnknown] of Object.entries(models)) {\n const model = modelUnknown as ModelDefinition;\n // Validate model has storage.table\n if (!model.storage?.table) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" is missing storage.table`);\n }\n\n const tableName = model.storage.table;\n\n // Validate model's table exists in storage\n if (!tableNames.has(tableName)) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" references non-existent table \"${tableName}\"`);\n }\n\n const table = storage.tables[tableName];\n if (!table) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" references non-existent table \"${tableName}\"`);\n }\n\n // Validate model's table has a primary key\n if (!table.primaryKey) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" table \"${tableName}\" is missing a primary key`);\n }\n\n const columnNames = new Set(Object.keys(table.columns));\n\n // Validate model fields\n if (!model.fields) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" is missing fields`);\n }\n\n for (const [fieldName, fieldUnknown] of Object.entries(model.fields)) {\n const field = fieldUnknown as { column: string };\n // Validate field has column property\n if (!field.column) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" field \"${fieldName}\" is missing column property`);\n }\n\n // Validate field's column exists in the model's backing table\n if (!columnNames.has(field.column)) {\n /* c8 ignore next */\n throw new Error(\n `Model \"${modelName}\" field \"${fieldName}\" references non-existent column \"${field.column}\" in table \"${tableName}\"`,\n );\n }\n }\n\n // Validate model relations have corresponding foreign keys\n if (model.relations) {\n for (const [relationName, relation] of Object.entries(model.relations)) {\n // For now, we'll do basic validation. Full FK validation can be added later\n // This would require checking that the relation's on.parentCols/childCols match FKs\n if (\n typeof relation === 'object' &&\n relation !== null &&\n 'on' in relation &&\n 'to' in relation\n ) {\n const on = relation.on as { parentCols?: string[]; childCols?: string[] };\n const cardinality = (relation as { cardinality?: string }).cardinality;\n if (on.parentCols && on.childCols) {\n // For 1:N relations, the foreign key is on the child table\n // For N:1 relations, the foreign key is on the parent table (this table)\n // For now, we'll skip validation for 1:N relations as the FK is on the child table\n // and we'll validate it when we process the child model\n if (cardinality === '1:N') {\n // Foreign key is on the child table, skip validation here\n // It will be validated when we process the child model\n continue;\n }\n\n // For N:1 relations, check that there's a foreign key matching this relation\n const hasMatchingFk = table.foreignKeys?.some((fk) => {\n return (\n fk.columns.length === on.childCols?.length &&\n fk.columns.every((col, i) => col === on.childCols?.[i]) &&\n fk.references.table &&\n fk.references.columns.length === on.parentCols?.length &&\n fk.references.columns.every((col, i) => col === on.parentCols?.[i])\n );\n });\n\n if (!hasMatchingFk) {\n /* c8 ignore next */\n throw new Error(\n `Model \"${modelName}\" relation \"${relationName}\" does not have a corresponding foreign key in table \"${tableName}\"`,\n );\n }\n }\n }\n }\n }\n }\n\n for (const [tableName, table] of Object.entries(storage.tables)) {\n const columnNames = new Set(Object.keys(table.columns));\n\n // Validate primaryKey references existing columns\n if (table.primaryKey) {\n for (const colName of table.primaryKey.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\n );\n }\n }\n }\n\n // Validate unique constraints reference existing columns\n for (const unique of table.uniques) {\n for (const colName of unique.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\n );\n }\n }\n }\n\n // Validate indexes reference existing columns\n for (const index of table.indexes) {\n for (const colName of index.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(`Table \"${tableName}\" index references non-existent column \"${colName}\"`);\n }\n }\n }\n\n // Validate foreignKeys reference existing tables and columns\n for (const fk of table.foreignKeys) {\n // Validate FK columns exist in the referencing table\n for (const colName of fk.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n );\n }\n }\n\n // Validate referenced table exists\n if (!tableNames.has(fk.references.table)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n );\n }\n\n // Validate referenced columns exist in the referenced table\n const referencedTable = storage.tables[fk.references.table];\n if (!referencedTable) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n );\n }\n const referencedColumnNames = new Set(Object.keys(referencedTable.columns));\n\n for (const colName of fk.references.columns) {\n if (!referencedColumnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\" in table \"${fk.references.table}\"`,\n );\n }\n }\n\n if (fk.columns.length !== fk.references.columns.length) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`,\n );\n }\n }\n }\n}\n\nexport function normalizeContract(contract: unknown): SqlContract<SqlStorage> {\n const contractObj = contract as Record<string, unknown>;\n\n // Only normalize if storage exists (validation will catch if it's missing)\n let normalizedStorage = contractObj['storage'];\n if (normalizedStorage && typeof normalizedStorage === 'object' && normalizedStorage !== null) {\n const storage = normalizedStorage as Record<string, unknown>;\n const tables = storage['tables'] as Record<string, unknown> | undefined;\n\n if (tables) {\n // Normalize storage tables\n const normalizedTables: Record<string, unknown> = {};\n for (const [tableName, table] of Object.entries(tables)) {\n const tableObj = table as Record<string, unknown>;\n const columns = tableObj['columns'] as Record<string, unknown> | undefined;\n\n if (columns) {\n // Normalize columns: add nullable: false if missing\n const normalizedColumns: Record<string, unknown> = {};\n for (const [columnName, column] of Object.entries(columns)) {\n const columnObj = column as Record<string, unknown>;\n normalizedColumns[columnName] = {\n ...columnObj,\n nullable: columnObj['nullable'] ?? false,\n };\n }\n\n // Normalize table arrays: add empty arrays if missing\n normalizedTables[tableName] = {\n ...tableObj,\n columns: normalizedColumns,\n uniques: tableObj['uniques'] ?? [],\n indexes: tableObj['indexes'] ?? [],\n foreignKeys: tableObj['foreignKeys'] ?? [],\n };\n } else {\n normalizedTables[tableName] = tableObj;\n }\n }\n\n normalizedStorage = {\n ...storage,\n tables: normalizedTables,\n };\n }\n }\n\n // Only normalize if models exists (validation will catch if it's missing)\n let normalizedModels = contractObj['models'];\n if (normalizedModels && typeof normalizedModels === 'object' && normalizedModels !== null) {\n const models = normalizedModels as Record<string, unknown>;\n const normalizedModelsObj: Record<string, unknown> = {};\n for (const [modelName, model] of Object.entries(models)) {\n const modelObj = model as Record<string, unknown>;\n normalizedModelsObj[modelName] = {\n ...modelObj,\n relations: modelObj['relations'] ?? {},\n };\n }\n normalizedModels = normalizedModelsObj;\n }\n\n // Normalize top-level fields: add empty objects if missing\n return {\n ...contractObj,\n models: normalizedModels,\n relations: contractObj['relations'] ?? {},\n storage: normalizedStorage,\n extensions: contractObj['extensions'] ?? {},\n capabilities: contractObj['capabilities'] ?? {},\n meta: contractObj['meta'] ?? {},\n sources: contractObj['sources'] ?? {},\n } as SqlContract<SqlStorage>;\n}\n\n/**\n * Validates that a JSON import conforms to the SqlContract structure\n * and returns a fully typed SqlContract.\n *\n * This function is specifically for validating JSON imports (e.g., from contract.json).\n * Contracts created via the builder API (defineContract) are already valid and should\n * not be passed to this function - use them directly without validation.\n *\n * Performs both structural validation (using Arktype) and logical validation\n * (ensuring all references are valid).\n *\n *\n * The type parameter `TContract` must be a fully-typed contract type (e.g., from `contract.d.ts`),\n * NOT a generic `SqlContract<SqlStorage>`.\n *\n * **Correct:**\n * ```typescript\n * import type { Contract } from './contract.d';\n * const contract = validateContract<Contract>(contractJson);\n * ```\n *\n * **Incorrect:**\n * ```typescript\n * import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';\n * const contract = validateContract<SqlContract<SqlStorage>>(contractJson);\n * // ❌ Types will be inferred as 'unknown' - this won't work!\n * ```\n *\n * The type parameter provides the specific table structure, column types, and model definitions.\n * This function validates the runtime structure matches the type, but does not infer types\n * from JSON (as JSON imports lose literal type information).\n *\n * @param value - The contract value to validate (must be from a JSON import, not a builder)\n * @returns A validated contract matching the TContract type\n * @throws Error if the contract structure or logic is invalid\n */\nexport function validateContract<TContract extends SqlContract<SqlStorage>>(\n value: unknown,\n): TContract {\n // Normalize contract first (add defaults for missing fields)\n const normalized = normalizeContract(value);\n\n const structurallyValid = validateContractStructure<SqlContract<SqlStorage>>(normalized);\n\n const contractForValidation = structurallyValid as SqlContract<SqlStorage>;\n\n // Validate contract logic (contracts must already have fully qualified type IDs)\n validateContractLogic(contractForValidation);\n\n // Extract existing mappings (optional - will be computed if missing)\n const existingMappings = (contractForValidation as { mappings?: Partial<SqlMappings> }).mappings;\n\n // Compute mappings from models and storage\n const mappings = computeMappings(\n contractForValidation.models as Record<string, ModelDefinition>,\n contractForValidation.storage,\n existingMappings,\n );\n\n // Add default values for optional metadata fields if missing\n const contractWithMappings = {\n ...structurallyValid,\n models: contractForValidation.models,\n relations: contractForValidation.relations,\n storage: contractForValidation.storage,\n mappings,\n };\n\n // Type assertion: The caller provides the strict type via TContract.\n // We validate the structure matches, but the precise types come from contract.d.ts\n return contractWithMappings as TContract;\n}\n"],"mappings":";AAeA,SAAS,YAAY;AAOrB,IAAM,sBAAsB,KAAK,QAAuB,EAAE,KAAK;AAAA,EAC7D,MAAM;AAAA,EACN,UAAU;AACZ,CAAC;AAED,IAAM,mBAAmB,KAAK,QAAoB,EAAE,KAAK;AAAA,EACvD,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,SAAS;AACX,CAAC;AAED,IAAM,yBAAyB,KAAK,QAA0B,EAAE,KAAK;AAAA,EACnE,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,SAAS;AACX,CAAC;AAED,IAAM,cAAc,KAAK,QAAe,EAAE,KAAK;AAAA,EAC7C,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,SAAS;AACX,CAAC;AAED,IAAM,6BAA6B,KAAK,QAA8B,EAAE,KAAK;AAAA,EAC3E,OAAO;AAAA,EACP,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AACxC,CAAC;AAED,IAAM,mBAAmB,KAAK,QAAoB,EAAE,KAAK;AAAA,EACvD,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,YAAY;AAAA,EACZ,SAAS;AACX,CAAC;AAED,IAAM,qBAAqB,KAAK,QAAsB,EAAE,KAAK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